Merge branch 'master' into nvolf

This commit is contained in:
Nikolay Volf
2016-02-03 19:00:05 +03:00
90 changed files with 2328 additions and 907 deletions

View File

@@ -83,11 +83,12 @@ impl<'a> fmt::Display for PrettySlice<'a> {
}
}
/// TODO [Gav Wood] Please document me
/// Trait to allow a type to be pretty-printed in `format!`, where unoverridable
/// defaults cannot otherwise be avoided.
pub trait ToPretty {
/// TODO [Gav Wood] Please document me
/// Convert a type into a derivative form in order to make `format!` print it prettily.
fn pretty(&self) -> PrettySlice;
/// TODO [Gav Wood] Please document me
/// Express the object as a hex string.
fn to_hex(&self) -> String {
format!("{}", self.pretty())
}
@@ -110,11 +111,11 @@ impl ToPretty for Bytes {
}
}
/// TODO [debris] Please document me
/// A byte collection reference that can either be a slice or a vector
pub enum BytesRef<'a> {
/// TODO [debris] Please document me
/// This is a reference to a vector
Flexible(&'a mut Bytes),
/// TODO [debris] Please document me
/// This is a reference to a slice
Fixed(&'a mut [u8])
}
@@ -144,11 +145,12 @@ pub type Bytes = Vec<u8>;
/// Slice of bytes to underlying memory
pub trait BytesConvertable {
// TODO: rename to as_slice
/// TODO [Gav Wood] Please document me
/// Get the underlying byte-wise representation of the value.
/// Deprecated - use `as_slice` instead.
fn bytes(&self) -> &[u8];
/// TODO [Gav Wood] Please document me
/// Get the underlying byte-wise representation of the value.
fn as_slice(&self) -> &[u8] { self.bytes() }
/// TODO [Gav Wood] Please document me
/// Get a copy of the underlying byte-wise representation.
fn to_bytes(&self) -> Bytes { self.as_slice().to_vec() }
}

View File

@@ -49,9 +49,9 @@ use sha3::*;
/// index. Their `BloomIndex` can be created from block number and given level.
#[derive(Eq, PartialEq, Hash, Clone, Debug)]
pub struct BloomIndex {
/// TODO [debris] Please document me
/// Bloom level
pub level: u8,
/// TODO [debris] Please document me
/// Filter Index
pub index: usize,
}

View File

@@ -48,7 +48,7 @@ macro_rules! flushln {
($fmt:expr, $($arg:tt)*) => (flush!(concat!($fmt, "\n"), $($arg)*));
}
/// TODO [Gav Wood] Please document me
#[doc(hidden)]
pub fn flush(s: String) {
::std::io::stdout().write(s.as_bytes()).unwrap();
::std::io::stdout().flush().unwrap();

View File

@@ -6,11 +6,12 @@ use uint::*;
use secp256k1::{key, Secp256k1};
use rand::os::OsRng;
/// TODO [Gav Wood] Please document me
/// Secret key for secp256k1 EC operations. 256 bit generic "hash" data.
pub type Secret = H256;
/// TODO [Gav Wood] Please document me
/// Public key for secp256k1 EC operations. 512 bit generic "hash" data.
pub type Public = H512;
/// TODO [Gav Wood] Please document me
/// Signature for secp256k1 EC operations; encodes two 256-bit curve points
/// and a third sign bit. 520 bit generic "hash" data.
pub type Signature = H520;
lazy_static! {
@@ -38,17 +39,17 @@ impl Signature {
}
#[derive(Debug)]
/// TODO [arkpar] Please document me
/// Crypto error
pub enum CryptoError {
/// TODO [arkpar] Please document me
/// Invalid secret key
InvalidSecret,
/// TODO [arkpar] Please document me
/// Invalid public key
InvalidPublic,
/// TODO [arkpar] Please document me
/// Invalid EC signature
InvalidSignature,
/// TODO [arkpar] Please document me
/// Invalid AES message
InvalidMessage,
/// TODO [arkpar] Please document me
/// IO Error
Io(::std::io::Error),
}
@@ -133,7 +134,7 @@ impl KeyPair {
pub fn sign(&self, message: &H256) -> Result<Signature, CryptoError> { ec::sign(&self.secret, message) }
}
/// TODO [arkpar] Please document me
/// EC functions
pub mod ec {
use hash::*;
use uint::*;
@@ -210,12 +211,12 @@ pub mod ec {
}
}
/// TODO [arkpar] Please document me
/// ECDH functions
pub mod ecdh {
use crypto::*;
use crypto::{self};
/// TODO [arkpar] Please document me
/// Agree on a shared secret
pub fn agree(secret: &Secret, public: &Public, ) -> Result<Secret, CryptoError> {
use secp256k1::*;
let context = &crypto::SECP256K1;
@@ -231,13 +232,13 @@ pub mod ecdh {
}
}
/// TODO [arkpar] Please document me
/// ECIES function
pub mod ecies {
use hash::*;
use bytes::*;
use crypto::*;
/// TODO [arkpar] Please document me
/// Encrypt a message with a public key
pub fn encrypt(public: &Public, plain: &[u8]) -> Result<Bytes, CryptoError> {
use ::rcrypto::digest::Digest;
use ::rcrypto::sha2::Sha256;
@@ -273,7 +274,7 @@ pub mod ecies {
Ok(msg)
}
/// TODO [arkpar] Please document me
/// Decrypt a message with a secret key
pub fn decrypt(secret: &Secret, encrypted: &[u8]) -> Result<Bytes, CryptoError> {
use ::rcrypto::digest::Digest;
use ::rcrypto::sha2::Sha256;
@@ -339,20 +340,20 @@ pub mod ecies {
}
}
/// TODO [arkpar] Please document me
/// AES encryption
pub mod aes {
use ::rcrypto::blockmodes::*;
use ::rcrypto::aessafe::*;
use ::rcrypto::symmetriccipher::*;
use ::rcrypto::buffer::*;
/// TODO [arkpar] Please document me
/// Encrypt a message
pub fn encrypt(k: &[u8], iv: &[u8], plain: &[u8], dest: &mut [u8]) {
let mut encryptor = CtrMode::new(AesSafe128Encryptor::new(k), iv.to_vec());
encryptor.encrypt(&mut RefReadBuffer::new(plain), &mut RefWriteBuffer::new(dest), true).expect("Invalid length or padding");
}
/// TODO [arkpar] Please document me
/// Decrypt a message
pub fn decrypt(k: &[u8], iv: &[u8], encrypted: &[u8], dest: &mut [u8]) {
let mut encryptor = CtrMode::new(AesSafe128Encryptor::new(k), iv.to_vec());
encryptor.decrypt(&mut RefReadBuffer::new(encrypted), &mut RefWriteBuffer::new(dest), true).expect("Invalid length or padding");

View File

@@ -6,36 +6,36 @@ use rlp::DecoderError;
use io;
#[derive(Debug)]
/// TODO [Gav Wood] Please document me
/// Error in database subsystem.
pub enum BaseDataError {
/// TODO [Gav Wood] Please document me
/// An entry was removed more times than inserted.
NegativelyReferencedHash,
}
#[derive(Debug)]
/// General error type which should be capable of representing all errors in ethcore.
pub enum UtilError {
/// TODO [Gav Wood] Please document me
/// Error concerning the crypto utility subsystem.
Crypto(::crypto::CryptoError),
/// TODO [Gav Wood] Please document me
/// Error concerning the Rust standard library's IO subsystem.
StdIo(::std::io::Error),
/// TODO [Gav Wood] Please document me
/// Error concerning our IO utility subsystem.
Io(io::IoError),
/// TODO [Gav Wood] Please document me
/// Error concerning the network address parsing subsystem.
AddressParse(::std::net::AddrParseError),
/// TODO [Gav Wood] Please document me
/// Error concerning the network address resolution subsystem.
AddressResolve(Option<::std::io::Error>),
/// TODO [Gav Wood] Please document me
/// Error concerning the hex conversion logic.
FromHex(FromHexError),
/// TODO [Gav Wood] Please document me
/// Error concerning the database abstraction logic.
BaseData(BaseDataError),
/// TODO [Gav Wood] Please document me
/// Error concerning the network subsystem.
Network(NetworkError),
/// TODO [Gav Wood] Please document me
/// Error concerning the RLP decoder.
Decoder(DecoderError),
/// TODO [Gav Wood] Please document me
/// Miscellaneous error described by a string.
SimpleString(String),
/// TODO [Gav Wood] Please document me
/// Error from a bad input size being given for the needed output.
BadSize,
}

View File

@@ -9,8 +9,8 @@ macro_rules! xjson {
}
}
/// TODO [Gav Wood] Please document me
/// Trait allowing conversion from a JSON value.
pub trait FromJson {
/// TODO [Gav Wood] Please document me
/// Convert a JSON value to an instance of this type.
fn from_json(json: &Json) -> Self;
}

View File

@@ -15,35 +15,35 @@ use serde;
///
/// Note: types implementing `FixedHash` must be also `BytesConvertable`.
pub trait FixedHash: Sized + BytesConvertable + Populatable + FromStr + Default {
/// TODO [Gav Wood] Please document me
/// Create a new, zero-initialised, instance.
fn new() -> Self;
/// Synonym for `new()`. Prefer to new as it's more readable.
fn zero() -> Self;
/// TODO [debris] Please document me
/// Create a new, cryptographically random, instance.
fn random() -> Self;
/// TODO [debris] Please document me
/// Assign self have a cryptographically random value.
fn randomize(&mut self);
/// TODO [arkpar] Please document me
fn size() -> usize;
/// TODO [arkpar] Please document me
/// Get the size of this object in bytes.
fn len() -> usize;
/// Convert a slice of bytes of length `len()` to an instance of this type.
fn from_slice(src: &[u8]) -> Self;
/// TODO [arkpar] Please document me
/// Assign self to be of the same value as a slice of bytes of length `len()`.
fn clone_from_slice(&mut self, src: &[u8]) -> usize;
/// TODO [Gav Wood] Please document me
/// Copy the data of this object into some mutable slice of length `len()`.
fn copy_to(&self, dest: &mut [u8]);
/// TODO [Gav Wood] Please document me
/// When interpreting self as a bloom output, augment (bit-wise OR) with the a bloomed version of `b`.
fn shift_bloomed<'a, T>(&'a mut self, b: &T) -> &'a mut Self where T: FixedHash;
/// TODO [debris] Please document me
/// Same as `shift_bloomed` except that `self` is consumed and a new value returned.
fn with_bloomed<T>(mut self, b: &T) -> Self where T: FixedHash { self.shift_bloomed(b); self }
/// TODO [Gav Wood] Please document me
/// Bloom the current value using the bloom parameter `m`.
fn bloom_part<T>(&self, m: usize) -> T where T: FixedHash;
/// TODO [debris] Please document me
/// Check to see whether this hash, interpreted as a bloom, contains the value `b` when bloomed.
fn contains_bloomed<T>(&self, b: &T) -> bool where T: FixedHash;
/// TODO [arkpar] Please document me
/// Returns `true` if all bits set in `b` are also set in `self`.
fn contains<'a>(&'a self, b: &'a Self) -> bool;
/// TODO [debris] Please document me
/// Returns `true` if no bits are set.
fn is_zero(&self) -> bool;
/// Return the lowest 8 bytes interpreted as a BigEndian integer.
/// Returns the lowest 8 bytes interpreted as a BigEndian integer.
fn low_u64(&self) -> u64;
}
@@ -58,7 +58,7 @@ fn clean_0x(s: &str) -> &str {
macro_rules! impl_hash {
($from: ident, $size: expr) => {
#[derive(Eq)]
/// TODO [Gav Wood] Please document me
/// Unformatted binary data of fixed length.
pub struct $from (pub [u8; $size]);
impl BytesConvertable for $from {
@@ -103,7 +103,7 @@ macro_rules! impl_hash {
rng.fill_bytes(&mut self.0);
}
fn size() -> usize {
fn len() -> usize {
$size
}
@@ -457,12 +457,12 @@ macro_rules! impl_hash {
}
impl $from {
/// TODO [Gav Wood] Please document me
/// Get a hex representation.
pub fn hex(&self) -> String {
format!("{:?}", self)
}
/// TODO [Gav Wood] Please document me
/// Construct new instance equal to the bloomed value of `b`.
pub fn from_bloomed<T>(b: &T) -> Self where T: FixedHash { b.bloom_part($size) }
}
@@ -578,25 +578,27 @@ impl<'_> From<&'_ Address> for H256 {
}
}
/// TODO [Gav Wood] Please document me
/// Convert string `s` to an `H256`. Will panic if `s` is not 64 characters long or if any of
/// those characters are not 0-9, a-z or A-Z.
pub fn h256_from_hex(s: &str) -> H256 {
use std::str::FromStr;
H256::from_str(s).unwrap()
}
/// TODO [Gav Wood] Please document me
/// Convert `n` to an `H256`, setting the rightmost 8 bytes.
pub fn h256_from_u64(n: u64) -> H256 {
use uint::U256;
H256::from(&U256::from(n))
}
/// TODO [Gav Wood] Please document me
/// Convert string `s` to an `Address`. Will panic if `s` is not 40 characters long or if any of
/// those characters are not 0-9, a-z or A-Z.
pub fn address_from_hex(s: &str) -> Address {
use std::str::FromStr;
Address::from_str(s).unwrap()
}
/// TODO [Gav Wood] Please document me
/// Convert `n` to an `Address`, setting the rightmost 8 bytes.
pub fn address_from_u64(n: u64) -> Address {
let h256 = h256_from_u64(n);
From::from(h256)

View File

@@ -42,9 +42,9 @@ mod worker;
use mio::{EventLoop, Token};
#[derive(Debug)]
/// TODO [arkpar] Please document me
/// IO Error
pub enum IoError {
/// TODO [arkpar] Please document me
/// Low level error from mio crate
Mio(::std::io::Error),
}
@@ -78,19 +78,12 @@ pub trait IoHandler<Message>: Send + Sync where Message: Send + Sync + Clone + '
fn deregister_stream(&self, _stream: StreamToken, _event_loop: &mut EventLoop<IoManager<Message>>) {}
}
/// TODO [arkpar] Please document me
pub use io::service::TimerToken;
/// TODO [arkpar] Please document me
pub use io::service::StreamToken;
/// TODO [arkpar] Please document me
pub use io::service::IoContext;
/// TODO [arkpar] Please document me
pub use io::service::IoService;
/// TODO [arkpar] Please document me
pub use io::service::IoChannel;
/// TODO [arkpar] Please document me
pub use io::service::IoManager;
/// TODO [arkpar] Please document me
pub use io::service::TOKENS_PER_HANDLER;
#[cfg(test)]

View File

@@ -1,6 +1,6 @@
use common::*;
/// TODO [Gav Wood] Please document me
/// Remove the `"0x"`, if present, from the left of `s`, returning the remaining slice.
pub fn clean(s: &str) -> &str {
if s.len() >= 2 && &s[0..2] == "0x" {
&s[2..]

View File

@@ -107,14 +107,17 @@ impl MemoryDB {
self.data.get(key)
}
/// TODO [Gav Wood] Please document me
/// Return the internal map of hashes to data, clearing the current state.
pub fn drain(&mut self) -> HashMap<H256, (Bytes, i32)> {
let mut data = HashMap::new();
mem::swap(&mut self.data, &mut data);
data
}
/// TODO [Gav Wood] Please document me
/// Denote than an existing value has the given key. Used when a key gets removed without
/// a prior insert and thus has a negative reference with no value.
///
/// May safely be called even if the key's value is known, in which case it will be a no-op.
pub fn denote(&self, key: &H256, value: Bytes) -> &(Bytes, i32) {
if self.raw(key) == None {
unsafe {

View File

@@ -5,13 +5,13 @@ use common::*;
#[derive(Debug,Clone,PartialEq,Eq)]
/// Diff type for specifying a change (or not).
pub enum Diff<T> where T: Eq {
/// TODO [Gav Wood] Please document me
/// Both sides are the same.
Same,
/// TODO [Gav Wood] Please document me
/// Left (pre, source) side doesn't include value, right side (post, destination) does.
Born(T),
/// TODO [Gav Wood] Please document me
/// Both sides include data; it chaged value between them.
Changed(T, T),
/// TODO [Gav Wood] Please document me
/// Left (pre, source) side does include value, right side (post, destination) does not.
Died(T),
}
@@ -32,8 +32,8 @@ impl<T> Diff<T> where T: Eq {
#[derive(PartialEq,Eq,Clone,Copy)]
/// Boolean type for clean/dirty status.
pub enum Filth {
/// TODO [Gav Wood] Please document me
/// Data has not been changed.
Clean,
/// TODO [Gav Wood] Please document me
/// Data has been changed.
Dirty,
}

View File

@@ -216,6 +216,12 @@ pub struct EncryptedConnection {
}
impl EncryptedConnection {
/// Get socket token
pub fn token(&self) -> StreamToken {
self.connection.token
}
/// Create an encrypted connection out of the handshake. Consumes a handshake object.
pub fn new(mut handshake: Handshake) -> Result<EncryptedConnection, UtilError> {
let shared = try!(crypto::ecdh::agree(handshake.ecdhe.secret(), &handshake.remote_public));
@@ -607,4 +613,4 @@ mod tests {
assert!(!status.is_ok());
assert_eq!(1, connection.send_queue.len());
}
}
}

View File

@@ -5,17 +5,17 @@ use rlp::*;
pub enum DisconnectReason
{
DisconnectRequested,
//TCPError,
//BadProtocol,
_TCPError,
_BadProtocol,
UselessPeer,
//TooManyPeers,
//DuplicatePeer,
//IncompatibleProtocol,
//NullIdentity,
//ClientQuit,
//UnexpectedIdentity,
//LocalIdentity,
//PingTimeout,
_TooManyPeers,
_DuplicatePeer,
_IncompatibleProtocol,
_NullIdentity,
_ClientQuit,
_UnexpectedIdentity,
_LocalIdentity,
PingTimeout,
}
#[derive(Debug)]

View File

@@ -19,6 +19,7 @@ use io::*;
use network::NetworkProtocolHandler;
use network::node::*;
use network::stats::NetworkStats;
use network::error::DisconnectReason;
type Slab<T> = ::slab::Slab<T, usize>;
@@ -108,6 +109,8 @@ pub enum NetworkIoMessage<Message> where Message: Send + Sync + Clone {
/// Timer delay in milliseconds.
delay: u64,
},
/// Disconnect a peer
Disconnect(PeerId),
/// User message
User(Message),
}
@@ -181,8 +184,14 @@ impl<'s, Message> NetworkContext<'s, Message> where Message: Send + Sync + Clone
}
/// Disable current protocol capability for given peer. If no capabilities left peer gets disconnected.
pub fn disable_peer(&self, _peer: PeerId) {
pub fn disable_peer(&self, peer: PeerId) {
//TODO: remove capability, disconnect if no capabilities left
self.disconnect_peer(peer);
}
/// Disconnect peer. Reconnect can be attempted later.
pub fn disconnect_peer(&self, peer: PeerId) {
self.io.message(NetworkIoMessage::Disconnect(peer));
}
/// Register a new IO timer. 'IoHandler::timeout' will be called with the token.
@@ -332,6 +341,7 @@ impl<Message> Host<Message> where Message: Send + Sync + Clone {
}
fn maintain_network(&self, io: &IoContext<NetworkIoMessage<Message>>) {
self.keep_alive(io);
self.connect_peers(io);
}
@@ -343,6 +353,21 @@ impl<Message> Host<Message> where Message: Send + Sync + Clone {
self.connections.read().unwrap().iter().any(|e| match *e.lock().unwrap().deref() { ConnectionEntry::Handshake(ref h) => h.id.eq(&id), _ => false })
}
fn keep_alive(&self, io: &IoContext<NetworkIoMessage<Message>>) {
let mut to_kill = Vec::new();
for e in self.connections.write().unwrap().iter_mut() {
if let ConnectionEntry::Session(ref mut s) = *e.lock().unwrap().deref_mut() {
if !s.keep_alive() {
s.disconnect(DisconnectReason::PingTimeout);
to_kill.push(s.token());
}
}
}
for p in to_kill {
self.kill_connection(p, io);
}
}
fn connect_peers(&self, io: &IoContext<NetworkIoMessage<Message>>) {
struct NodeInfo {
id: NodeId,
@@ -684,6 +709,15 @@ impl<Message> IoHandler<NetworkIoMessage<Message>> for Host<Message> where Messa
self.timers.write().unwrap().insert(handler_token, ProtocolTimer { protocol: protocol, token: *token });
io.register_timer(handler_token, *delay).expect("Error registering timer");
},
NetworkIoMessage::Disconnect(ref peer) => {
if let Some(connection) = self.connections.read().unwrap().get(*peer).cloned() {
match *connection.lock().unwrap().deref_mut() {
ConnectionEntry::Handshake(_) => {},
ConnectionEntry::Session(ref mut s) => { s.disconnect(DisconnectReason::DisconnectRequested); }
}
}
self.kill_connection(*peer, io);
},
NetworkIoMessage::User(ref message) => {
for (p, h) in self.handlers.read().unwrap().iter() {
h.message(&NetworkContext::new(io, p, None, self.connections.clone()), &message);

View File

@@ -21,7 +21,7 @@ impl<Message> NetworkService<Message> where Message: Send + Sync + Clone + 'stat
let host = Arc::new(Host::new(config));
let stats = host.stats().clone();
let host_info = host.client_version();
info!("NetworkService::start(): id={:?}", host.client_id());
info!("Host ID={:?}", host.client_id());
try!(io_service.register_handler(host));
Ok(NetworkService {
io_service: io_service,

View File

@@ -4,10 +4,14 @@ use rlp::*;
use network::connection::{EncryptedConnection, Packet};
use network::handshake::Handshake;
use error::*;
use io::{IoContext};
use io::{IoContext, StreamToken};
use network::error::{NetworkError, DisconnectReason};
use network::host::*;
use network::node::NodeId;
use time;
const PING_TIMEOUT_SEC: u64 = 30;
const PING_INTERVAL_SEC: u64 = 30;
/// Peer session over encrypted connection.
/// When created waits for Hello packet exchange and signals ready state.
@@ -19,6 +23,8 @@ pub struct Session {
connection: EncryptedConnection,
/// Session ready flag. Set after successfull Hello packet exchange
had_hello: bool,
ping_time_ns: u64,
pong_time_ns: Option<u64>,
}
/// Structure used to report various session events.
@@ -47,6 +53,8 @@ pub struct SessionInfo {
pub protocol_version: u32,
/// Peer protocol capabilities
capabilities: Vec<SessionCapabilityInfo>,
/// Peer ping delay in milliseconds
pub ping_ms: Option<u64>,
}
#[derive(Debug, PartialEq, Eq)]
@@ -95,10 +103,13 @@ impl Session {
client_version: String::new(),
protocol_version: 0,
capabilities: Vec::new(),
ping_ms: None,
},
ping_time_ns: 0,
pong_time_ns: None,
};
try!(session.write_hello(host));
try!(session.write_ping());
try!(session.send_ping());
Ok(session)
}
@@ -141,7 +152,7 @@ impl Session {
while protocol != self.info.capabilities[i].protocol {
i += 1;
if i == self.info.capabilities.len() {
debug!(target: "net", "Unkown protocol: {:?}", protocol);
debug!(target: "net", "Unknown protocol: {:?}", protocol);
return Ok(())
}
}
@@ -152,6 +163,26 @@ impl Session {
self.connection.send_packet(&rlp.out())
}
/// Keep this session alive. Returns false if ping timeout happened
pub fn keep_alive(&mut self) -> bool {
let timed_out = if let Some(pong) = self.pong_time_ns {
pong - self.ping_time_ns > PING_TIMEOUT_SEC * 1000_000_000
} else {
time::precise_time_ns() - self.ping_time_ns > PING_TIMEOUT_SEC * 1000_000_000
};
if !timed_out && time::precise_time_ns() - self.ping_time_ns > PING_INTERVAL_SEC * 1000_000_000 {
if let Err(e) = self.send_ping() {
debug!("Error sending ping message: {:?}", e);
}
}
!timed_out
}
pub fn token(&self) -> StreamToken {
self.connection.token()
}
fn read_packet(&mut self, packet: Packet, host: &HostInfo) -> Result<SessionData, UtilError> {
if packet.data.len() < 2 {
return Err(From::from(NetworkError::BadProtocol));
@@ -168,7 +199,12 @@ impl Session {
},
PACKET_DISCONNECT => Err(From::from(NetworkError::Disconnect(DisconnectReason::DisconnectRequested))),
PACKET_PING => {
try!(self.write_pong());
try!(self.send_pong());
Ok(SessionData::None)
},
PACKET_PONG => {
self.pong_time_ns = Some(time::precise_time_ns());
self.info.ping_ms = Some((self.pong_time_ns.unwrap() - self.ping_time_ns) / 1000_000);
Ok(SessionData::None)
},
PACKET_GET_PEERS => Ok(SessionData::None), //TODO;
@@ -178,7 +214,7 @@ impl Session {
while packet_id < self.info.capabilities[i].id_offset {
i += 1;
if i == self.info.capabilities.len() {
debug!(target: "net", "Unkown packet: {:?}", packet_id);
debug!(target: "net", "Unknown packet: {:?}", packet_id);
return Ok(SessionData::None)
}
}
@@ -189,7 +225,7 @@ impl Session {
Ok(SessionData::Packet { data: packet.data, protocol: protocol, packet_id: pid } )
},
_ => {
debug!(target: "net", "Unkown packet: {:?}", packet_id);
debug!(target: "net", "Unknown packet: {:?}", packet_id);
Ok(SessionData::None)
}
}
@@ -255,15 +291,20 @@ impl Session {
Ok(())
}
fn write_ping(&mut self) -> Result<(), UtilError> {
self.send(try!(Session::prepare(PACKET_PING)))
/// Senf ping packet
pub fn send_ping(&mut self) -> Result<(), UtilError> {
try!(self.send(try!(Session::prepare(PACKET_PING))));
self.ping_time_ns = time::precise_time_ns();
self.pong_time_ns = None;
Ok(())
}
fn write_pong(&mut self) -> Result<(), UtilError> {
fn send_pong(&mut self) -> Result<(), UtilError> {
self.send(try!(Session::prepare(PACKET_PONG)))
}
fn disconnect(&mut self, reason: DisconnectReason) -> NetworkError {
/// Disconnect this session
pub fn disconnect(&mut self, reason: DisconnectReason) -> NetworkError {
let mut rlp = RlpStream::new();
rlp.append(&(PACKET_DISCONNECT as u32));
rlp.begin_list(1);

View File

@@ -34,7 +34,7 @@ pub struct NibbleSlice<'a> {
offset_encode_suffix: usize,
}
/// TODO [Gav Wood] Please document me
/// Iterator type for a nibble slice.
pub struct NibbleSliceIterator<'a> {
p: &'a NibbleSlice<'a>,
i: usize,
@@ -77,7 +77,7 @@ impl<'a, 'view> NibbleSlice<'a> where 'a: 'view {
(r, a.len() + b.len())
}*/
/// TODO [Gav Wood] Please document me
/// Get an iterator for the series of nibbles.
pub fn iter(&'a self) -> NibbleSliceIterator<'a> {
NibbleSliceIterator { p: self, i: 0 }
}
@@ -132,7 +132,7 @@ impl<'a, 'view> NibbleSlice<'a> where 'a: 'view {
i
}
/// TODO [Gav Wood] Please document me
/// Encode while nibble slice in prefixed hex notation, noting whether it `is_leaf`.
pub fn encoded(&self, is_leaf: bool) -> Bytes {
let l = self.len();
let mut r = Bytes::with_capacity(l / 2 + 1);
@@ -145,7 +145,8 @@ impl<'a, 'view> NibbleSlice<'a> where 'a: 'view {
r
}
/// TODO [Gav Wood] Please document me
/// Encode only the leftmost `n` bytes of the nibble slice in prefixed hex notation,
/// noting whether it `is_leaf`.
pub fn encoded_leftmost(&self, n: usize, is_leaf: bool) -> Bytes {
let l = min(self.len(), n);
let mut r = Bytes::with_capacity(l / 2 + 1);

View File

@@ -140,9 +140,9 @@ impl <T>ToBytes for T where T: FixedHash {
/// Error returned when FromBytes conversation goes wrong
#[derive(Debug, PartialEq, Eq)]
pub enum FromBytesError {
/// TODO [debris] Please document me
/// Expected more RLP data
DataIsTooShort,
/// TODO [debris] Please document me
/// Extra bytes after the end of the last item
DataIsTooLong,
/// Integer-representation is non-canonically prefixed with zero byte(s).
ZeroPrefixedInt,
@@ -165,7 +165,7 @@ pub type FromBytesResult<T> = Result<T, FromBytesError>;
///
/// TODO: check size of bytes before conversation and return appropriate error
pub trait FromBytes: Sized {
/// TODO [debris] Please document me
/// Create a value from bytes
fn from_bytes(bytes: &[u8]) -> FromBytesResult<Self>;
}
@@ -236,7 +236,7 @@ impl_uint_from_bytes!(U128);
impl <T>FromBytes for T where T: FixedHash {
fn from_bytes(bytes: &[u8]) -> FromBytesResult<T> {
match bytes.len().cmp(&T::size()) {
match bytes.len().cmp(&T::len()) {
Ordering::Less => return Err(FromBytesError::DataIsTooShort),
Ordering::Greater => return Err(FromBytesError::DataIsTooLong),
Ordering::Equal => ()
@@ -246,7 +246,7 @@ impl <T>FromBytes for T where T: FixedHash {
use std::{mem, ptr};
let mut res: T = mem::uninitialized();
ptr::copy(bytes.as_ptr(), res.as_slice_mut().as_mut_ptr(), T::size());
ptr::copy(bytes.as_ptr(), res.as_slice_mut().as_mut_ptr(), T::len());
Ok(res)
}

View File

@@ -48,13 +48,13 @@ pub use self::rlpstream::{RlpStream};
pub use elastic_array::ElasticArray1024;
use super::hash::H256;
/// TODO [arkpar] Please document me
/// The RLP encoded empty data (used to mean "null value").
pub const NULL_RLP: [u8; 1] = [0x80; 1];
/// TODO [Gav Wood] Please document me
/// The RLP encoded empty list.
pub const EMPTY_LIST_RLP: [u8; 1] = [0xC0; 1];
/// TODO [arkpar] Please document me
/// The SHA3 of the RLP encoding of empty data.
pub const SHA3_NULL_RLP: H256 = H256( [0x56, 0xe8, 0x1f, 0x17, 0x1b, 0xcc, 0x55, 0xa6, 0xff, 0x83, 0x45, 0xe6, 0x92, 0xc0, 0xf8, 0x6e, 0x5b, 0x48, 0xe0, 0x1b, 0x99, 0x6c, 0xad, 0xc0, 0x01, 0x62, 0x2f, 0xb5, 0xe3, 0x63, 0xb4, 0x21] );
/// TODO [debris] Please document me
/// The SHA3 of the RLP encoding of empty list.
pub const SHA3_EMPTY_LIST_RLP: H256 = H256( [0x1d, 0xcc, 0x4d, 0xe8, 0xde, 0xc7, 0x5d, 0x7a, 0xab, 0x85, 0xb5, 0x67, 0xb6, 0xcc, 0xd4, 0x1a, 0xd3, 0x12, 0x45, 0x1b, 0x94, 0x8a, 0x74, 0x13, 0xf0, 0xa1, 0x42, 0xfd, 0x40, 0xd4, 0x93, 0x47] );
/// Shortcut function to decode trusted rlp

View File

@@ -3,27 +3,27 @@ use std::error::Error as StdError;
use rlp::bytes::FromBytesError;
#[derive(Debug, PartialEq, Eq)]
/// TODO [debris] Please document me
/// Error concerning the RLP decoder.
pub enum DecoderError {
/// TODO [debris] Please document me
/// Couldn't convert given bytes to an instance of required type.
FromBytesError(FromBytesError),
/// Given data has additional bytes at the end of the valid RLP fragment.
/// Data has additional bytes at the end of the valid RLP fragment.
RlpIsTooBig,
/// TODO [debris] Please document me
/// Data has too few bytes for valid RLP.
RlpIsTooShort,
/// TODO [debris] Please document me
/// Expect an encoded list, RLP was something else.
RlpExpectedToBeList,
/// TODO [Gav Wood] Please document me
/// Expect encoded data, RLP was something else.
RlpExpectedToBeData,
/// TODO [Gav Wood] Please document me
/// Expected a different size list.
RlpIncorrectListLen,
/// TODO [Gav Wood] Please document me
/// Data length number has a prefixed zero byte, invalid for numbers.
RlpDataLenWithZeroPrefix,
/// TODO [Gav Wood] Please document me
/// List length number has a prefixed zero byte, invalid for numbers.
RlpListLenWithZeroPrefix,
/// TODO [debris] Please document me
/// Non-canonical (longer than necessary) representation used for data or list.
RlpInvalidIndirection,
/// Returned when declared length is inconsistent with data specified after
/// Declared length is inconsistent with data specified after.
RlpInconsistentLengthAndData
}

View File

@@ -103,12 +103,12 @@ impl <'a, 'view> Rlp<'a> where 'a: 'view {
res.unwrap_or_else(|_| panic!())
}
/// TODO [debris] Please document me
/// Decode into an object
pub fn as_val<T>(&self) -> T where T: RlpDecodable {
Self::view_as_val(self)
}
/// TODO [debris] Please document me
/// Decode list item at given index into an object
pub fn val_at<T>(&self, index: usize) -> T where T: RlpDecodable {
Self::view_as_val(&self.at(index))
}

View File

@@ -7,15 +7,15 @@ use elastic_array::ElasticArray1024;
use hash::H256;
use sha3::*;
/// TODO [debris] Please document me
/// Type is able to decode RLP.
pub trait Decoder: Sized {
/// TODO [debris] Please document me
/// Read a value from the RLP into a given type.
fn read_value<T, F>(&self, f: F) -> Result<T, DecoderError>
where F: FnOnce(&[u8]) -> Result<T, DecoderError>;
/// TODO [Gav Wood] Please document me
/// Get underlying `UntrustedRLP` object.
fn as_rlp(&self) -> &UntrustedRlp;
/// TODO [debris] Please document me
/// Get underlying raw bytes slice.
fn as_raw(&self) -> &[u8];
}
@@ -31,17 +31,17 @@ pub trait RlpDecodable: Sized {
fn decode<D>(decoder: &D) -> Result<Self, DecoderError> where D: Decoder;
}
/// TODO [debris] Please document me
/// A view into RLP encoded data
pub trait View<'a, 'view>: Sized {
/// TODO [debris] Please document me
/// RLP prototype type
type Prototype;
/// TODO [debris] Please document me
/// Payload info type
type PayloadInfo;
/// TODO [debris] Please document me
/// Data type
type Data;
/// TODO [debris] Please document me
/// Item type
type Item;
/// TODO [debris] Please document me
/// Iterator type
type Iter;
/// Creates a new instance of `Rlp` reader
@@ -65,10 +65,10 @@ pub trait View<'a, 'view>: Sized {
/// Get the prototype of the RLP.
fn prototype(&self) -> Self::Prototype;
/// TODO [debris] Please document me
/// Get payload info.
fn payload_info(&self) -> Self::PayloadInfo;
/// TODO [debris] Please document me
/// Get underlieing data.
fn data(&'view self) -> Self::Data;
/// Returns number of RLP items.
@@ -205,18 +205,18 @@ pub trait View<'a, 'view>: Sized {
/// ```
fn iter(&'view self) -> Self::Iter;
/// TODO [debris] Please document me
/// Decode data into an object
fn as_val<T>(&self) -> Result<T, DecoderError> where T: RlpDecodable;
/// TODO [debris] Please document me
/// Decode data at given list index into an object
fn val_at<T>(&self, index: usize) -> Result<T, DecoderError> where T: RlpDecodable;
}
/// TODO [debris] Please document me
/// Raw RLP encoder
pub trait Encoder {
/// TODO [debris] Please document me
/// Write a value represented as bytes
fn emit_value<E: ByteEncodable>(&mut self, value: &E);
/// TODO [debris] Please document me
/// Write raw preencoded data to the output
fn emit_raw(&mut self, bytes: &[u8]) -> ();
}
@@ -250,7 +250,7 @@ pub trait RlpEncodable {
fn rlp_append(&self, s: &mut RlpStream);
}
/// TODO [debris] Please document me
/// RLP encoding stream
pub trait Stream: Sized {
/// Initializes instance of empty `Stream`.
@@ -341,7 +341,7 @@ pub trait Stream: Sized {
/// }
fn is_finished(&self) -> bool;
/// TODO [debris] Please document me
/// Get raw encoded bytes
fn as_raw(&self) -> &[u8];
/// Streams out encoded bytes.

View File

@@ -21,21 +21,21 @@ impl OffsetCache {
}
#[derive(Debug)]
/// TODO [debris] Please document me
/// RLP prototype
pub enum Prototype {
/// TODO [debris] Please document me
/// Empty
Null,
/// TODO [debris] Please document me
/// Value
Data(usize),
/// TODO [debris] Please document me
/// List
List(usize),
}
/// Stores basic information about item
pub struct PayloadInfo {
/// TODO [debris] Please document me
/// Header length in bytes
pub header_len: usize,
/// TODO [debris] Please document me
/// Value length in bytes
pub value_len: usize,
}

View File

@@ -6,7 +6,7 @@ use bytes::{BytesConvertable, Populatable};
use hash::{H256, FixedHash};
use self::sha3_ext::*;
/// TODO [Gav Wood] Please document me
/// Get the SHA3 (i.e. Keccak) hash of the empty bytes string.
pub const SHA3_EMPTY: H256 = H256( [0xc5, 0xd2, 0x46, 0x01, 0x86, 0xf7, 0x23, 0x3c, 0x92, 0x7e, 0x7d, 0xb2, 0xdc, 0xc7, 0x03, 0xc0, 0xe5, 0x00, 0xb6, 0x53, 0xca, 0x82, 0x27, 0x3b, 0x7b, 0xfa, 0xd8, 0x04, 0x5d, 0x85, 0xa4, 0x70] );

View File

@@ -36,7 +36,7 @@ use heapsize::HeapSizeOf;
/// Should be used to squeeze collections to certain size in bytes
pub trait Squeeze {
/// TODO [debris] Please document me
/// Try to reduce collection size to `size` bytes
fn squeeze(&mut self, size: usize);
}

View File

@@ -1,19 +1,20 @@
//! Trie interface and implementation.
/// TODO [Gav Wood] Please document me
/// Export the trietraits module.
pub mod trietraits;
/// Export the standardmap module.
pub mod standardmap;
/// TODO [Gav Wood] Please document me
/// Export the journal module.
pub mod journal;
/// TODO [Gav Wood] Please document me
/// Export the node module.
pub mod node;
/// TODO [Gav Wood] Please document me
/// Export the triedb module.
pub mod triedb;
/// TODO [Gav Wood] Please document me
/// Export the triedbmut module.
pub mod triedbmut;
/// TODO [Gav Wood] Please document me
/// Export the sectriedb module.
pub mod sectriedb;
/// TODO [Gav Wood] Please document me
/// Export the sectriedbmut module.
pub mod sectriedbmut;
pub use self::trietraits::*;

View File

@@ -7,13 +7,13 @@ use super::journal::*;
/// Type of node in the trie and essential information thereof.
#[derive(Clone, Eq, PartialEq, Debug)]
pub enum Node<'a> {
/// TODO [Gav Wood] Please document me
/// Null trie node; could be an empty root or an empty branch entry.
Empty,
/// TODO [Gav Wood] Please document me
/// Leaf node; has key slice and value. Value may not be empty.
Leaf(NibbleSlice<'a>, &'a[u8]),
/// TODO [Gav Wood] Please document me
/// Extension node; has key slice and node data. Data may not be null.
Extension(NibbleSlice<'a>, &'a[u8]),
/// TODO [Gav Wood] Please document me
/// Branch node; has array of 16 child nodes (each possibly null) and an optional immediate node data.
Branch([&'a[u8]; 16], Option<&'a [u8]>)
}

View File

@@ -7,13 +7,13 @@ use hash::*;
/// Alphabet to use when creating words for insertion into tries.
pub enum Alphabet {
/// TODO [Gav Wood] Please document me
/// All values are allowed in each bytes of the key.
All,
/// TODO [Gav Wood] Please document me
/// Only a 6 values ('a' - 'f') are chosen to compose the key.
Low,
/// TODO [Gav Wood] Please document me
/// Quite a few values (around 32) are chosen to compose the key.
Mid,
/// TODO [Gav Wood] Please document me
/// A set of bytes given is used to compose the key.
Custom(Bytes),
}

View File

@@ -34,7 +34,7 @@ use super::node::*;
pub struct TrieDB<'db> {
db: &'db HashDB,
root: &'db H256,
/// TODO [Gav Wood] Please document me
/// The number of hashes performed so far in operations on this trie.
pub hash_count: usize,
}

View File

@@ -40,7 +40,7 @@ use super::trietraits::*;
pub struct TrieDBMut<'db> {
db: &'db mut HashDB,
root: &'db mut H256,
/// TODO [Gav Wood] Please document me
/// The number of hashes performed so far in operations on this trie.
pub hash_count: usize,
}
@@ -72,7 +72,7 @@ impl<'db> TrieDBMut<'db> {
// TODO: return Result<Self, TrieError>
pub fn from_existing(db: &'db mut HashDB, root: &'db mut H256) -> Self {
if !db.exists(root) {
flush(format!("Trie root not found {}", root));
flushln!("Trie root not found {}", root);
panic!("Trie root not found!");
}
TrieDBMut {

View File

@@ -60,20 +60,20 @@ macro_rules! panic_on_overflow {
}
}
/// TODO [Gav Wood] Please document me
/// Large, fixed-length unsigned integer type.
pub trait Uint: Sized + Default + FromStr + From<u64> + FromJson + fmt::Debug + fmt::Display + PartialOrd + Ord + PartialEq + Eq + Hash {
/// Size of this type.
const SIZE: usize;
/// TODO [Gav Wood] Please document me
/// Returns new instance equalling zero.
fn zero() -> Self;
/// TODO [Gav Wood] Please document me
/// Returns new instance equalling one.
fn one() -> Self;
/// TODO [Gav Wood] Please document me
/// Error type for converting from a decimal string.
type FromDecStrErr;
/// TODO [Gav Wood] Please document me
/// Convert from a decimal string.
fn from_dec_str(value: &str) -> Result<Self, Self::FromDecStrErr>;
/// Conversion to u32
@@ -104,26 +104,25 @@ pub trait Uint: Sized + Default + FromStr + From<u64> + FromJson + fmt::Debug +
/// Return wrapped eponentation `self**other` and flag if there was an overflow
fn overflowing_pow(self, other: Self) -> (Self, bool);
/// TODO [debris] Please document me
/// Add this `Uint` to other returning result and possible overflow
fn overflowing_add(self, other: Self) -> (Self, bool);
/// TODO [debris] Please document me
/// Subtract another `Uint` from this returning result and possible overflow
fn overflowing_sub(self, other: Self) -> (Self, bool);
/// TODO [debris] Please document me
/// Multiple this `Uint` with other returning result and possible overflow
fn overflowing_mul(self, other: Self) -> (Self, bool);
/// TODO [debris] Please document me
/// Divide this `Uint` by other returning result and possible overflow
fn overflowing_div(self, other: Self) -> (Self, bool);
/// TODO [debris] Please document me
/// Returns reminder of division of this `Uint` by other and possible overflow
fn overflowing_rem(self, other: Self) -> (Self, bool);
/// TODO [debris] Please document me
/// Returns negation of this `Uint` and overflow (always true)
fn overflowing_neg(self) -> (Self, bool);
/// TODO [Gav Wood] Please document me
/// Shifts this `Uint` and returns overflow
fn overflowing_shl(self, shift: u32) -> (Self, bool);
}
@@ -939,12 +938,10 @@ impl From<U256> for u32 {
}
}
/// TODO [Gav Wood] Please document me
/// Constant value of `U256::zero()` that can be used for a reference saving an additional instance creation.
pub const ZERO_U256: U256 = U256([0x00u64; 4]);
/// TODO [Gav Wood] Please document me
/// Constant value of `U256::one()` that can be used for a reference saving an additional instance creation.
pub const ONE_U256: U256 = U256([0x01u64, 0x00u64, 0x00u64, 0x00u64]);
/// TODO [Gav Wood] Please document me
pub const BAD_U256: U256 = U256([0xffffffffffffffffu64; 4]);
#[cfg(test)]
mod tests {

View File

@@ -13,7 +13,7 @@
/// }
/// ```
pub trait SharedPrefix <T> {
/// TODO [debris] Please document me
/// Get common prefix length
fn shared_prefix_len(&self, elem: &[T]) -> usize;
}