f06d12455f bitcoin: Remove the custom sink (Tobin C. Harding)
b503aa1544 Run the formatter (Tobin C. Harding)
3ca55fb163 Remove qualifying path from Read and Write (Tobin C. Harding)
ebeb21fa7a Import fmt::Write using underscore (Tobin C. Harding)
e2dbcb1d28 Use W for writer generic type (Tobin C. Harding)
8704d9f0ae docs: Fix grammar (Tobin C. Harding)

Pull request description:

  A few cleanups to how we use the `io` crate, this is reasonably trivial but commit `a6c7e696 Remove qualifying path from Read and Write` is big, I have however gone to some effort to make sure it is easy to flick through the diff.

  Done in preparation for another go at the `BufRead` stuff.

ACKs for top commit:
  apoelstra:
    ACK f06d12455f
  Kixunil:
    ACK f06d12455f

Tree-SHA512: 751c489c67901c7563f1cc91f7761a4e3c276ae1981010338134e8c13200720ba69fcc74948c1dc1e6e65390197da0da27b2b69b86034029748321b404142cba
This commit is contained in:
Andrew Poelstra 2023-12-12 19:51:40 +00:00
commit 2a6b4c1f43
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
22 changed files with 155 additions and 165 deletions

View File

@ -12,6 +12,7 @@ use std::error;
use hashes::{sha256, siphash24, Hash}; use hashes::{sha256, siphash24, Hash};
use internals::impl_array_newtype; use internals::impl_array_newtype;
use io::{Read, Write};
use crate::consensus::encode::{self, Decodable, Encodable, VarInt}; use crate::consensus::encode::{self, Decodable, Encodable, VarInt};
use crate::internal_macros::{impl_bytes_newtype, impl_consensus_encoding}; use crate::internal_macros::{impl_bytes_newtype, impl_consensus_encoding};
@ -73,14 +74,14 @@ impl convert::AsRef<Transaction> for PrefilledTransaction {
impl Encodable for PrefilledTransaction { impl Encodable for PrefilledTransaction {
#[inline] #[inline]
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
Ok(VarInt::from(self.idx).consensus_encode(w)? + self.tx.consensus_encode(w)?) Ok(VarInt::from(self.idx).consensus_encode(w)? + self.tx.consensus_encode(w)?)
} }
} }
impl Decodable for PrefilledTransaction { impl Decodable for PrefilledTransaction {
#[inline] #[inline]
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
let idx = VarInt::consensus_decode(r)?.0; let idx = VarInt::consensus_decode(r)?.0;
let idx = u16::try_from(idx) let idx = u16::try_from(idx)
.map_err(|_| encode::Error::ParseFailed("BIP152 prefilled tx index out of bounds"))?; .map_err(|_| encode::Error::ParseFailed("BIP152 prefilled tx index out of bounds"))?;
@ -129,14 +130,14 @@ impl ShortId {
impl Encodable for ShortId { impl Encodable for ShortId {
#[inline] #[inline]
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
self.0.consensus_encode(w) self.0.consensus_encode(w)
} }
} }
impl Decodable for ShortId { impl Decodable for ShortId {
#[inline] #[inline]
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<ShortId, encode::Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<ShortId, encode::Error> {
Ok(ShortId(Decodable::consensus_decode(r)?)) Ok(ShortId(Decodable::consensus_decode(r)?))
} }
} }
@ -258,7 +259,7 @@ impl Encodable for BlockTransactionsRequest {
/// ///
/// Panics if the index overflows [`u64::MAX`]. This happens when [`BlockTransactionsRequest::indexes`] /// Panics if the index overflows [`u64::MAX`]. This happens when [`BlockTransactionsRequest::indexes`]
/// contains an entry with the value [`u64::MAX`] as `u64` overflows during differential encoding. /// contains an entry with the value [`u64::MAX`] as `u64` overflows during differential encoding.
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let mut len = self.block_hash.consensus_encode(w)?; let mut len = self.block_hash.consensus_encode(w)?;
// Manually encode indexes because they are differentially encoded VarInts. // Manually encode indexes because they are differentially encoded VarInts.
len += VarInt(self.indexes.len() as u64).consensus_encode(w)?; len += VarInt(self.indexes.len() as u64).consensus_encode(w)?;
@ -272,7 +273,7 @@ impl Encodable for BlockTransactionsRequest {
} }
impl Decodable for BlockTransactionsRequest { impl Decodable for BlockTransactionsRequest {
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
Ok(BlockTransactionsRequest { Ok(BlockTransactionsRequest {
block_hash: BlockHash::consensus_decode(r)?, block_hash: BlockHash::consensus_decode(r)?,
indexes: { indexes: {

View File

@ -43,6 +43,7 @@ use core::fmt::{self, Display, Formatter};
use hashes::{sha256d, siphash24, Hash}; use hashes::{sha256d, siphash24, Hash};
use internals::write_err; use internals::write_err;
use io::{Read, Write};
use crate::blockdata::block::{Block, BlockHash}; use crate::blockdata::block::{Block, BlockHash};
use crate::blockdata::script::Script; use crate::blockdata::script::Script;
@ -175,7 +176,7 @@ pub struct BlockFilterWriter<'a, W> {
writer: GcsFilterWriter<'a, W>, writer: GcsFilterWriter<'a, W>,
} }
impl<'a, W: io::Write> BlockFilterWriter<'a, W> { impl<'a, W: Write> BlockFilterWriter<'a, W> {
/// Creates a new [`BlockFilterWriter`] from `block`. /// Creates a new [`BlockFilterWriter`] from `block`.
pub fn new(writer: &'a mut W, block: &'a Block) -> BlockFilterWriter<'a, W> { pub fn new(writer: &'a mut W, block: &'a Block) -> BlockFilterWriter<'a, W> {
let block_hash_as_int = block.block_hash().to_byte_array(); let block_hash_as_int = block.block_hash().to_byte_array();
@ -244,7 +245,7 @@ impl BlockFilterReader {
where where
I: Iterator, I: Iterator,
I::Item: Borrow<[u8]>, I::Item: Borrow<[u8]>,
R: io::Read + ?Sized, R: Read + ?Sized,
{ {
self.reader.match_any(reader, query) self.reader.match_any(reader, query)
} }
@ -254,7 +255,7 @@ impl BlockFilterReader {
where where
I: Iterator, I: Iterator,
I::Item: Borrow<[u8]>, I::Item: Borrow<[u8]>,
R: io::Read + ?Sized, R: Read + ?Sized,
{ {
self.reader.match_all(reader, query) self.reader.match_all(reader, query)
} }
@ -277,7 +278,7 @@ impl GcsFilterReader {
where where
I: Iterator, I: Iterator,
I::Item: Borrow<[u8]>, I::Item: Borrow<[u8]>,
R: io::Read + ?Sized, R: Read + ?Sized,
{ {
let n_elements: VarInt = Decodable::consensus_decode(reader).unwrap_or(VarInt(0)); let n_elements: VarInt = Decodable::consensus_decode(reader).unwrap_or(VarInt(0));
// map hashes to [0, n_elements << grp] // map hashes to [0, n_elements << grp]
@ -320,7 +321,7 @@ impl GcsFilterReader {
where where
I: Iterator, I: Iterator,
I::Item: Borrow<[u8]>, I::Item: Borrow<[u8]>,
R: io::Read + ?Sized, R: Read + ?Sized,
{ {
let n_elements: VarInt = Decodable::consensus_decode(reader).unwrap_or(VarInt(0)); let n_elements: VarInt = Decodable::consensus_decode(reader).unwrap_or(VarInt(0));
// map hashes to [0, n_elements << grp] // map hashes to [0, n_elements << grp]
@ -371,7 +372,7 @@ pub struct GcsFilterWriter<'a, W> {
m: u64, m: u64,
} }
impl<'a, W: io::Write> GcsFilterWriter<'a, W> { impl<'a, W: Write> GcsFilterWriter<'a, W> {
/// Creates a new [`GcsFilterWriter`] wrapping a generic writer, with specific seed to siphash. /// Creates a new [`GcsFilterWriter`] wrapping a generic writer, with specific seed to siphash.
pub fn new(writer: &'a mut W, k0: u64, k1: u64, m: u64, p: u8) -> GcsFilterWriter<'a, W> { pub fn new(writer: &'a mut W, k0: u64, k1: u64, m: u64, p: u8) -> GcsFilterWriter<'a, W> {
GcsFilterWriter { filter: GcsFilter::new(k0, k1, p), writer, elements: BTreeSet::new(), m } GcsFilterWriter { filter: GcsFilter::new(k0, k1, p), writer, elements: BTreeSet::new(), m }
@ -429,7 +430,7 @@ impl GcsFilter {
n: u64, n: u64,
) -> Result<usize, io::Error> ) -> Result<usize, io::Error>
where where
W: io::Write, W: Write,
{ {
let mut wrote = 0; let mut wrote = 0;
let mut q = n >> self.p; let mut q = n >> self.p;
@ -446,7 +447,7 @@ impl GcsFilter {
/// Golomb-Rice decodes a number from a bit stream (parameter 2^k). /// Golomb-Rice decodes a number from a bit stream (parameter 2^k).
fn golomb_rice_decode<R>(&self, reader: &mut BitStreamReader<R>) -> Result<u64, io::Error> fn golomb_rice_decode<R>(&self, reader: &mut BitStreamReader<R>) -> Result<u64, io::Error>
where where
R: io::Read + ?Sized, R: Read + ?Sized,
{ {
let mut q = 0u64; let mut q = 0u64;
while reader.read(1)? == 1 { while reader.read(1)? == 1 {
@ -469,7 +470,7 @@ pub struct BitStreamReader<'a, R: ?Sized> {
reader: &'a mut R, reader: &'a mut R,
} }
impl<'a, R: io::Read + ?Sized> BitStreamReader<'a, R> { impl<'a, R: Read + ?Sized> BitStreamReader<'a, R> {
/// Creates a new [`BitStreamReader`] that reads bitwise from a given `reader`. /// Creates a new [`BitStreamReader`] that reads bitwise from a given `reader`.
pub fn new(reader: &'a mut R) -> BitStreamReader<'a, R> { pub fn new(reader: &'a mut R) -> BitStreamReader<'a, R> {
BitStreamReader { buffer: [0u8], reader, offset: 8 } BitStreamReader { buffer: [0u8], reader, offset: 8 }
@ -516,7 +517,7 @@ pub struct BitStreamWriter<'a, W> {
writer: &'a mut W, writer: &'a mut W,
} }
impl<'a, W: io::Write> BitStreamWriter<'a, W> { impl<'a, W: Write> BitStreamWriter<'a, W> {
/// Creates a new [`BitStreamWriter`] that writes bitwise to a given `writer`. /// Creates a new [`BitStreamWriter`] that writes bitwise to a given `writer`.
pub fn new(writer: &'a mut W) -> BitStreamWriter<'a, W> { pub fn new(writer: &'a mut W) -> BitStreamWriter<'a, W> {
BitStreamWriter { buffer: [0u8], writer, offset: 0 } BitStreamWriter { buffer: [0u8], writer, offset: 0 }

View File

@ -11,6 +11,7 @@
use core::fmt; use core::fmt;
use hashes::{sha256d, Hash, HashEngine}; use hashes::{sha256d, Hash, HashEngine};
use io::{Read, Write};
use super::Weight; use super::Weight;
use crate::blockdata::script; use crate::blockdata::script;
@ -200,13 +201,13 @@ impl Default for Version {
} }
impl Encodable for Version { impl Encodable for Version {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
self.0.consensus_encode(w) self.0.consensus_encode(w)
} }
} }
impl Decodable for Version { impl Decodable for Version {
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
Decodable::consensus_decode(r).map(Version) Decodable::consensus_decode(r).map(Version)
} }
} }

View File

@ -66,6 +66,7 @@ use core::fmt;
use core::ops::{Deref, DerefMut}; use core::ops::{Deref, DerefMut};
use hashes::{hash160, sha256}; use hashes::{hash160, sha256};
use io::{Read, Write};
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
use serde; use serde;
@ -579,21 +580,21 @@ impl<'de> serde::Deserialize<'de> for ScriptBuf {
impl Encodable for Script { impl Encodable for Script {
#[inline] #[inline]
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
crate::consensus::encode::consensus_encode_with_size(&self.0, w) crate::consensus::encode::consensus_encode_with_size(&self.0, w)
} }
} }
impl Encodable for ScriptBuf { impl Encodable for ScriptBuf {
#[inline] #[inline]
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
self.0.consensus_encode(w) self.0.consensus_encode(w)
} }
} }
impl Decodable for ScriptBuf { impl Decodable for ScriptBuf {
#[inline] #[inline]
fn consensus_decode_from_finite_reader<R: io::Read + ?Sized>( fn consensus_decode_from_finite_reader<R: Read + ?Sized>(
r: &mut R, r: &mut R,
) -> Result<Self, encode::Error> { ) -> Result<Self, encode::Error> {
Ok(ScriptBuf(Decodable::consensus_decode_from_finite_reader(r)?)) Ok(ScriptBuf(Decodable::consensus_decode_from_finite_reader(r)?))

View File

@ -16,6 +16,7 @@ use core::{cmp, fmt, str};
use hashes::{self, sha256d, Hash}; use hashes::{self, sha256d, Hash};
use internals::write_err; use internals::write_err;
use io::{Read, Write};
use super::Weight; use super::Weight;
use crate::blockdata::fee_rate::FeeRate; use crate::blockdata::fee_rate::FeeRate;
@ -1024,13 +1025,13 @@ impl Version {
} }
impl Encodable for Version { impl Encodable for Version {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
self.0.consensus_encode(w) self.0.consensus_encode(w)
} }
} }
impl Decodable for Version { impl Decodable for Version {
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
Decodable::consensus_decode(r).map(Version) Decodable::consensus_decode(r).map(Version)
} }
} }
@ -1038,13 +1039,13 @@ impl Decodable for Version {
impl_consensus_encoding!(TxOut, value, script_pubkey); impl_consensus_encoding!(TxOut, value, script_pubkey);
impl Encodable for OutPoint { impl Encodable for OutPoint {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let len = self.txid.consensus_encode(w)?; let len = self.txid.consensus_encode(w)?;
Ok(len + self.vout.consensus_encode(w)?) Ok(len + self.vout.consensus_encode(w)?)
} }
} }
impl Decodable for OutPoint { impl Decodable for OutPoint {
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
Ok(OutPoint { Ok(OutPoint {
txid: Decodable::consensus_decode(r)?, txid: Decodable::consensus_decode(r)?,
vout: Decodable::consensus_decode(r)?, vout: Decodable::consensus_decode(r)?,
@ -1053,7 +1054,7 @@ impl Decodable for OutPoint {
} }
impl Encodable for TxIn { impl Encodable for TxIn {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let mut len = 0; let mut len = 0;
len += self.previous_output.consensus_encode(w)?; len += self.previous_output.consensus_encode(w)?;
len += self.script_sig.consensus_encode(w)?; len += self.script_sig.consensus_encode(w)?;
@ -1063,7 +1064,7 @@ impl Encodable for TxIn {
} }
impl Decodable for TxIn { impl Decodable for TxIn {
#[inline] #[inline]
fn consensus_decode_from_finite_reader<R: io::Read + ?Sized>( fn consensus_decode_from_finite_reader<R: Read + ?Sized>(
r: &mut R, r: &mut R,
) -> Result<Self, encode::Error> { ) -> Result<Self, encode::Error> {
Ok(TxIn { Ok(TxIn {
@ -1076,19 +1077,19 @@ impl Decodable for TxIn {
} }
impl Encodable for Sequence { impl Encodable for Sequence {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
self.0.consensus_encode(w) self.0.consensus_encode(w)
} }
} }
impl Decodable for Sequence { impl Decodable for Sequence {
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
Decodable::consensus_decode(r).map(Sequence) Decodable::consensus_decode(r).map(Sequence)
} }
} }
impl Encodable for Transaction { impl Encodable for Transaction {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let mut len = 0; let mut len = 0;
len += self.version.consensus_encode(w)?; len += self.version.consensus_encode(w)?;
@ -1112,7 +1113,7 @@ impl Encodable for Transaction {
} }
impl Decodable for Transaction { impl Decodable for Transaction {
fn consensus_decode_from_finite_reader<R: io::Read + ?Sized>( fn consensus_decode_from_finite_reader<R: Read + ?Sized>(
r: &mut R, r: &mut R,
) -> Result<Self, encode::Error> { ) -> Result<Self, encode::Error> {
let version = Version::consensus_decode_from_finite_reader(r)?; let version = Version::consensus_decode_from_finite_reader(r)?;

View File

@ -20,7 +20,7 @@ use core::{fmt, mem, u32};
use hashes::{sha256, sha256d, Hash}; use hashes::{sha256, sha256d, Hash};
use internals::write_err; use internals::write_err;
use io::{Cursor, Read}; use io::{Cursor, Read, Write};
use crate::bip152::{PrefilledTransaction, ShortId}; use crate::bip152::{PrefilledTransaction, ShortId};
use crate::bip158::{FilterHash, FilterHeader}; use crate::bip158::{FilterHash, FilterHeader};
@ -137,7 +137,7 @@ pub fn deserialize_partial<T: Decodable>(data: &[u8]) -> Result<(T, usize), Erro
} }
/// Extensions of `Write` to encode data as per Bitcoin consensus. /// Extensions of `Write` to encode data as per Bitcoin consensus.
pub trait WriteExt: io::Write { pub trait WriteExt: Write {
/// Outputs a 64-bit unsigned integer. /// Outputs a 64-bit unsigned integer.
fn emit_u64(&mut self, v: u64) -> Result<(), io::Error>; fn emit_u64(&mut self, v: u64) -> Result<(), io::Error>;
/// Outputs a 32-bit unsigned integer. /// Outputs a 32-bit unsigned integer.
@ -164,7 +164,7 @@ pub trait WriteExt: io::Write {
} }
/// Extensions of `Read` to decode data as per Bitcoin consensus. /// Extensions of `Read` to decode data as per Bitcoin consensus.
pub trait ReadExt: io::Read { pub trait ReadExt: Read {
/// Reads a 64-bit unsigned integer. /// Reads a 64-bit unsigned integer.
fn read_u64(&mut self) -> Result<u64, Error>; fn read_u64(&mut self) -> Result<u64, Error>;
/// Reads a 32-bit unsigned integer. /// Reads a 32-bit unsigned integer.
@ -210,7 +210,7 @@ macro_rules! decoder_fn {
}; };
} }
impl<W: io::Write + ?Sized> WriteExt for W { impl<W: Write + ?Sized> WriteExt for W {
encoder_fn!(emit_u64, u64); encoder_fn!(emit_u64, u64);
encoder_fn!(emit_u32, u32); encoder_fn!(emit_u32, u32);
encoder_fn!(emit_u16, u16); encoder_fn!(emit_u16, u16);
@ -267,7 +267,7 @@ pub trait Encodable {
/// ///
/// The number of bytes written on success. The only errors returned are errors propagated from /// The number of bytes written on success. The only errors returned are errors propagated from
/// the writer. /// the writer.
fn consensus_encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error>; fn consensus_encode<W: Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error>;
} }
/// Data which can be encoded in a consensus-consistent way. /// Data which can be encoded in a consensus-consistent way.
@ -301,7 +301,7 @@ pub trait Decodable: Sized {
/// avoid creating redundant `Take` wrappers. Failure to do so might result only in a tiny /// avoid creating redundant `Take` wrappers. Failure to do so might result only in a tiny
/// performance hit. /// performance hit.
#[inline] #[inline]
fn consensus_decode_from_finite_reader<R: io::Read + ?Sized>( fn consensus_decode_from_finite_reader<R: Read + ?Sized>(
reader: &mut R, reader: &mut R,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
// This method is always strictly less general than, `consensus_decode`, so it's safe and // This method is always strictly less general than, `consensus_decode`, so it's safe and
@ -319,7 +319,7 @@ pub trait Decodable: Sized {
/// for types that override [`Self::consensus_decode_from_finite_reader`] /// for types that override [`Self::consensus_decode_from_finite_reader`]
/// instead. /// instead.
#[inline] #[inline]
fn consensus_decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, Error> { fn consensus_decode<R: Read + ?Sized>(reader: &mut R) -> Result<Self, Error> {
Self::consensus_decode_from_finite_reader(&mut reader.take(MAX_VEC_SIZE as u64)) Self::consensus_decode_from_finite_reader(&mut reader.take(MAX_VEC_SIZE as u64))
} }
} }
@ -357,16 +357,13 @@ macro_rules! impl_int_encodable {
($ty:ident, $meth_dec:ident, $meth_enc:ident) => { ($ty:ident, $meth_dec:ident, $meth_enc:ident) => {
impl Decodable for $ty { impl Decodable for $ty {
#[inline] #[inline]
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
ReadExt::$meth_dec(r) ReadExt::$meth_dec(r)
} }
} }
impl Encodable for $ty { impl Encodable for $ty {
#[inline] #[inline]
fn consensus_encode<W: io::Write + ?Sized>( fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
&self,
w: &mut W,
) -> Result<usize, io::Error> {
w.$meth_enc(*self)?; w.$meth_enc(*self)?;
Ok(mem::size_of::<$ty>()) Ok(mem::size_of::<$ty>())
} }
@ -416,7 +413,7 @@ impl_var_int_from!(u8, u16, u32, u64, usize);
impl Encodable for VarInt { impl Encodable for VarInt {
#[inline] #[inline]
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
match self.0 { match self.0 {
0..=0xFC => { 0..=0xFC => {
(self.0 as u8).consensus_encode(w)?; (self.0 as u8).consensus_encode(w)?;
@ -443,7 +440,7 @@ impl Encodable for VarInt {
impl Decodable for VarInt { impl Decodable for VarInt {
#[inline] #[inline]
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
let n = ReadExt::read_u8(r)?; let n = ReadExt::read_u8(r)?;
match n { match n {
0xFF => { 0xFF => {
@ -477,7 +474,7 @@ impl Decodable for VarInt {
impl Encodable for bool { impl Encodable for bool {
#[inline] #[inline]
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
w.emit_bool(*self)?; w.emit_bool(*self)?;
Ok(1) Ok(1)
} }
@ -485,14 +482,14 @@ impl Encodable for bool {
impl Decodable for bool { impl Decodable for bool {
#[inline] #[inline]
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<bool, Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<bool, Error> {
ReadExt::read_bool(r) ReadExt::read_bool(r)
} }
} }
impl Encodable for String { impl Encodable for String {
#[inline] #[inline]
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let b = self.as_bytes(); let b = self.as_bytes();
let vi_len = VarInt(b.len() as u64).consensus_encode(w)?; let vi_len = VarInt(b.len() as u64).consensus_encode(w)?;
w.emit_slice(b)?; w.emit_slice(b)?;
@ -502,7 +499,7 @@ impl Encodable for String {
impl Decodable for String { impl Decodable for String {
#[inline] #[inline]
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<String, Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<String, Error> {
String::from_utf8(Decodable::consensus_decode(r)?) String::from_utf8(Decodable::consensus_decode(r)?)
.map_err(|_| self::Error::ParseFailed("String was not valid UTF8")) .map_err(|_| self::Error::ParseFailed("String was not valid UTF8"))
} }
@ -510,7 +507,7 @@ impl Decodable for String {
impl Encodable for Cow<'static, str> { impl Encodable for Cow<'static, str> {
#[inline] #[inline]
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let b = self.as_bytes(); let b = self.as_bytes();
let vi_len = VarInt(b.len() as u64).consensus_encode(w)?; let vi_len = VarInt(b.len() as u64).consensus_encode(w)?;
w.emit_slice(b)?; w.emit_slice(b)?;
@ -520,7 +517,7 @@ impl Encodable for Cow<'static, str> {
impl Decodable for Cow<'static, str> { impl Decodable for Cow<'static, str> {
#[inline] #[inline]
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Cow<'static, str>, Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Cow<'static, str>, Error> {
String::from_utf8(Decodable::consensus_decode(r)?) String::from_utf8(Decodable::consensus_decode(r)?)
.map_err(|_| self::Error::ParseFailed("String was not valid UTF8")) .map_err(|_| self::Error::ParseFailed("String was not valid UTF8"))
.map(Cow::Owned) .map(Cow::Owned)
@ -542,7 +539,7 @@ macro_rules! impl_array {
impl Decodable for [u8; $size] { impl Decodable for [u8; $size] {
#[inline] #[inline]
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
let mut ret = [0; $size]; let mut ret = [0; $size];
r.read_slice(&mut ret)?; r.read_slice(&mut ret)?;
Ok(ret) Ok(ret)
@ -563,7 +560,7 @@ impl_array!(33);
impl Decodable for [u16; 8] { impl Decodable for [u16; 8] {
#[inline] #[inline]
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
let mut res = [0; 8]; let mut res = [0; 8];
for item in &mut res { for item in &mut res {
*item = Decodable::consensus_decode(r)?; *item = Decodable::consensus_decode(r)?;
@ -574,7 +571,7 @@ impl Decodable for [u16; 8] {
impl Encodable for [u16; 8] { impl Encodable for [u16; 8] {
#[inline] #[inline]
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
for c in self.iter() { for c in self.iter() {
c.consensus_encode(w)?; c.consensus_encode(w)?;
} }
@ -586,10 +583,7 @@ macro_rules! impl_vec {
($type: ty) => { ($type: ty) => {
impl Encodable for Vec<$type> { impl Encodable for Vec<$type> {
#[inline] #[inline]
fn consensus_encode<W: io::Write + ?Sized>( fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
&self,
w: &mut W,
) -> Result<usize, io::Error> {
let mut len = 0; let mut len = 0;
len += VarInt(self.len() as u64).consensus_encode(w)?; len += VarInt(self.len() as u64).consensus_encode(w)?;
for c in self.iter() { for c in self.iter() {
@ -601,7 +595,7 @@ macro_rules! impl_vec {
impl Decodable for Vec<$type> { impl Decodable for Vec<$type> {
#[inline] #[inline]
fn consensus_decode_from_finite_reader<R: io::Read + ?Sized>( fn consensus_decode_from_finite_reader<R: Read + ?Sized>(
r: &mut R, r: &mut R,
) -> Result<Self, Error> { ) -> Result<Self, Error> {
let len = VarInt::consensus_decode_from_finite_reader(r)?.0; let len = VarInt::consensus_decode_from_finite_reader(r)?.0;
@ -643,7 +637,7 @@ impl_vec!((u32, Address));
#[cfg(feature = "std")] #[cfg(feature = "std")]
impl_vec!(AddrV2Message); impl_vec!(AddrV2Message);
pub(crate) fn consensus_encode_with_size<W: io::Write + ?Sized>( pub(crate) fn consensus_encode_with_size<W: Write + ?Sized>(
data: &[u8], data: &[u8],
w: &mut W, w: &mut W,
) -> Result<usize, io::Error> { ) -> Result<usize, io::Error> {
@ -662,7 +656,7 @@ struct ReadBytesFromFiniteReaderOpts {
/// This function relies on reader being bound in amount of data /// This function relies on reader being bound in amount of data
/// it returns for OOM protection. See [`Decodable::consensus_decode_from_finite_reader`]. /// it returns for OOM protection. See [`Decodable::consensus_decode_from_finite_reader`].
#[inline] #[inline]
fn read_bytes_from_finite_reader<D: io::Read + ?Sized>( fn read_bytes_from_finite_reader<D: Read + ?Sized>(
d: &mut D, d: &mut D,
mut opts: ReadBytesFromFiniteReaderOpts, mut opts: ReadBytesFromFiniteReaderOpts,
) -> Result<Vec<u8>, Error> { ) -> Result<Vec<u8>, Error> {
@ -684,14 +678,14 @@ fn read_bytes_from_finite_reader<D: io::Read + ?Sized>(
impl Encodable for Vec<u8> { impl Encodable for Vec<u8> {
#[inline] #[inline]
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
consensus_encode_with_size(self, w) consensus_encode_with_size(self, w)
} }
} }
impl Decodable for Vec<u8> { impl Decodable for Vec<u8> {
#[inline] #[inline]
fn consensus_decode_from_finite_reader<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> { fn consensus_decode_from_finite_reader<R: Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
let len = VarInt::consensus_decode(r)?.0 as usize; let len = VarInt::consensus_decode(r)?.0 as usize;
// most real-world vec of bytes data, wouldn't be larger than 128KiB // most real-world vec of bytes data, wouldn't be larger than 128KiB
let opts = ReadBytesFromFiniteReaderOpts { len, chunk_size: 128 * 1024 }; let opts = ReadBytesFromFiniteReaderOpts { len, chunk_size: 128 * 1024 };
@ -701,14 +695,14 @@ impl Decodable for Vec<u8> {
impl Encodable for Box<[u8]> { impl Encodable for Box<[u8]> {
#[inline] #[inline]
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
consensus_encode_with_size(self, w) consensus_encode_with_size(self, w)
} }
} }
impl Decodable for Box<[u8]> { impl Decodable for Box<[u8]> {
#[inline] #[inline]
fn consensus_decode_from_finite_reader<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> { fn consensus_decode_from_finite_reader<R: Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
<Vec<u8>>::consensus_decode_from_finite_reader(r).map(From::from) <Vec<u8>>::consensus_decode_from_finite_reader(r).map(From::from)
} }
} }
@ -721,7 +715,7 @@ fn sha2_checksum(data: &[u8]) -> [u8; 4] {
impl Encodable for CheckedData { impl Encodable for CheckedData {
#[inline] #[inline]
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
u32::try_from(self.data.len()) u32::try_from(self.data.len())
.expect("network message use u32 as length") .expect("network message use u32 as length")
.consensus_encode(w)?; .consensus_encode(w)?;
@ -733,7 +727,7 @@ impl Encodable for CheckedData {
impl Decodable for CheckedData { impl Decodable for CheckedData {
#[inline] #[inline]
fn consensus_decode_from_finite_reader<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> { fn consensus_decode_from_finite_reader<R: Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
let len = u32::consensus_decode_from_finite_reader(r)? as usize; let len = u32::consensus_decode_from_finite_reader(r)? as usize;
let checksum = <[u8; 4]>::consensus_decode_from_finite_reader(r)?; let checksum = <[u8; 4]>::consensus_decode_from_finite_reader(r)?;
@ -749,19 +743,19 @@ impl Decodable for CheckedData {
} }
impl<'a, T: Encodable> Encodable for &'a T { impl<'a, T: Encodable> Encodable for &'a T {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
(**self).consensus_encode(w) (**self).consensus_encode(w)
} }
} }
impl<'a, T: Encodable> Encodable for &'a mut T { impl<'a, T: Encodable> Encodable for &'a mut T {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
(**self).consensus_encode(w) (**self).consensus_encode(w)
} }
} }
impl<T: Encodable> Encodable for rc::Rc<T> { impl<T: Encodable> Encodable for rc::Rc<T> {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
(**self).consensus_encode(w) (**self).consensus_encode(w)
} }
} }
@ -769,7 +763,7 @@ impl<T: Encodable> Encodable for rc::Rc<T> {
/// Note: This will fail to compile on old Rust for targets that don't support atomics /// Note: This will fail to compile on old Rust for targets that don't support atomics
#[cfg(any(not(rust_v_1_60), target_has_atomic = "ptr"))] #[cfg(any(not(rust_v_1_60), target_has_atomic = "ptr"))]
impl<T: Encodable> Encodable for sync::Arc<T> { impl<T: Encodable> Encodable for sync::Arc<T> {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
(**self).consensus_encode(w) (**self).consensus_encode(w)
} }
} }
@ -779,7 +773,7 @@ macro_rules! tuple_encode {
impl <$($x: Encodable),*> Encodable for ($($x),*) { impl <$($x: Encodable),*> Encodable for ($($x),*) {
#[inline] #[inline]
#[allow(non_snake_case)] #[allow(non_snake_case)]
fn consensus_encode<W: io::Write + ?Sized>( fn consensus_encode<W: Write + ?Sized>(
&self, &self,
w: &mut W, w: &mut W,
) -> Result<usize, io::Error> { ) -> Result<usize, io::Error> {
@ -793,7 +787,7 @@ macro_rules! tuple_encode {
impl<$($x: Decodable),*> Decodable for ($($x),*) { impl<$($x: Decodable),*> Decodable for ($($x),*) {
#[inline] #[inline]
#[allow(non_snake_case)] #[allow(non_snake_case)]
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
Ok(($({let $x = Decodable::consensus_decode(r)?; $x }),*)) Ok(($({let $x = Decodable::consensus_decode(r)?; $x }),*))
} }
} }
@ -809,37 +803,37 @@ tuple_encode!(T0, T1, T2, T3, T4, T5, T6);
tuple_encode!(T0, T1, T2, T3, T4, T5, T6, T7); tuple_encode!(T0, T1, T2, T3, T4, T5, T6, T7);
impl Encodable for sha256d::Hash { impl Encodable for sha256d::Hash {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
self.as_byte_array().consensus_encode(w) self.as_byte_array().consensus_encode(w)
} }
} }
impl Decodable for sha256d::Hash { impl Decodable for sha256d::Hash {
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
Ok(Self::from_byte_array(<<Self as Hash>::Bytes>::consensus_decode(r)?)) Ok(Self::from_byte_array(<<Self as Hash>::Bytes>::consensus_decode(r)?))
} }
} }
impl Encodable for sha256::Hash { impl Encodable for sha256::Hash {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
self.as_byte_array().consensus_encode(w) self.as_byte_array().consensus_encode(w)
} }
} }
impl Decodable for sha256::Hash { impl Decodable for sha256::Hash {
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
Ok(Self::from_byte_array(<<Self as Hash>::Bytes>::consensus_decode(r)?)) Ok(Self::from_byte_array(<<Self as Hash>::Bytes>::consensus_decode(r)?))
} }
} }
impl Encodable for TapLeafHash { impl Encodable for TapLeafHash {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
self.as_byte_array().consensus_encode(w) self.as_byte_array().consensus_encode(w)
} }
} }
impl Decodable for TapLeafHash { impl Decodable for TapLeafHash {
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
Ok(Self::from_byte_array(<<Self as Hash>::Bytes>::consensus_decode(r)?)) Ok(Self::from_byte_array(<<Self as Hash>::Bytes>::consensus_decode(r)?))
} }
} }

View File

@ -12,6 +12,7 @@
use core::fmt; use core::fmt;
use core::marker::PhantomData; use core::marker::PhantomData;
use io::{Read, Write};
use serde::de::{SeqAccess, Unexpected, Visitor}; use serde::de::{SeqAccess, Unexpected, Visitor};
use serde::ser::SerializeSeq; use serde::ser::SerializeSeq;
use serde::{Deserializer, Serializer}; use serde::{Deserializer, Serializer};
@ -268,7 +269,7 @@ impl<'a, W: fmt::Write, E: EncodeBytes> IoWrapper<'a, W, E> {
fn actually_flush(&mut self) -> fmt::Result { self.encoder.flush(&mut self.writer) } fn actually_flush(&mut self) -> fmt::Result { self.encoder.flush(&mut self.writer) }
} }
impl<'a, W: fmt::Write, E: EncodeBytes> io::Write for IoWrapper<'a, W, E> { impl<'a, W: fmt::Write, E: EncodeBytes> Write for IoWrapper<'a, W, E> {
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> { fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
match self.encoder.encode_chunk(&mut self.writer, bytes) { match self.encoder.encode_chunk(&mut self.writer, bytes) {
Ok(()) => Ok(bytes.len()), Ok(()) => Ok(bytes.len()),
@ -338,7 +339,7 @@ struct BinWriter<S: SerializeSeq> {
error: Option<S::Error>, error: Option<S::Error>,
} }
impl<S: SerializeSeq> io::Write for BinWriter<S> { impl<S: SerializeSeq> Write for BinWriter<S> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.write_all(buf).map(|_| buf.len()) } fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.write_all(buf).map(|_| buf.len()) }
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
@ -441,7 +442,7 @@ impl<E: fmt::Debug, I: Iterator<Item = Result<u8, E>>> IterReader<E, I> {
} }
} }
impl<E: fmt::Debug, I: Iterator<Item = Result<u8, E>>> io::Read for IterReader<E, I> { impl<E: fmt::Debug, I: Iterator<Item = Result<u8, E>>> Read for IterReader<E, I> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let mut count = 0; let mut count = 0;
for (dst, src) in buf.iter_mut().zip(&mut self.iterator) { for (dst, src) in buf.iter_mut().zip(&mut self.iterator) {

View File

@ -5,13 +5,14 @@
//! This module provides keys used in Bitcoin that can be roundtrip //! This module provides keys used in Bitcoin that can be roundtrip
//! (de)serialized. //! (de)serialized.
use core::fmt::{self, Write}; use core::fmt::{self, Write as _};
use core::ops; use core::ops;
use core::str::FromStr; use core::str::FromStr;
use hashes::{hash160, Hash}; use hashes::{hash160, Hash};
use hex::FromHex; use hex::FromHex;
use internals::write_err; use internals::write_err;
use io::{Read, Write};
use crate::crypto::ecdsa; use crate::crypto::ecdsa;
use crate::internal_macros::impl_asref_push_bytes; use crate::internal_macros::impl_asref_push_bytes;
@ -70,7 +71,7 @@ impl PublicKey {
} }
/// Write the public key into a writer /// Write the public key into a writer
pub fn write_into<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<(), io::Error> { pub fn write_into<W: Write + ?Sized>(&self, writer: &mut W) -> Result<(), io::Error> {
self.with_serialized(|bytes| writer.write_all(bytes)) self.with_serialized(|bytes| writer.write_all(bytes))
} }
@ -78,7 +79,7 @@ impl PublicKey {
/// ///
/// This internally reads the first byte before reading the rest, so /// This internally reads the first byte before reading the rest, so
/// use of a `BufReader` is recommended. /// use of a `BufReader` is recommended.
pub fn read_from<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> { pub fn read_from<R: Read + ?Sized>(reader: &mut R) -> Result<Self, io::Error> {
let mut bytes = [0; 65]; let mut bytes = [0; 65];
reader.read_exact(&mut bytes[0..1])?; reader.read_exact(&mut bytes[0..1])?;

View File

@ -16,12 +16,13 @@ use core::{fmt, str};
use hashes::{hash_newtype, sha256, sha256d, sha256t_hash_newtype, Hash}; use hashes::{hash_newtype, sha256, sha256d, sha256t_hash_newtype, Hash};
use internals::write_err; use internals::write_err;
use io::Write;
use crate::blockdata::witness::Witness; use crate::blockdata::witness::Witness;
use crate::consensus::{encode, Encodable}; use crate::consensus::{encode, Encodable};
use crate::prelude::*; use crate::prelude::*;
use crate::taproot::{LeafVersion, TapLeafHash, TAPROOT_ANNEX_PREFIX}; use crate::taproot::{LeafVersion, TapLeafHash, TAPROOT_ANNEX_PREFIX};
use crate::{io, Amount, Script, ScriptBuf, Sequence, Transaction, TxIn, TxOut}; use crate::{Amount, Script, ScriptBuf, Sequence, Transaction, TxIn, TxOut};
/// Used for signature hash for invalid use of SIGHASH_SINGLE. /// Used for signature hash for invalid use of SIGHASH_SINGLE.
#[rustfmt::skip] #[rustfmt::skip]
@ -671,11 +672,11 @@ impl<R: Borrow<Transaction>> SighashCache<R> {
/// Destroys the cache and recovers the stored transaction. /// Destroys the cache and recovers the stored transaction.
pub fn into_transaction(self) -> R { self.tx } pub fn into_transaction(self) -> R { self.tx }
/// Encodes the BIP341 signing data for any flag type into a given object implementing a /// Encodes the BIP341 signing data for any flag type into a given object implementing the
/// [`io::Write`] trait. /// [`io::Write`] trait.
pub fn taproot_encode_signing_data_to<Write: io::Write + ?Sized, T: Borrow<TxOut>>( pub fn taproot_encode_signing_data_to<W: Write + ?Sized, T: Borrow<TxOut>>(
&mut self, &mut self,
writer: &mut Write, writer: &mut W,
input_index: usize, input_index: usize,
prevouts: &Prevouts<T>, prevouts: &Prevouts<T>,
annex: Option<Annex>, annex: Option<Annex>,
@ -854,15 +855,15 @@ impl<R: Borrow<Transaction>> SighashCache<R> {
Ok(TapSighash::from_engine(enc)) Ok(TapSighash::from_engine(enc))
} }
/// Encodes the BIP143 signing data for any flag type into a given object implementing a /// Encodes the BIP143 signing data for any flag type into a given object implementing the
/// [`std::io::Write`] trait. /// [`std::io::Write`] trait.
/// ///
/// `script_code` is dependent on the type of the spend transaction. For p2wpkh use /// `script_code` is dependent on the type of the spend transaction. For p2wpkh use
/// [`Script::p2wpkh_script_code`], for p2wsh just pass in the witness script. (Also see /// [`Script::p2wpkh_script_code`], for p2wsh just pass in the witness script. (Also see
/// [`Self::p2wpkh_signature_hash`] and [`SighashCache::p2wsh_signature_hash`].) /// [`Self::p2wpkh_signature_hash`] and [`SighashCache::p2wsh_signature_hash`].)
pub fn segwit_v0_encode_signing_data_to<Write: io::Write + ?Sized>( pub fn segwit_v0_encode_signing_data_to<W: Write + ?Sized>(
&mut self, &mut self,
writer: &mut Write, writer: &mut W,
input_index: usize, input_index: usize,
script_code: &Script, script_code: &Script,
value: Amount, value: Amount,
@ -984,9 +985,9 @@ impl<R: Borrow<Transaction>> SighashCache<R> {
/// ///
/// This function can't handle the SIGHASH_SINGLE bug internally, so it returns [`EncodeSigningDataResult`] /// This function can't handle the SIGHASH_SINGLE bug internally, so it returns [`EncodeSigningDataResult`]
/// that must be handled by the caller (see [`EncodeSigningDataResult::is_sighash_single_bug`]). /// that must be handled by the caller (see [`EncodeSigningDataResult::is_sighash_single_bug`]).
pub fn legacy_encode_signing_data_to<Write: io::Write + ?Sized, U: Into<u32>>( pub fn legacy_encode_signing_data_to<W: Write + ?Sized, U: Into<u32>>(
&self, &self,
writer: &mut Write, writer: &mut W,
input_index: usize, input_index: usize,
script_pubkey: &Script, script_pubkey: &Script,
sighash_type: U, sighash_type: U,
@ -1011,9 +1012,9 @@ impl<R: Borrow<Transaction>> SighashCache<R> {
return EncodeSigningDataResult::SighashSingleBug; return EncodeSigningDataResult::SighashSingleBug;
} }
fn encode_signing_data_to_inner<Write: io::Write + ?Sized>( fn encode_signing_data_to_inner<W: Write + ?Sized>(
self_: &Transaction, self_: &Transaction,
writer: &mut Write, writer: &mut W,
input_index: usize, input_index: usize,
script_pubkey: &Script, script_pubkey: &Script,
sighash_type: u32, sighash_type: u32,
@ -1239,7 +1240,7 @@ impl<'a> Annex<'a> {
} }
impl<'a> Encodable for Annex<'a> { impl<'a> Encodable for Annex<'a> {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
encode::consensus_encode_with_size(self.0, w) encode::consensus_encode_with_size(self.0, w)
} }
} }

View File

@ -140,27 +140,6 @@ pub use crate::{
taproot::{TapBranchTag, TapLeafHash, TapLeafTag, TapNodeHash, TapTweakHash, TapTweakTag}, taproot::{TapBranchTag, TapLeafHash, TapLeafTag, TapNodeHash, TapTweakHash, TapTweakTag},
}; };
#[cfg(not(feature = "std"))]
mod io_extras {
use crate::io;
/// A writer which will move data into the void.
pub struct Sink {
_priv: (),
}
/// Creates an instance of a writer which will successfully consume all data.
pub const fn sink() -> Sink { Sink { _priv: () } }
impl io::Write for Sink {
#[inline]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { Ok(buf.len()) }
#[inline]
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
}
#[rustfmt::skip] #[rustfmt::skip]
mod prelude { mod prelude {
#[cfg(all(not(feature = "std"), not(test)))] #[cfg(all(not(feature = "std"), not(test)))]
@ -178,12 +157,8 @@ mod prelude {
#[cfg(any(feature = "std", test))] #[cfg(any(feature = "std", test))]
pub use std::collections::{BTreeMap, BTreeSet, btree_map, BinaryHeap}; pub use std::collections::{BTreeMap, BTreeSet, btree_map, BinaryHeap};
#[cfg(feature = "std")]
pub use crate::io::sink; pub use crate::io::sink;
#[cfg(not(feature = "std"))]
pub use crate::io_extras::sink;
pub use hex::DisplayHex; pub use hex::DisplayHex;
} }

View File

@ -41,6 +41,7 @@
use core::fmt; use core::fmt;
use hashes::Hash; use hashes::Hash;
use io::{Read, Write};
use self::MerkleBlockError::*; use self::MerkleBlockError::*;
use crate::blockdata::block::{self, Block, TxMerkleNode}; use crate::blockdata::block::{self, Block, TxMerkleNode};
@ -143,14 +144,14 @@ impl MerkleBlock {
} }
impl Encodable for MerkleBlock { impl Encodable for MerkleBlock {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let len = self.header.consensus_encode(w)? + self.txn.consensus_encode(w)?; let len = self.header.consensus_encode(w)? + self.txn.consensus_encode(w)?;
Ok(len) Ok(len)
} }
} }
impl Decodable for MerkleBlock { impl Decodable for MerkleBlock {
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
Ok(MerkleBlock { Ok(MerkleBlock {
header: Decodable::consensus_decode(r)?, header: Decodable::consensus_decode(r)?,
txn: Decodable::consensus_decode(r)?, txn: Decodable::consensus_decode(r)?,
@ -433,7 +434,7 @@ impl PartialMerkleTree {
} }
impl Encodable for PartialMerkleTree { impl Encodable for PartialMerkleTree {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let mut ret = self.num_transactions.consensus_encode(w)?; let mut ret = self.num_transactions.consensus_encode(w)?;
ret += self.hashes.consensus_encode(w)?; ret += self.hashes.consensus_encode(w)?;
@ -451,7 +452,7 @@ impl Encodable for PartialMerkleTree {
} }
impl Decodable for PartialMerkleTree { impl Decodable for PartialMerkleTree {
fn consensus_decode_from_finite_reader<R: io::Read + ?Sized>( fn consensus_decode_from_finite_reader<R: Read + ?Sized>(
r: &mut R, r: &mut R,
) -> Result<Self, encode::Error> { ) -> Result<Self, encode::Error> {
let num_transactions: u32 = Decodable::consensus_decode(r)?; let num_transactions: u32 = Decodable::consensus_decode(r)?;

View File

@ -19,6 +19,7 @@ use core::cmp::min;
use core::iter; use core::iter;
use hashes::Hash; use hashes::Hash;
use io::Write;
use crate::consensus::encode::Encodable; use crate::consensus::encode::Encodable;
use crate::prelude::*; use crate::prelude::*;
@ -40,7 +41,7 @@ pub use self::block::{MerkleBlock, MerkleBlockError, PartialMerkleTree};
pub fn calculate_root_inline<T>(hashes: &mut [T]) -> Option<T> pub fn calculate_root_inline<T>(hashes: &mut [T]) -> Option<T>
where where
T: Hash + Encodable, T: Hash + Encodable,
<T as Hash>::Engine: io::Write, <T as Hash>::Engine: Write,
{ {
match hashes.len() { match hashes.len() {
0 => None, 0 => None,
@ -58,7 +59,7 @@ where
pub fn calculate_root<T, I>(mut hashes: I) -> Option<T> pub fn calculate_root<T, I>(mut hashes: I) -> Option<T>
where where
T: Hash + Encodable, T: Hash + Encodable,
<T as Hash>::Engine: io::Write, <T as Hash>::Engine: Write,
I: Iterator<Item = T>, I: Iterator<Item = T>,
{ {
let first = hashes.next()?; let first = hashes.next()?;
@ -90,7 +91,7 @@ where
fn merkle_root_r<T>(hashes: &mut [T]) -> T fn merkle_root_r<T>(hashes: &mut [T]) -> T
where where
T: Hash + Encodable, T: Hash + Encodable,
<T as Hash>::Engine: io::Write, <T as Hash>::Engine: Write,
{ {
if hashes.len() == 1 { if hashes.len() == 1 {
return hashes[0]; return hashes[0];

View File

@ -9,6 +9,8 @@
use core::{fmt, iter}; use core::{fmt, iter};
use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs}; use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6, ToSocketAddrs};
use io::{Read, Write};
use crate::consensus::encode::{self, Decodable, Encodable, ReadExt, VarInt, WriteExt}; use crate::consensus::encode::{self, Decodable, Encodable, ReadExt, VarInt, WriteExt};
use crate::p2p::ServiceFlags; use crate::p2p::ServiceFlags;
use crate::prelude::*; use crate::prelude::*;
@ -56,7 +58,7 @@ impl Address {
impl Encodable for Address { impl Encodable for Address {
#[inline] #[inline]
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let mut len = self.services.consensus_encode(w)?; let mut len = self.services.consensus_encode(w)?;
for word in &self.address { for word in &self.address {
@ -73,7 +75,7 @@ impl Encodable for Address {
impl Decodable for Address { impl Decodable for Address {
#[inline] #[inline]
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
Ok(Address { Ok(Address {
services: Decodable::consensus_decode(r)?, services: Decodable::consensus_decode(r)?,
address: read_be_address(r)?, address: read_be_address(r)?,
@ -83,12 +85,12 @@ impl Decodable for Address {
} }
/// Read a big-endian address from reader. /// Read a big-endian address from reader.
fn read_be_address<R: io::Read + ?Sized>(r: &mut R) -> Result<[u16; 8], encode::Error> { fn read_be_address<R: Read + ?Sized>(r: &mut R) -> Result<[u16; 8], encode::Error> {
let mut address = [0u16; 8]; let mut address = [0u16; 8];
let mut buf = [0u8; 2]; let mut buf = [0u8; 2];
for word in &mut address { for word in &mut address {
io::Read::read_exact(r, &mut buf)?; Read::read_exact(r, &mut buf)?;
*word = u16::from_be_bytes(buf) *word = u16::from_be_bytes(buf)
} }
Ok(address) Ok(address)
@ -140,8 +142,8 @@ pub enum AddrV2 {
} }
impl Encodable for AddrV2 { impl Encodable for AddrV2 {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
fn encode_addr<W: io::Write + ?Sized>( fn encode_addr<W: Write + ?Sized>(
w: &mut W, w: &mut W,
network: u8, network: u8,
bytes: &[u8], bytes: &[u8],
@ -165,7 +167,7 @@ impl Encodable for AddrV2 {
} }
impl Decodable for AddrV2 { impl Decodable for AddrV2 {
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
let network_id = u8::consensus_decode(r)?; let network_id = u8::consensus_decode(r)?;
let len = VarInt::consensus_decode(r)?.0; let len = VarInt::consensus_decode(r)?.0;
if len > 512 { if len > 512 {
@ -269,7 +271,7 @@ impl AddrV2Message {
} }
impl Encodable for AddrV2Message { impl Encodable for AddrV2Message {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let mut len = 0; let mut len = 0;
len += self.time.consensus_encode(w)?; len += self.time.consensus_encode(w)?;
len += VarInt(self.services.to_u64()).consensus_encode(w)?; len += VarInt(self.services.to_u64()).consensus_encode(w)?;
@ -283,7 +285,7 @@ impl Encodable for AddrV2Message {
} }
impl Decodable for AddrV2Message { impl Decodable for AddrV2Message {
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
Ok(AddrV2Message { Ok(AddrV2Message {
time: Decodable::consensus_decode(r)?, time: Decodable::consensus_decode(r)?,
services: ServiceFlags::from(VarInt::consensus_decode(r)?.0), services: ServiceFlags::from(VarInt::consensus_decode(r)?.0),

View File

@ -9,6 +9,7 @@
use core::{fmt, iter}; use core::{fmt, iter};
use hashes::{sha256d, Hash}; use hashes::{sha256d, Hash};
use io::{Read, Write};
use crate::blockdata::{block, transaction}; use crate::blockdata::{block, transaction};
use crate::consensus::encode::{self, CheckedData, Decodable, Encodable, VarInt}; use crate::consensus::encode::{self, CheckedData, Decodable, Encodable, VarInt};
@ -98,7 +99,7 @@ impl AsRef<str> for CommandString {
impl Encodable for CommandString { impl Encodable for CommandString {
#[inline] #[inline]
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let mut rawbytes = [0u8; 12]; let mut rawbytes = [0u8; 12];
let strbytes = self.0.as_bytes(); let strbytes = self.0.as_bytes();
debug_assert!(strbytes.len() <= 12); debug_assert!(strbytes.len() <= 12);
@ -109,7 +110,7 @@ impl Encodable for CommandString {
impl Decodable for CommandString { impl Decodable for CommandString {
#[inline] #[inline]
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
let rawbytes: [u8; 12] = Decodable::consensus_decode(r)?; let rawbytes: [u8; 12] = Decodable::consensus_decode(r)?;
let rv = iter::FromIterator::from_iter(rawbytes.iter().filter_map(|&u| { let rv = iter::FromIterator::from_iter(rawbytes.iter().filter_map(|&u| {
if u > 0 { if u > 0 {
@ -334,7 +335,7 @@ struct HeaderSerializationWrapper<'a>(&'a Vec<block::Header>);
impl<'a> Encodable for HeaderSerializationWrapper<'a> { impl<'a> Encodable for HeaderSerializationWrapper<'a> {
#[inline] #[inline]
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let mut len = 0; let mut len = 0;
len += VarInt::from(self.0.len()).consensus_encode(w)?; len += VarInt::from(self.0.len()).consensus_encode(w)?;
for header in self.0.iter() { for header in self.0.iter() {
@ -346,7 +347,7 @@ impl<'a> Encodable for HeaderSerializationWrapper<'a> {
} }
impl Encodable for NetworkMessage { impl Encodable for NetworkMessage {
fn consensus_encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> {
match self { match self {
NetworkMessage::Version(ref dat) => dat.consensus_encode(writer), NetworkMessage::Version(ref dat) => dat.consensus_encode(writer),
NetworkMessage::Addr(ref dat) => dat.consensus_encode(writer), NetworkMessage::Addr(ref dat) => dat.consensus_encode(writer),
@ -391,7 +392,7 @@ impl Encodable for NetworkMessage {
} }
impl Encodable for RawNetworkMessage { impl Encodable for RawNetworkMessage {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let mut len = 0; let mut len = 0;
len += self.magic.consensus_encode(w)?; len += self.magic.consensus_encode(w)?;
len += self.command().consensus_encode(w)?; len += self.command().consensus_encode(w)?;
@ -406,7 +407,7 @@ struct HeaderDeserializationWrapper(Vec<block::Header>);
impl Decodable for HeaderDeserializationWrapper { impl Decodable for HeaderDeserializationWrapper {
#[inline] #[inline]
fn consensus_decode_from_finite_reader<R: io::Read + ?Sized>( fn consensus_decode_from_finite_reader<R: Read + ?Sized>(
r: &mut R, r: &mut R,
) -> Result<Self, encode::Error> { ) -> Result<Self, encode::Error> {
let len = VarInt::consensus_decode(r)?.0; let len = VarInt::consensus_decode(r)?.0;
@ -425,13 +426,13 @@ impl Decodable for HeaderDeserializationWrapper {
} }
#[inline] #[inline]
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
Self::consensus_decode_from_finite_reader(&mut r.take(MAX_MSG_SIZE as u64)) Self::consensus_decode_from_finite_reader(&mut r.take(MAX_MSG_SIZE as u64))
} }
} }
impl Decodable for RawNetworkMessage { impl Decodable for RawNetworkMessage {
fn consensus_decode_from_finite_reader<R: io::Read + ?Sized>( fn consensus_decode_from_finite_reader<R: Read + ?Sized>(
r: &mut R, r: &mut R,
) -> Result<Self, encode::Error> { ) -> Result<Self, encode::Error> {
let magic = Decodable::consensus_decode_from_finite_reader(r)?; let magic = Decodable::consensus_decode_from_finite_reader(r)?;
@ -530,7 +531,7 @@ impl Decodable for RawNetworkMessage {
} }
#[inline] #[inline]
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
Self::consensus_decode_from_finite_reader(&mut r.take(MAX_MSG_SIZE as u64)) Self::consensus_decode_from_finite_reader(&mut r.take(MAX_MSG_SIZE as u64))
} }
} }

View File

@ -7,6 +7,7 @@
//! //!
use hashes::{sha256d, Hash as _}; use hashes::{sha256d, Hash as _};
use io::{Read, Write};
use crate::blockdata::block::BlockHash; use crate::blockdata::block::BlockHash;
use crate::blockdata::transaction::{Txid, Wtxid}; use crate::blockdata::transaction::{Txid, Wtxid};
@ -61,7 +62,7 @@ impl Inventory {
impl Encodable for Inventory { impl Encodable for Inventory {
#[inline] #[inline]
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
macro_rules! encode_inv { macro_rules! encode_inv {
($code:expr, $item:expr) => { ($code:expr, $item:expr) => {
u32::consensus_encode(&$code, w)? + $item.consensus_encode(w)? u32::consensus_encode(&$code, w)? + $item.consensus_encode(w)?
@ -82,7 +83,7 @@ impl Encodable for Inventory {
impl Decodable for Inventory { impl Decodable for Inventory {
#[inline] #[inline]
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
let inv_type: u32 = Decodable::consensus_decode(r)?; let inv_type: u32 = Decodable::consensus_decode(r)?;
Ok(match inv_type { Ok(match inv_type {
0 => Inventory::Error, 0 => Inventory::Error,

View File

@ -5,6 +5,8 @@
//! This module describes BIP37 Connection Bloom filtering network messages. //! This module describes BIP37 Connection Bloom filtering network messages.
//! //!
use io::{Read, Write};
use crate::consensus::{encode, Decodable, Encodable, ReadExt}; use crate::consensus::{encode, Decodable, Encodable, ReadExt};
use crate::internal_macros::impl_consensus_encoding; use crate::internal_macros::impl_consensus_encoding;
@ -35,7 +37,7 @@ pub enum BloomFlags {
} }
impl Encodable for BloomFlags { impl Encodable for BloomFlags {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
w.write_all(&[match self { w.write_all(&[match self {
BloomFlags::None => 0, BloomFlags::None => 0,
BloomFlags::All => 1, BloomFlags::All => 1,
@ -46,7 +48,7 @@ impl Encodable for BloomFlags {
} }
impl Decodable for BloomFlags { impl Decodable for BloomFlags {
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
Ok(match r.read_u8()? { Ok(match r.read_u8()? {
0 => BloomFlags::None, 0 => BloomFlags::None,
1 => BloomFlags::All, 1 => BloomFlags::All,

View File

@ -7,6 +7,7 @@
//! //!
use hashes::sha256d; use hashes::sha256d;
use io::{Read, Write};
use crate::consensus::{encode, Decodable, Encodable, ReadExt}; use crate::consensus::{encode, Decodable, Encodable, ReadExt};
use crate::internal_macros::impl_consensus_encoding; use crate::internal_macros::impl_consensus_encoding;
@ -102,14 +103,14 @@ pub enum RejectReason {
} }
impl Encodable for RejectReason { impl Encodable for RejectReason {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
w.write_all(&[*self as u8])?; w.write_all(&[*self as u8])?;
Ok(1) Ok(1)
} }
} }
impl Decodable for RejectReason { impl Decodable for RejectReason {
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
Ok(match r.read_u8()? { Ok(match r.read_u8()? {
0x01 => RejectReason::Malformed, 0x01 => RejectReason::Malformed,
0x10 => RejectReason::Invalid, 0x10 => RejectReason::Invalid,

View File

@ -25,6 +25,7 @@ use core::{fmt, ops};
use hex::FromHex; use hex::FromHex;
use internals::{debug_from_display, write_err}; use internals::{debug_from_display, write_err};
use io::{Read, Write};
use crate::consensus::encode::{self, Decodable, Encodable}; use crate::consensus::encode::{self, Decodable, Encodable};
use crate::prelude::{Borrow, BorrowMut, String, ToOwned}; use crate::prelude::{Borrow, BorrowMut, String, ToOwned};
@ -190,14 +191,14 @@ impl ops::BitXorAssign for ServiceFlags {
impl Encodable for ServiceFlags { impl Encodable for ServiceFlags {
#[inline] #[inline]
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
self.0.consensus_encode(w) self.0.consensus_encode(w)
} }
} }
impl Decodable for ServiceFlags { impl Decodable for ServiceFlags {
#[inline] #[inline]
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
Ok(ServiceFlags(Decodable::consensus_decode(r)?)) Ok(ServiceFlags(Decodable::consensus_decode(r)?))
} }
} }
@ -283,13 +284,13 @@ impl fmt::UpperHex for Magic {
} }
impl Encodable for Magic { impl Encodable for Magic {
fn consensus_encode<W: io::Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, writer: &mut W) -> Result<usize, io::Error> {
self.0.consensus_encode(writer) self.0.consensus_encode(writer)
} }
} }
impl Decodable for Magic { impl Decodable for Magic {
fn consensus_decode<R: io::Read + ?Sized>(reader: &mut R) -> Result<Self, encode::Error> { fn consensus_decode<R: Read + ?Sized>(reader: &mut R) -> Result<Self, encode::Error> {
Ok(Magic(Decodable::consensus_decode(reader)?)) Ok(Magic(Decodable::consensus_decode(reader)?))
} }
} }

View File

@ -70,7 +70,7 @@ impl Map for Psbt {
} }
impl Psbt { impl Psbt {
pub(crate) fn decode_global<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> { pub(crate) fn decode_global<R: Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
let mut r = r.take(MAX_VEC_SIZE as u64); let mut r = r.take(MAX_VEC_SIZE as u64);
let mut tx: Option<Transaction> = None; let mut tx: Option<Transaction> = None;
let mut version: Option<u32> = None; let mut version: Option<u32> = None;

View File

@ -8,6 +8,8 @@
use core::fmt; use core::fmt;
use io::{Read, Write};
use super::serialize::{Deserialize, Serialize}; use super::serialize::{Deserialize, Serialize};
use crate::consensus::encode::{ use crate::consensus::encode::{
self, deserialize, serialize, Decodable, Encodable, ReadExt, VarInt, WriteExt, MAX_VEC_SIZE, self, deserialize, serialize, Decodable, Encodable, ReadExt, VarInt, WriteExt, MAX_VEC_SIZE,
@ -72,7 +74,7 @@ impl fmt::Display for Key {
} }
impl Key { impl Key {
pub(crate) fn decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> { pub(crate) fn decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
let VarInt(byte_size): VarInt = Decodable::consensus_decode(r)?; let VarInt(byte_size): VarInt = Decodable::consensus_decode(r)?;
if byte_size == 0 { if byte_size == 0 {
@ -135,7 +137,7 @@ impl Deserialize for Pair {
} }
impl Pair { impl Pair {
pub(crate) fn decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, Error> { pub(crate) fn decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, Error> {
Ok(Pair { key: Key::decode(r)?, value: Decodable::consensus_decode(r)? }) Ok(Pair { key: Key::decode(r)?, value: Decodable::consensus_decode(r)? })
} }
} }
@ -144,7 +146,7 @@ impl<Subtype> Encodable for ProprietaryKey<Subtype>
where where
Subtype: Copy + From<u8> + Into<u8>, Subtype: Copy + From<u8> + Into<u8>,
{ {
fn consensus_encode<W: io::Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> { fn consensus_encode<W: Write + ?Sized>(&self, w: &mut W) -> Result<usize, io::Error> {
let mut len = self.prefix.consensus_encode(w)? + 1; let mut len = self.prefix.consensus_encode(w)? + 1;
w.emit_u8(self.subtype.into())?; w.emit_u8(self.subtype.into())?;
w.write_all(&self.key)?; w.write_all(&self.key)?;
@ -157,7 +159,7 @@ impl<Subtype> Decodable for ProprietaryKey<Subtype>
where where
Subtype: Copy + From<u8> + Into<u8>, Subtype: Copy + From<u8> + Into<u8>,
{ {
fn consensus_decode<R: io::Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> { fn consensus_decode<R: Read + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
let prefix = Vec::<u8>::consensus_decode(r)?; let prefix = Vec::<u8>::consensus_decode(r)?;
let subtype = Subtype::from(r.read_u8()?); let subtype = Subtype::from(r.read_u8()?);
let key = read_to_end(r)?; let key = read_to_end(r)?;
@ -194,7 +196,7 @@ where
} }
// core2 doesn't have read_to_end // core2 doesn't have read_to_end
pub(crate) fn read_to_end<D: io::Read + ?Sized>(d: &mut D) -> Result<Vec<u8>, io::Error> { pub(crate) fn read_to_end<D: Read + ?Sized>(d: &mut D) -> Result<Vec<u8>, io::Error> {
let mut result = vec![]; let mut result = vec![];
let mut buf = [0u8; 64]; let mut buf = [0u8; 64];
loop { loop {

View File

@ -14,6 +14,7 @@ use core::iter::FusedIterator;
use hashes::{sha256t_hash_newtype, Hash, HashEngine}; use hashes::{sha256t_hash_newtype, Hash, HashEngine};
use internals::write_err; use internals::write_err;
use io::Write;
use secp256k1::{self, Scalar, Secp256k1}; use secp256k1::{self, Scalar, Secp256k1};
use crate::consensus::Encodable; use crate::consensus::Encodable;
@ -1109,7 +1110,7 @@ impl ControlBlock {
/// # Returns /// # Returns
/// ///
/// The number of bytes written to the writer. /// The number of bytes written to the writer.
pub fn encode<Write: io::Write + ?Sized>(&self, writer: &mut Write) -> io::Result<usize> { pub fn encode<W: Write + ?Sized>(&self, writer: &mut W) -> io::Result<usize> {
let first_byte: u8 = let first_byte: u8 =
i32::from(self.output_key_parity) as u8 | self.leaf_version.to_consensus(); i32::from(self.output_key_parity) as u8 | self.leaf_version.to_consensus();
writer.write_all(&[first_byte])?; writer.write_all(&[first_byte])?;

View File

@ -6,7 +6,7 @@
//! We refer to the documentation on the types for more information. //! We refer to the documentation on the types for more information.
use core::cmp::Ordering; use core::cmp::Ordering;
use core::fmt::{self, Write}; use core::fmt::{self, Write as _};
use core::str::FromStr; use core::str::FromStr;
use core::{default, ops}; use core::{default, ops};