eliminate type parameter from `Encodable` trait

This commit is contained in:
Andrew Poelstra 2019-07-11 14:56:37 +00:00
parent 87e7ebcf1b
commit 42960b959f
12 changed files with 209 additions and 131 deletions

View File

@ -25,12 +25,12 @@
//! //!
use std::default::Default; use std::default::Default;
use std::{error, fmt}; use std::{error, fmt, io};
#[cfg(feature = "serde")] use serde; #[cfg(feature = "serde")] use serde;
use blockdata::opcodes; use blockdata::opcodes;
use consensus::{encode, Decodable, Encodable, ReadExt, WriteExt}; use consensus::{encode, Decodable, Encodable, ReadExt};
use bitcoin_hashes::{hash160, sha256, Hash}; use bitcoin_hashes::{hash160, sha256, Hash};
#[cfg(feature="bitcoinconsensus")] use bitcoinconsensus; #[cfg(feature="bitcoinconsensus")] use bitcoinconsensus;
#[cfg(feature="bitcoinconsensus")] use std::convert; #[cfg(feature="bitcoinconsensus")] use std::convert;
@ -725,9 +725,12 @@ impl serde::Serialize for Script {
} }
// Network serialization // Network serialization
impl<S: WriteExt> Encodable<S> for Script { impl Encodable for Script {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<usize, encode::Error> { fn consensus_encode<S: io::Write>(
&self,
s: S,
) -> Result<usize, encode::Error> {
self.0.consensus_encode(s) self.0.consensus_encode(s)
} }
} }

View File

@ -25,7 +25,7 @@
use byteorder::{LittleEndian, WriteBytesExt}; use byteorder::{LittleEndian, WriteBytesExt};
use std::default::Default; use std::default::Default;
use std::fmt; use std::{fmt, io};
#[cfg(feature="bitcoinconsensus")] use std::collections::HashMap; #[cfg(feature="bitcoinconsensus")] use std::collections::HashMap;
use bitcoin_hashes::{self, sha256d, Hash}; use bitcoin_hashes::{self, sha256d, Hash};
@ -34,7 +34,7 @@ use bitcoin_hashes::hex::FromHex;
use util::hash::BitcoinHash; use util::hash::BitcoinHash;
#[cfg(feature="bitcoinconsensus")] use blockdata::script; #[cfg(feature="bitcoinconsensus")] use blockdata::script;
use blockdata::script::Script; use blockdata::script::Script;
use consensus::{encode, serialize, Decodable, Encodable, ReadExt, WriteExt}; use consensus::{encode, serialize, Decodable, Encodable, ReadExt};
use VarInt; use VarInt;
/// A reference to a transaction output /// A reference to a transaction output
@ -439,9 +439,12 @@ impl BitcoinHash for Transaction {
impl_consensus_encoding!(TxOut, value, script_pubkey); impl_consensus_encoding!(TxOut, value, script_pubkey);
impl<S: WriteExt> Encodable<S> for OutPoint { impl Encodable for OutPoint {
fn consensus_encode(&self, s: &mut S) -> Result <usize, encode::Error> { fn consensus_encode<S: io::Write>(
let len = self.txid.consensus_encode(s)?; &self,
mut s: S,
) -> Result<usize, encode::Error> {
let len = self.txid.consensus_encode(&mut s)?;
Ok(len + self.vout.consensus_encode(s)?) Ok(len + self.vout.consensus_encode(s)?)
} }
} }
@ -454,11 +457,14 @@ impl<D: ReadExt> Decodable<D> for OutPoint {
} }
} }
impl<S: WriteExt> Encodable<S> for TxIn { impl Encodable for TxIn {
fn consensus_encode(&self, s: &mut S) -> Result <usize, encode::Error> { fn consensus_encode<S: io::Write>(
&self,
mut s: S,
) -> Result<usize, encode::Error> {
let mut len = 0; let mut len = 0;
len += self.previous_output.consensus_encode(s)?; len += self.previous_output.consensus_encode(&mut s)?;
len += self.script_sig.consensus_encode(s)?; len += self.script_sig.consensus_encode(&mut s)?;
len += self.sequence.consensus_encode(s)?; len += self.sequence.consensus_encode(s)?;
Ok(len) Ok(len)
} }
@ -474,10 +480,13 @@ impl<D: ReadExt> Decodable<D> for TxIn {
} }
} }
impl<S: WriteExt> Encodable<S> for Transaction { impl Encodable for Transaction {
fn consensus_encode(&self, s: &mut S) -> Result <usize, encode::Error> { fn consensus_encode<S: io::Write>(
&self,
mut s: S,
) -> Result<usize, encode::Error> {
let mut len = 0; let mut len = 0;
len += self.version.consensus_encode(s)?; len += self.version.consensus_encode(&mut s)?;
let mut have_witness = self.input.is_empty(); let mut have_witness = self.input.is_empty();
for input in &self.input { for input in &self.input {
if !input.witness.is_empty() { if !input.witness.is_empty() {
@ -486,15 +495,15 @@ impl<S: WriteExt> Encodable<S> for Transaction {
} }
} }
if !have_witness { if !have_witness {
len += self.input.consensus_encode(s)?; len += self.input.consensus_encode(&mut s)?;
len += self.output.consensus_encode(s)?; len += self.output.consensus_encode(&mut s)?;
} else { } else {
len += 0u8.consensus_encode(s)?; len += 0u8.consensus_encode(&mut s)?;
len += 1u8.consensus_encode(s)?; len += 1u8.consensus_encode(&mut s)?;
len += self.input.consensus_encode(s)?; len += self.input.consensus_encode(&mut s)?;
len += self.output.consensus_encode(s)?; len += self.output.consensus_encode(&mut s)?;
for input in &self.input { for input in &self.input {
len += input.witness.consensus_encode(s)?; len += input.witness.consensus_encode(&mut s)?;
} }
} }
len += self.lock_time.consensus_encode(s)?; len += self.lock_time.consensus_encode(s)?;

View File

@ -199,18 +199,14 @@ impl From<psbt::Error> for Error {
} }
/// Encode an object into a vector /// Encode an object into a vector
pub fn serialize<T: ?Sized>(data: &T) -> Vec<u8> pub fn serialize<T: Encodable + ?Sized>(data: &T) -> Vec<u8> {
where T: Encodable<Cursor<Vec<u8>>>,
{
let mut encoder = Cursor::new(vec![]); let mut encoder = Cursor::new(vec![]);
data.consensus_encode(&mut encoder).unwrap(); data.consensus_encode(&mut encoder).unwrap();
encoder.into_inner() encoder.into_inner()
} }
/// Encode an object into a hex-encoded string /// Encode an object into a hex-encoded string
pub fn serialize_hex<T: ?Sized>(data: &T) -> String pub fn serialize_hex<T: Encodable + ?Sized>(data: &T) -> String {
where T: Encodable<Cursor<Vec<u8>>>
{
hex_encode(serialize(data)) hex_encode(serialize(data))
} }
@ -370,11 +366,11 @@ impl<R: Read> ReadExt for R {
pub const MAX_VEC_SIZE: usize = 32 * 1024 * 1024; pub const MAX_VEC_SIZE: usize = 32 * 1024 * 1024;
/// Data which can be encoded in a consensus-consistent way /// Data which can be encoded in a consensus-consistent way
pub trait Encodable<S: WriteExt> { pub trait Encodable {
/// Encode an object with a well-defined format, should only ever error if /// Encode an object with a well-defined format, should only ever error if
/// the underlying WriteExt errors. Returns the number of bytes written on /// the underlying `Write` errors. Returns the number of bytes written on
/// success /// success
fn consensus_encode(&self, e: &mut S) -> Result<usize, self::Error>; fn consensus_encode<W: io::Write>(&self, e: W) -> Result<usize, Error>;
} }
/// Data which can be encoded in a consensus-consistent way /// Data which can be encoded in a consensus-consistent way
@ -399,9 +395,12 @@ macro_rules! impl_int_encodable{
fn consensus_decode(d: &mut D) -> Result<$ty, self::Error> { d.$meth_dec().map($ty::from_le) } fn consensus_decode(d: &mut D) -> Result<$ty, self::Error> { d.$meth_dec().map($ty::from_le) }
} }
impl<S: WriteExt> Encodable<S> for $ty { impl Encodable for $ty {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<usize, self::Error> { fn consensus_encode<S: WriteExt>(
&self,
mut s: S,
) -> Result<usize, self::Error> {
s.$meth_enc(self.to_le())?; s.$meth_enc(self.to_le())?;
Ok(mem::size_of::<$ty>()) Ok(mem::size_of::<$ty>())
} }
@ -433,14 +432,29 @@ impl VarInt {
} }
} }
impl<S: WriteExt> Encodable<S> for VarInt { impl Encodable for VarInt {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<usize, self::Error> { fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, Error> {
match self.0 { match self.0 {
0...0xFC => { (self.0 as u8).consensus_encode(s)?; Ok(1) } 0...0xFC => {
0xFD...0xFFFF => { s.emit_u8(0xFD)?; (self.0 as u16).consensus_encode(s)?; Ok(3) } (self.0 as u8).consensus_encode(s)?;
0x10000...0xFFFFFFFF => { s.emit_u8(0xFE)?; (self.0 as u32).consensus_encode(s)?; Ok(5) } Ok(1)
_ => { s.emit_u8(0xFF)?; (self.0 as u64).consensus_encode(s)?; Ok(9) } },
0xFD...0xFFFF => {
s.emit_u8(0xFD)?;
(self.0 as u16).consensus_encode(s)?;
Ok(3)
},
0x10000...0xFFFFFFFF => {
s.emit_u8(0xFE)?;
(self.0 as u32).consensus_encode(s)?;
Ok(5)
},
_ => {
s.emit_u8(0xFF)?;
(self.0 as u64).consensus_encode(s)?;
Ok(9)
},
} }
} }
} }
@ -481,9 +495,9 @@ impl<D: ReadExt> Decodable<D> for VarInt {
// Booleans // Booleans
impl<S: WriteExt> Encodable<S> for bool { impl Encodable for bool {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<usize, self::Error> { fn consensus_encode<S: WriteExt>(&self, mut s: S) -> Result<usize, Error> {
s.emit_u8(if *self {1} else {0})?; s.emit_u8(if *self {1} else {0})?;
Ok(1) Ok(1)
} }
@ -495,11 +509,11 @@ impl<D: ReadExt> Decodable<D> for bool {
} }
// Strings // Strings
impl<S: WriteExt> Encodable<S> for String { impl Encodable for String {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<usize, self::Error> { fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, Error> {
let b = self.as_bytes(); let b = self.as_bytes();
let vi_len = VarInt(b.len() as u64).consensus_encode(s)?; let vi_len = VarInt(b.len() as u64).consensus_encode(&mut s)?;
s.emit_slice(&b)?; s.emit_slice(&b)?;
Ok(vi_len + b.len()) Ok(vi_len + b.len())
} }
@ -517,9 +531,12 @@ impl<D: ReadExt> Decodable<D> for String {
// Arrays // Arrays
macro_rules! impl_array { macro_rules! impl_array {
( $size:expr ) => ( ( $size:expr ) => (
impl<S: WriteExt> Encodable<S> for [u8; $size] { impl Encodable for [u8; $size] {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<usize, self::Error> { fn consensus_encode<S: WriteExt>(
&self,
mut s: S,
) -> Result<usize, Error> {
s.emit_slice(&self[..])?; s.emit_slice(&self[..])?;
Ok(self.len()) Ok(self.len())
} }
@ -555,10 +572,10 @@ impl<D: ReadExt> Decodable<D> for [u16; 8] {
} }
} }
impl<S: WriteExt> Encodable<S> for [u16; 8] { impl Encodable for [u16; 8] {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<usize, self::Error> { fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, Error> {
for c in self.iter() { c.consensus_encode(s)?; } for c in self.iter() { c.consensus_encode(&mut s)?; }
Ok(16) Ok(16)
} }
} }
@ -566,13 +583,16 @@ impl<S: WriteExt> Encodable<S> for [u16; 8] {
// Vectors // Vectors
macro_rules! impl_vec { macro_rules! impl_vec {
($type: ty) => { ($type: ty) => {
impl<S: WriteExt> Encodable<S> for Vec<$type> { impl Encodable for Vec<$type> {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<usize, self::Error> { fn consensus_encode<S: io::Write>(
&self,
mut s: S,
) -> Result<usize, Error> {
let mut len = 0; let mut len = 0;
len += VarInt(self.len() as u64).consensus_encode(s)?; len += VarInt(self.len() as u64).consensus_encode(&mut s)?;
for c in self.iter() { for c in self.iter() {
len += c.consensus_encode(s)?; len += c.consensus_encode(&mut s)?;
} }
Ok(len) Ok(len)
} }
@ -604,10 +624,10 @@ impl_vec!(Vec<u8>);
impl_vec!((u32, Address)); impl_vec!((u32, Address));
impl_vec!(u64); impl_vec!(u64);
impl<S: WriteExt> Encodable<S> for Vec<u8> { impl Encodable for Vec<u8> {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<usize, self::Error> { fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, Error> {
let vi_len = VarInt(self.len() as u64).consensus_encode(s)?; let vi_len = VarInt(self.len() as u64).consensus_encode(&mut s)?;
s.emit_slice(&self)?; s.emit_slice(&self)?;
Ok(vi_len + self.len()) Ok(vi_len + self.len())
} }
@ -628,10 +648,10 @@ impl<D: ReadExt> Decodable<D> for Vec<u8> {
} }
} }
impl<S: WriteExt> Encodable<S> for Box<[u8]> { impl Encodable for Box<[u8]> {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<usize, self::Error> { fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, Error> {
let vi_len = VarInt(self.len() as u64).consensus_encode(s)?; let vi_len = VarInt(self.len() as u64).consensus_encode(&mut s)?;
s.emit_slice(&self)?; s.emit_slice(&self)?;
Ok(vi_len + self.len()) Ok(vi_len + self.len())
} }
@ -660,11 +680,11 @@ fn sha2_checksum(data: &[u8]) -> [u8; 4] {
} }
// Checked data // Checked data
impl<S: WriteExt> Encodable<S> for CheckedData { impl Encodable for CheckedData {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<usize, self::Error> { fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, Error> {
(self.0.len() as u32).consensus_encode(s)?; (self.0.len() as u32).consensus_encode(&mut s)?;
sha2_checksum(&self.0).consensus_encode(s)?; sha2_checksum(&self.0).consensus_encode(&mut s)?;
s.emit_slice(&self.0)?; s.emit_slice(&self.0)?;
Ok(8 + self.0.len()) Ok(8 + self.0.len())
} }
@ -699,13 +719,16 @@ impl<D: ReadExt> Decodable<D> for CheckedData {
// Tuples // Tuples
macro_rules! tuple_encode { macro_rules! tuple_encode {
($($x:ident),*) => ( ($($x:ident),*) => (
impl <S: WriteExt, $($x: Encodable<S>),*> Encodable<S> for ($($x),*) { impl <$($x: Encodable),*> Encodable for ($($x),*) {
#[inline] #[inline]
#[allow(non_snake_case)] #[allow(non_snake_case)]
fn consensus_encode(&self, s: &mut S) -> Result<usize, self::Error> { fn consensus_encode<S: io::Write>(
&self,
mut s: S,
) -> Result<usize, self::Error> {
let &($(ref $x),*) = self; let &($(ref $x),*) = self;
let mut len = 0; let mut len = 0;
$(len += $x.consensus_encode(s)?;)* $(len += $x.consensus_encode(&mut s)?;)*
Ok(len) Ok(len)
} }
} }
@ -725,8 +748,8 @@ tuple_encode!(T0, T1, T2, T3);
tuple_encode!(T0, T1, T2, T3, T4, T5); tuple_encode!(T0, T1, T2, T3, T4, T5);
tuple_encode!(T0, T1, T2, T3, T4, T5, T6, T7); tuple_encode!(T0, T1, T2, T3, T4, T5, T6, T7);
impl<S: WriteExt> Encodable<S> for sha256d::Hash { impl Encodable for sha256d::Hash {
fn consensus_encode(&self, s: &mut S) -> Result<usize, self::Error> { fn consensus_encode<S: io::Write>(&self, s: S) -> Result<usize, Error> {
self.into_inner().consensus_encode(s) self.into_inner().consensus_encode(s)
} }
} }

View File

@ -18,11 +18,14 @@
macro_rules! impl_consensus_encoding { macro_rules! impl_consensus_encoding {
($thing:ident, $($field:ident),+) => ( ($thing:ident, $($field:ident),+) => (
impl<S: ::consensus::WriteExt> ::consensus::Encodable<S> for $thing { impl ::consensus::Encodable for $thing {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<usize, ::consensus::encode::Error> { fn consensus_encode<S: ::std::io::Write>(
&self,
mut s: S,
) -> Result<usize, ::consensus::encode::Error> {
let mut len = 0; let mut len = 0;
$(len += self.$field.consensus_encode(s)?;)+ $(len += self.$field.consensus_encode(&mut s)?;)+
Ok(len) Ok(len)
} }
} }

View File

@ -22,7 +22,7 @@ use std::io;
use std::fmt; use std::fmt;
use std::net::{SocketAddr, Ipv6Addr, SocketAddrV4, SocketAddrV6}; use std::net::{SocketAddr, Ipv6Addr, SocketAddrV4, SocketAddrV6};
use consensus::{encode, ReadExt, WriteExt}; use consensus::{encode, ReadExt};
use consensus::encode::{Decodable, Encodable}; use consensus::encode::{Decodable, Encodable};
/// A message which can be sent on the Bitcoin network /// A message which can be sent on the Bitcoin network
@ -72,13 +72,15 @@ fn addr_to_be(addr: [u16; 8]) -> [u16; 8] {
addr[4].to_be(), addr[5].to_be(), addr[6].to_be(), addr[7].to_be()] addr[4].to_be(), addr[5].to_be(), addr[6].to_be(), addr[7].to_be()]
} }
impl<S: WriteExt> Encodable<S> for Address { impl Encodable for Address {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<usize, encode::Error> { fn consensus_encode<S: io::Write>(
let mut len = 0; &self,
len += self.services.consensus_encode(s)?; mut s: S,
len += addr_to_be(self.address).consensus_encode(s)?; ) -> Result<usize, encode::Error> {
len += self.port.to_be().consensus_encode(s)?; let len = self.services.consensus_encode(&mut s)?
+ addr_to_be(self.address).consensus_encode(&mut s)?
+ self.port.to_be().consensus_encode(s)?;
Ok(len) Ok(len)
} }
} }

View File

@ -19,7 +19,7 @@
//! also defines (de)serialization routines for many primitives. //! also defines (de)serialization routines for many primitives.
//! //!
use std::{iter, mem}; use std::{io, iter, mem};
use std::io::Cursor; use std::io::Cursor;
use blockdata::block; use blockdata::block;
@ -30,16 +30,19 @@ use network::message_blockdata;
use network::message_filter; use network::message_filter;
use consensus::encode::{Decodable, Encodable}; use consensus::encode::{Decodable, Encodable};
use consensus::encode::{CheckedData, VarInt}; use consensus::encode::{CheckedData, VarInt};
use consensus::{encode, serialize, ReadExt, WriteExt}; use consensus::{encode, serialize, ReadExt};
use consensus::encode::MAX_VEC_SIZE; use consensus::encode::MAX_VEC_SIZE;
/// Serializer for command string /// Serializer for command string
#[derive(PartialEq, Eq, Clone, Debug)] #[derive(PartialEq, Eq, Clone, Debug)]
pub struct CommandString(pub String); pub struct CommandString(pub String);
impl<S: WriteExt> Encodable<S> for CommandString { impl Encodable for CommandString {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<usize, encode::Error> { fn consensus_encode<S: io::Write>(
&self,
s: S,
) -> Result<usize, encode::Error> {
let &CommandString(ref inner_str) = self; let &CommandString(ref inner_str) = self;
let mut rawbytes = [0u8; 12]; let mut rawbytes = [0u8; 12];
let strbytes = inner_str.as_bytes(); let strbytes = inner_str.as_bytes();
@ -160,24 +163,31 @@ impl RawNetworkMessage {
} }
struct HeaderSerializationWrapper<'a>(&'a Vec<block::BlockHeader>); struct HeaderSerializationWrapper<'a>(&'a Vec<block::BlockHeader>);
impl <'a, S: WriteExt> Encodable<S> for HeaderSerializationWrapper<'a> {
impl<'a> Encodable for HeaderSerializationWrapper<'a> {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<usize, encode::Error> { fn consensus_encode<S: io::Write>(
&self,
mut s: S,
) -> Result<usize, encode::Error> {
let mut len = 0; let mut len = 0;
len += VarInt(self.0.len() as u64).consensus_encode(s)?; len += VarInt(self.0.len() as u64).consensus_encode(&mut s)?;
for header in self.0.iter() { for header in self.0.iter() {
len += header.consensus_encode(s)?; len += header.consensus_encode(&mut s)?;
len += 0u8.consensus_encode(s)?; len += 0u8.consensus_encode(&mut s)?;
} }
Ok(len) Ok(len)
} }
} }
impl<S: WriteExt> Encodable<S> for RawNetworkMessage { impl Encodable for RawNetworkMessage {
fn consensus_encode(&self, s: &mut S) -> Result<usize, encode::Error> { fn consensus_encode<S: io::Write>(
&self,
mut s: S,
) -> Result<usize, encode::Error> {
let mut len = 0; let mut len = 0;
len += self.magic.consensus_encode(s)?; len += self.magic.consensus_encode(&mut s)?;
len += CommandString(self.command()).consensus_encode(s)?; len += CommandString(self.command()).consensus_encode(&mut s)?;
len += CheckedData(match self.payload { len += CheckedData(match self.payload {
NetworkMessage::Version(ref dat) => serialize(dat), NetworkMessage::Version(ref dat) => serialize(dat),
NetworkMessage::Addr(ref dat) => serialize(dat), NetworkMessage::Addr(ref dat) => serialize(dat),
@ -202,7 +212,7 @@ impl<S: WriteExt> Encodable<S> for RawNetworkMessage {
| NetworkMessage::SendHeaders | NetworkMessage::SendHeaders
| NetworkMessage::MemPool | NetworkMessage::MemPool
| NetworkMessage::GetAddr => vec![], | NetworkMessage::GetAddr => vec![],
}).consensus_encode(s)?; }).consensus_encode(&mut s)?;
Ok(len) Ok(len)
} }
} }

View File

@ -20,9 +20,11 @@
use network::constants; use network::constants;
use consensus::encode::{Decodable, Encodable}; use consensus::encode::{Decodable, Encodable};
use consensus::{encode, ReadExt, WriteExt}; use consensus::{encode, ReadExt};
use bitcoin_hashes::sha256d; use bitcoin_hashes::sha256d;
use std::io;
#[derive(PartialEq, Eq, Clone, Debug)] #[derive(PartialEq, Eq, Clone, Debug)]
/// The type of an inventory object /// The type of an inventory object
pub enum InvType { pub enum InvType {
@ -101,17 +103,20 @@ impl GetHeadersMessage {
impl_consensus_encoding!(GetHeadersMessage, version, locator_hashes, stop_hash); impl_consensus_encoding!(GetHeadersMessage, version, locator_hashes, stop_hash);
impl<S: WriteExt> Encodable<S> for Inventory { impl Encodable for Inventory {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<usize, encode::Error> { fn consensus_encode<S: io::Write>(
&self,
mut s: S,
) -> Result<usize, encode::Error> {
let inv_len = match self.inv_type { let inv_len = match self.inv_type {
InvType::Error => 0u32, InvType::Error => 0u32,
InvType::Transaction => 1, InvType::Transaction => 1,
InvType::Block => 2, InvType::Block => 2,
InvType::WitnessBlock => 0x40000002, InvType::WitnessBlock => 0x40000002,
InvType::WitnessTransaction => 0x40000001 InvType::WitnessTransaction => 0x40000001
}.consensus_encode(s)?; }.consensus_encode(&mut s)?;
Ok(inv_len + self.hash.consensus_encode(s)?) Ok(inv_len + self.hash.consensus_encode(&mut s)?)
} }
} }

View File

@ -57,12 +57,13 @@
//! ``` //! ```
use std::collections::HashSet; use std::collections::HashSet;
use std::io;
use bitcoin_hashes::{sha256d, Hash}; use bitcoin_hashes::{sha256d, Hash};
use blockdata::constants::{MAX_BLOCK_WEIGHT, MIN_TRANSACTION_WEIGHT}; use blockdata::constants::{MAX_BLOCK_WEIGHT, MIN_TRANSACTION_WEIGHT};
use consensus::encode::{Encodable, Error}; use consensus::encode::{Encodable, Error};
use consensus::{Decodable, ReadExt, WriteExt}; use consensus::{Decodable, ReadExt};
use util::hash::BitcoinHash; use util::hash::BitcoinHash;
use util::merkleblock::MerkleBlockError::*; use util::merkleblock::MerkleBlockError::*;
use {Block, BlockHeader}; use {Block, BlockHeader};
@ -353,10 +354,10 @@ impl PartialMerkleTree {
} }
} }
impl<S: WriteExt> Encodable<S> for PartialMerkleTree { impl Encodable for PartialMerkleTree {
fn consensus_encode(&self, s: &mut S) -> Result<usize, Error> { fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, Error> {
let ret = self.num_transactions.consensus_encode(s)? let ret = self.num_transactions.consensus_encode(&mut s)?
+ self.hashes.consensus_encode(s)?; + self.hashes.consensus_encode(&mut s)?;
let mut bytes: Vec<u8> = vec![0; (self.bits.len() + 7) / 8]; let mut bytes: Vec<u8> = vec![0; (self.bits.len() + 7) / 8];
for p in 0..self.bits.len() { for p in 0..self.bits.len() {
bytes[p / 8] |= (self.bits[p] as u8) << (p % 8) as u8; bytes[p / 8] |= (self.bits[p] as u8) << (p % 8) as u8;
@ -471,9 +472,11 @@ impl MerkleBlock {
} }
} }
impl<S: WriteExt> Encodable<S> for MerkleBlock { impl Encodable for MerkleBlock {
fn consensus_encode(&self, s: &mut S) -> Result<usize, Error> { fn consensus_encode<S: io::Write>(&self, mut s: S) -> Result<usize, Error> {
Ok(self.header.consensus_encode(s)? + self.txn.consensus_encode(s)?) let len = self.header.consensus_encode(&mut s)?
+ self.txn.consensus_encode(s)?;
Ok(len)
} }
} }

View File

@ -54,11 +54,17 @@ macro_rules! impl_psbt_serialize {
macro_rules! impl_psbtmap_consensus_encoding { macro_rules! impl_psbtmap_consensus_encoding {
($thing:ty) => { ($thing:ty) => {
impl<S: ::consensus::WriteExt> ::consensus::Encodable<S> for $thing { impl ::consensus::Encodable for $thing {
fn consensus_encode(&self, s: &mut S) -> Result<usize, ::consensus::encode::Error> { fn consensus_encode<S: ::std::io::Write>(
&self,
mut s: S,
) -> Result<usize, ::consensus::encode::Error> {
let mut len = 0; let mut len = 0;
for pair in ::util::psbt::Map::get_pairs(self)? { for pair in ::util::psbt::Map::get_pairs(self)? {
len += ::consensus::Encodable::consensus_encode(&pair, s)?; len += ::consensus::Encodable::consensus_encode(
&pair,
&mut s,
)?;
} }
Ok(len + ::consensus::Encodable::consensus_encode(&0x00_u8, s)?) Ok(len + ::consensus::Encodable::consensus_encode(&0x00_u8, s)?)

View File

@ -20,7 +20,9 @@
use blockdata::script::Script; use blockdata::script::Script;
use blockdata::transaction::Transaction; use blockdata::transaction::Transaction;
use consensus::{encode, Encodable, Decodable, WriteExt, ReadExt}; use consensus::{encode, Encodable, Decodable, ReadExt};
use std::io;
mod error; mod error;
pub use self::error::Error; pub use self::error::Error;
@ -88,21 +90,24 @@ impl PartiallySignedTransaction {
} }
} }
impl<S: WriteExt> Encodable<S> for PartiallySignedTransaction { impl Encodable for PartiallySignedTransaction {
fn consensus_encode(&self, s: &mut S) -> Result<usize, encode::Error> { fn consensus_encode<S: io::Write>(
&self,
mut s: S,
) -> Result<usize, encode::Error> {
let mut len = 0; let mut len = 0;
len += b"psbt".consensus_encode(s)?; len += b"psbt".consensus_encode(&mut s)?;
len += 0xff_u8.consensus_encode(s)?; len += 0xff_u8.consensus_encode(&mut s)?;
len += self.global.consensus_encode(s)?; len += self.global.consensus_encode(&mut s)?;
for i in &self.inputs { for i in &self.inputs {
len += i.consensus_encode(s)?; len += i.consensus_encode(&mut s)?;
} }
for i in &self.outputs { for i in &self.outputs {
len += i.consensus_encode(s)?; len += i.consensus_encode(&mut s)?;
} }
Ok(len) Ok(len)

View File

@ -17,10 +17,10 @@
//! Raw PSBT key-value pairs as defined at //! Raw PSBT key-value pairs as defined at
//! https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki. //! https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki.
use std::fmt; use std::{fmt, io};
use consensus::encode::{Decodable, Encodable, VarInt, MAX_VEC_SIZE}; use consensus::encode::{Decodable, Encodable, VarInt, MAX_VEC_SIZE};
use consensus::{encode, ReadExt, WriteExt}; use consensus::{encode, ReadExt};
use util::psbt::Error; use util::psbt::Error;
/// A PSBT key in its raw byte form. /// A PSBT key in its raw byte form.
@ -80,24 +80,30 @@ impl<D: ReadExt> Decodable<D> for Key {
} }
} }
impl<S: WriteExt> Encodable<S> for Key { impl Encodable for Key {
fn consensus_encode(&self, s: &mut S) -> Result<usize, encode::Error> { fn consensus_encode<S: io::Write>(
&self,
mut s: S,
) -> Result<usize, encode::Error> {
let mut len = 0; let mut len = 0;
len += VarInt((self.key.len() + 1) as u64).consensus_encode(s)?; len += VarInt((self.key.len() + 1) as u64).consensus_encode(&mut s)?;
len += self.type_value.consensus_encode(s)?; len += self.type_value.consensus_encode(&mut s)?;
for key in &self.key { for key in &self.key {
len += key.consensus_encode(s)? len += key.consensus_encode(&mut s)?
} }
Ok(len) Ok(len)
} }
} }
impl<S: WriteExt> Encodable<S> for Pair { impl Encodable for Pair {
fn consensus_encode(&self, s: &mut S) -> Result<usize, encode::Error> { fn consensus_encode<S: io::Write>(
let len = self.key.consensus_encode(s)?; &self,
mut s: S,
) -> Result<usize, encode::Error> {
let len = self.key.consensus_encode(&mut s)?;
Ok(len + self.value.consensus_encode(s)?) Ok(len + self.value.consensus_encode(s)?)
} }
} }

View File

@ -336,13 +336,16 @@ macro_rules! construct_uint {
} }
} }
impl<S: ::consensus::WriteExt> ::consensus::Encodable<S> for $name { impl ::consensus::Encodable for $name {
#[inline] #[inline]
fn consensus_encode(&self, s: &mut S) -> Result<usize, encode::Error> { fn consensus_encode<S: ::std::io::Write>(
&self,
mut s: S,
) -> Result<usize, encode::Error> {
let &$name(ref data) = self; let &$name(ref data) = self;
let mut len = 0; let mut len = 0;
for word in data.iter() { for word in data.iter() {
len += word.consensus_encode(s)?; len += word.consensus_encode(&mut s)?;
} }
Ok(len) Ok(len)
} }