parity-zcash/p2p/src/io/read_any_message.rs

119 lines
3.4 KiB
Rust
Raw Normal View History

2019-06-28 14:27:46 -07:00
use bytes::Bytes;
use futures::{Async, Future, Poll};
use io::{read_header, ReadHeader};
use std::io;
2017-03-25 02:05:49 -07:00
use tokio_io::io::{read_exact, ReadExact};
use tokio_io::AsyncRead;
Prefix workspace crates with zebra- (#70) * Update license and author metadata in workspace crates. - ensure that the license field is set to GPL-3 for all GPL-3 licensed crates; - ensure that the author field is set to "Zcash Foundation", responsible for maintenance; - preserve the original authorship info in AUTHORS.md for human-readable history. Updating the author field ensures that all of the machine systems that read crate metadata list the ZF organization, not any single individual, as the maintainer of the crate. * Prefix all internal crate names with zebra-. This does not move the directories containing these crates to also have zebra- prefixes (for instance, zebra-chain instead of chain). I think that this would be preferable, but because it's a `git mv`, it will be simple to do later and leaving it out of this change makes it easier to see the renaming of all of the internal modules. * Remove git dependency from eth-secp256k1 * Avoid an error seemingly related to Deref coercions. This code caused an overflow while evaluating type constraints. As best as I can determine, the cause of the problem was something like so: the Rust implementation of the Bitcoin-specific hash function used in the Bloom filter doesn't operate on byte slices, but only on a `&mut R where R: Read`, so to hash a byte slice, you need to create a mutable copy of the input slice which can be consumed as a `Read` implementation by the hash function; the previous version of this code created a slice copy using a `Deref` coercion instead of `.clone()`, and when a tokio update added new trait impls, the type inference for the `Deref` coercion exploded (somehow -- I'm not sure about the last part?). This commit avoids the problem by manually cloning the input slice.
2019-07-02 12:07:06 -07:00
use zebra_crypto::checksum;
use zebra_message::{Command, Error, MessageHeader, MessageResult};
use zebra_network::Magic;
2019-06-28 14:27:46 -07:00
pub fn read_any_message<A>(a: A, magic: Magic) -> ReadAnyMessage<A>
where
A: AsyncRead,
{
ReadAnyMessage {
state: ReadAnyMessageState::ReadHeader(read_header(a, magic)),
}
}
pub enum ReadAnyMessageState<A> {
2019-06-28 14:27:46 -07:00
ReadHeader(ReadHeader<A>),
ReadPayload {
header: MessageHeader,
future: ReadExact<A, Bytes>,
},
}
pub struct ReadAnyMessage<A> {
2019-06-28 14:27:46 -07:00
state: ReadAnyMessageState<A>,
}
2019-06-28 14:27:46 -07:00
impl<A> Future for ReadAnyMessage<A>
where
A: AsyncRead,
{
type Item = MessageResult<(Command, Bytes)>;
type Error = io::Error;
2019-06-28 14:27:46 -07:00
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
loop {
let next_state = match self.state {
ReadAnyMessageState::ReadHeader(ref mut header) => {
let (stream, header) = try_ready!(header.poll());
let header = match header {
Ok(header) => header,
Err(err) => return Ok(Err(err).into()),
};
ReadAnyMessageState::ReadPayload {
future: read_exact(stream, Bytes::new_with_len(header.len as usize)),
header: header,
}
}
ReadAnyMessageState::ReadPayload {
ref mut header,
ref mut future,
} => {
let (_stream, bytes) = try_ready!(future.poll());
if checksum(&bytes) != header.checksum {
return Ok(Err(Error::InvalidChecksum).into());
}
2019-06-28 14:27:46 -07:00
return Ok(Async::Ready(Ok((header.command.clone(), bytes))));
}
};
2017-08-04 05:05:58 -07:00
2019-06-28 14:27:46 -07:00
self.state = next_state;
}
}
}
#[cfg(test)]
mod tests {
2019-06-28 14:27:46 -07:00
use super::read_any_message;
use bytes::Bytes;
use futures::Future;
Prefix workspace crates with zebra- (#70) * Update license and author metadata in workspace crates. - ensure that the license field is set to GPL-3 for all GPL-3 licensed crates; - ensure that the author field is set to "Zcash Foundation", responsible for maintenance; - preserve the original authorship info in AUTHORS.md for human-readable history. Updating the author field ensures that all of the machine systems that read crate metadata list the ZF organization, not any single individual, as the maintainer of the crate. * Prefix all internal crate names with zebra-. This does not move the directories containing these crates to also have zebra- prefixes (for instance, zebra-chain instead of chain). I think that this would be preferable, but because it's a `git mv`, it will be simple to do later and leaving it out of this change makes it easier to see the renaming of all of the internal modules. * Remove git dependency from eth-secp256k1 * Avoid an error seemingly related to Deref coercions. This code caused an overflow while evaluating type constraints. As best as I can determine, the cause of the problem was something like so: the Rust implementation of the Bitcoin-specific hash function used in the Bloom filter doesn't operate on byte slices, but only on a `&mut R where R: Read`, so to hash a byte slice, you need to create a mutable copy of the input slice which can be consumed as a `Read` implementation by the hash function; the previous version of this code created a slice copy using a `Deref` coercion instead of `.clone()`, and when a tokio update added new trait impls, the type inference for the `Deref` coercion exploded (somehow -- I'm not sure about the last part?). This commit avoids the problem by manually cloning the input slice.
2019-07-02 12:07:06 -07:00
use zebra_message::Error;
use zebra_network::Network;
2019-06-28 14:27:46 -07:00
#[test]
fn test_read_any_message() {
let raw: Bytes = "24e9276470696e6700000000000000000800000083c00c765845303b6da97786".into();
let name = "ping".into();
let nonce = "5845303b6da97786".into();
let expected = (name, nonce);
2019-06-28 14:27:46 -07:00
assert_eq!(
read_any_message(raw.as_ref(), Network::Mainnet.magic())
.wait()
.unwrap(),
Ok(expected)
);
assert_eq!(
read_any_message(raw.as_ref(), Network::Testnet.magic())
.wait()
.unwrap(),
Err(Error::InvalidMagic)
);
}
2019-06-28 14:27:46 -07:00
#[test]
fn test_read_too_short_any_message() {
let raw: Bytes = "24e9276470696e6700000000000000000800000083c00c765845303b6da977".into();
assert!(read_any_message(raw.as_ref(), Network::Mainnet.magic())
.wait()
.is_err());
}
2019-06-28 14:27:46 -07:00
#[test]
fn test_read_any_message_with_invalid_checksum() {
let raw: Bytes = "24e9276470696e6700000000000000000800000083c01c765845303b6da97786".into();
assert_eq!(
read_any_message(raw.as_ref(), Network::Mainnet.magic())
.wait()
.unwrap(),
Err(Error::InvalidChecksum)
);
}
}