From 23f1a8fd4869c140f9710dc52b63a71fa989c48a Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Thu, 5 May 2016 22:20:34 +0400 Subject: [PATCH 01/32] transaction moved --- ethcore/src/lib.rs | 4 +- ethcore/src/types/mod.rs | 19 ++ ethcore/src/types/mod.rs.in | 0 ethcore/src/types/transaction.rs | 383 +++++++++++++++++++++++++++++++ 4 files changed, 405 insertions(+), 1 deletion(-) create mode 100644 ethcore/src/types/mod.rs create mode 100644 ethcore/src/types/mod.rs.in create mode 100644 ethcore/src/types/transaction.rs diff --git a/ethcore/src/lib.rs b/ethcore/src/lib.rs index 43b4c5099..45692f556 100644 --- a/ethcore/src/lib.rs +++ b/ethcore/src/lib.rs @@ -101,7 +101,6 @@ pub mod service; pub mod log_entry; pub mod trace; pub mod spec; -pub mod transaction; pub mod views; pub mod receipt; pub mod pod_state; @@ -128,9 +127,12 @@ mod executive; mod externalities; mod verification; mod blockchain; +mod types; #[cfg(test)] mod tests; #[cfg(test)] #[cfg(feature="json-tests")] mod json_tests; + +pub use types::*; diff --git a/ethcore/src/types/mod.rs b/ethcore/src/types/mod.rs new file mode 100644 index 000000000..438dbafb0 --- /dev/null +++ b/ethcore/src/types/mod.rs @@ -0,0 +1,19 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +//! Types used in the public api + +pub mod transaction; diff --git a/ethcore/src/types/mod.rs.in b/ethcore/src/types/mod.rs.in new file mode 100644 index 000000000..e69de29bb diff --git a/ethcore/src/types/transaction.rs b/ethcore/src/types/transaction.rs new file mode 100644 index 000000000..ca54f26bb --- /dev/null +++ b/ethcore/src/types/transaction.rs @@ -0,0 +1,383 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +//! Transaction data structure. + +use util::*; +use error::*; +use evm::Schedule; +use header::BlockNumber; +use ethjson; + +#[derive(Debug, Clone, PartialEq, Eq)] +/// Transaction action type. +pub enum Action { + /// Create creates new contract. + Create, + /// Calls contract at given address. + Call(Address), +} + +impl Default for Action { + fn default() -> Action { Action::Create } +} + +impl Decodable for Action { + fn decode(decoder: &D) -> Result where D: Decoder { + let rlp = decoder.as_rlp(); + if rlp.is_empty() { + Ok(Action::Create) + } else { + Ok(Action::Call(try!(rlp.as_val()))) + } + } +} + +/// A set of information describing an externally-originating message call +/// or contract creation operation. +#[derive(Default, Debug, Clone, PartialEq, Eq)] +pub struct Transaction { + /// Nonce. + pub nonce: U256, + /// Gas price. + pub gas_price: U256, + /// Gas paid up front for transaction execution. + pub gas: U256, + /// Action, can be either call or contract create. + pub action: Action, + /// Transfered value. + pub value: U256, + /// Transaction data. + pub data: Bytes, +} + +impl Transaction { + /// Append object with a without signature into RLP stream + pub fn rlp_append_unsigned_transaction(&self, s: &mut RlpStream) { + s.begin_list(6); + s.append(&self.nonce); + s.append(&self.gas_price); + s.append(&self.gas); + match self.action { + Action::Create => s.append_empty_data(), + Action::Call(ref to) => s.append(to) + }; + s.append(&self.value); + s.append(&self.data); + } +} + +impl From for SignedTransaction { + fn from(t: ethjson::state::Transaction) -> Self { + let to: Option<_> = t.to.into(); + Transaction { + nonce: t.nonce.into(), + gas_price: t.gas_price.into(), + gas: t.gas_limit.into(), + action: match to { + Some(to) => Action::Call(to.into()), + None => Action::Create + }, + value: t.value.into(), + data: t.data.into(), + }.sign(&t.secret.into()) + } +} + +impl From for SignedTransaction { + fn from(t: ethjson::transaction::Transaction) -> Self { + let to: Option<_> = t.to.into(); + SignedTransaction { + unsigned: Transaction { + nonce: t.nonce.into(), + gas_price: t.gas_price.into(), + gas: t.gas_limit.into(), + action: match to { + Some(to) => Action::Call(to.into()), + None => Action::Create + }, + value: t.value.into(), + data: t.data.into(), + }, + r: t.r.into(), + s: t.s.into(), + v: t.v.into(), + sender: Cell::new(None), + hash: Cell::new(None) + } + } +} + +impl Transaction { + /// The message hash of the transaction. + pub fn hash(&self) -> H256 { + let mut stream = RlpStream::new(); + self.rlp_append_unsigned_transaction(&mut stream); + stream.out().sha3() + } + + /// Signs the transaction as coming from `sender`. + pub fn sign(self, secret: &Secret) -> SignedTransaction { + let sig = ec::sign(secret, &self.hash()); + let (r, s, v) = sig.unwrap().to_rsv(); + SignedTransaction { + unsigned: self, + r: r, + s: s, + v: v + 27, + hash: Cell::new(None), + sender: Cell::new(None), + } + } + + /// Useful for test incorrectly signed transactions. + #[cfg(test)] + pub fn invalid_sign(self) -> SignedTransaction { + SignedTransaction { + unsigned: self, + r: U256::zero(), + s: U256::zero(), + v: 0, + hash: Cell::new(None), + sender: Cell::new(None), + } + } + + /// Specify the sender; this won't survive the serialize/deserialize process, but can be cloned. + pub fn fake_sign(self, from: Address) -> SignedTransaction { + SignedTransaction { + unsigned: self, + r: U256::zero(), + s: U256::zero(), + v: 0, + hash: Cell::new(None), + sender: Cell::new(Some(from)), + } + } + + /// Get the transaction cost in gas for the given params. + pub fn gas_required_for(is_create: bool, data: &[u8], schedule: &Schedule) -> u64 { + data.iter().fold( + (if is_create {schedule.tx_create_gas} else {schedule.tx_gas}) as u64, + |g, b| g + (match *b { 0 => schedule.tx_data_zero_gas, _ => schedule.tx_data_non_zero_gas }) as u64 + ) + } + + /// Get the transaction cost in gas for this transaction. + pub fn gas_required(&self, schedule: &Schedule) -> u64 { + Self::gas_required_for(match self.action{Action::Create=>true, Action::Call(_)=>false}, &self.data, schedule) + } +} + +/// Signed transaction information. +#[derive(Debug, Clone, Eq)] +pub struct SignedTransaction { + /// Plain Transaction. + unsigned: Transaction, + /// The V field of the signature, either 27 or 28; helps describe the point on the curve. + v: u8, + /// The R field of the signature; helps describe the point on the curve. + r: U256, + /// The S field of the signature; helps describe the point on the curve. + s: U256, + /// Cached hash. + hash: Cell>, + /// Cached sender. + sender: Cell>, +} + +impl PartialEq for SignedTransaction { + fn eq(&self, other: &SignedTransaction) -> bool { + self.unsigned == other.unsigned && self.v == other.v && self.r == other.r && self.s == other.s + } +} + +impl Deref for SignedTransaction { + type Target = Transaction; + + fn deref(&self) -> &Self::Target { + &self.unsigned + } +} + +impl Decodable for SignedTransaction { + fn decode(decoder: &D) -> Result where D: Decoder { + let d = decoder.as_rlp(); + if d.item_count() != 9 { + return Err(DecoderError::RlpIncorrectListLen); + } + Ok(SignedTransaction { + unsigned: Transaction { + nonce: try!(d.val_at(0)), + gas_price: try!(d.val_at(1)), + gas: try!(d.val_at(2)), + action: try!(d.val_at(3)), + value: try!(d.val_at(4)), + data: try!(d.val_at(5)), + }, + v: try!(d.val_at(6)), + r: try!(d.val_at(7)), + s: try!(d.val_at(8)), + hash: Cell::new(None), + sender: Cell::new(None), + }) + } +} + +impl Encodable for SignedTransaction { + fn rlp_append(&self, s: &mut RlpStream) { self.rlp_append_sealed_transaction(s) } +} + +impl SignedTransaction { + /// Append object with a signature into RLP stream + pub fn rlp_append_sealed_transaction(&self, s: &mut RlpStream) { + s.begin_list(9); + s.append(&self.nonce); + s.append(&self.gas_price); + s.append(&self.gas); + match self.action { + Action::Create => s.append_empty_data(), + Action::Call(ref to) => s.append(to) + }; + s.append(&self.value); + s.append(&self.data); + s.append(&self.v); + s.append(&self.r); + s.append(&self.s); + } + + /// Get the hash of this header (sha3 of the RLP). + pub fn hash(&self) -> H256 { + let hash = self.hash.get(); + match hash { + Some(h) => h, + None => { + let h = self.rlp_sha3(); + self.hash.set(Some(h)); + h + } + } + } + + /// 0 is `v` is 27, 1 if 28, and 4 otherwise. + pub fn standard_v(&self) -> u8 { match self.v { 27 => 0, 28 => 1, _ => 4 } } + + /// Construct a signature object from the sig. + pub fn signature(&self) -> Signature { Signature::from_rsv(&From::from(&self.r), &From::from(&self.s), self.standard_v()) } + + /// Checks whether the signature has a low 's' value. + pub fn check_low_s(&self) -> Result<(), Error> { + if !ec::is_low_s(&self.s) { + Err(Error::Util(UtilError::Crypto(CryptoError::InvalidSignature))) + } else { + Ok(()) + } + } + + /// Returns transaction sender. + pub fn sender(&self) -> Result { + let sender = self.sender.get(); + match sender { + Some(s) => Ok(s), + None => { + let s = Address::from(try!(ec::recover(&self.signature(), &self.unsigned.hash())).sha3()); + self.sender.set(Some(s)); + Ok(s) + } + } + } + + /// Do basic validation, checking for valid signature and minimum gas, + // TODO: consider use in block validation. + #[cfg(test)] + #[cfg(feature = "json-tests")] + pub fn validate(self, schedule: &Schedule, require_low: bool) -> Result { + if require_low && !ec::is_low_s(&self.s) { + return Err(Error::Util(UtilError::Crypto(CryptoError::InvalidSignature))); + } + try!(self.sender()); + if self.gas < U256::from(self.gas_required(&schedule)) { + Err(From::from(TransactionError::InvalidGasLimit(OutOfBounds{min: Some(U256::from(self.gas_required(&schedule))), max: None, found: self.gas}))) + } else { + Ok(self) + } + } +} + +/// Signed Transaction that is a part of canon blockchain. +#[derive(Debug, PartialEq, Eq)] +pub struct LocalizedTransaction { + /// Signed part. + pub signed: SignedTransaction, + /// Block number. + pub block_number: BlockNumber, + /// Block hash. + pub block_hash: H256, + /// Transaction index within block. + pub transaction_index: usize +} + +impl Deref for LocalizedTransaction { + type Target = SignedTransaction; + + fn deref(&self) -> &Self::Target { + &self.signed + } +} + +#[test] +fn sender_test() { + let t: SignedTransaction = decode(&FromHex::from_hex("f85f800182520894095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap()); + assert_eq!(t.data, b""); + assert_eq!(t.gas, U256::from(0x5208u64)); + assert_eq!(t.gas_price, U256::from(0x01u64)); + assert_eq!(t.nonce, U256::from(0x00u64)); + if let Action::Call(ref to) = t.action { + assert_eq!(*to, address_from_hex("095e7baea6a6c7c4c2dfeb977efac326af552d87")); + } else { panic!(); } + assert_eq!(t.value, U256::from(0x0au64)); + assert_eq!(t.sender().unwrap(), address_from_hex("0f65fe9276bc9a24ae7083ae28e2660ef72df99e")); +} + +#[test] +fn signing() { + let key = KeyPair::create().unwrap(); + let t = Transaction { + action: Action::Create, + nonce: U256::from(42), + gas_price: U256::from(3000), + gas: U256::from(50_000), + value: U256::from(1), + data: b"Hello!".to_vec() + }.sign(&key.secret()); + assert_eq!(Address::from(key.public().sha3()), t.sender().unwrap()); +} + +#[test] +fn fake_signing() { + let t = Transaction { + action: Action::Create, + nonce: U256::from(42), + gas_price: U256::from(3000), + gas: U256::from(50_000), + value: U256::from(1), + data: b"Hello!".to_vec() + }.fake_sign(Address::from(0x69)); + assert_eq!(Address::from(0x69), t.sender().unwrap()); + + let t = t.clone(); + assert_eq!(Address::from(0x69), t.sender().unwrap()); +} From 7d27aceee478f39bee344ce1dd85259bdf3b16b6 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Thu, 5 May 2016 22:21:40 +0400 Subject: [PATCH 02/32] trash remove --- ethcore/src/transaction.rs | 383 ------------------------------------- 1 file changed, 383 deletions(-) delete mode 100644 ethcore/src/transaction.rs diff --git a/ethcore/src/transaction.rs b/ethcore/src/transaction.rs deleted file mode 100644 index ca54f26bb..000000000 --- a/ethcore/src/transaction.rs +++ /dev/null @@ -1,383 +0,0 @@ -// Copyright 2015, 2016 Ethcore (UK) Ltd. -// This file is part of Parity. - -// Parity is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Parity is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Parity. If not, see . - -//! Transaction data structure. - -use util::*; -use error::*; -use evm::Schedule; -use header::BlockNumber; -use ethjson; - -#[derive(Debug, Clone, PartialEq, Eq)] -/// Transaction action type. -pub enum Action { - /// Create creates new contract. - Create, - /// Calls contract at given address. - Call(Address), -} - -impl Default for Action { - fn default() -> Action { Action::Create } -} - -impl Decodable for Action { - fn decode(decoder: &D) -> Result where D: Decoder { - let rlp = decoder.as_rlp(); - if rlp.is_empty() { - Ok(Action::Create) - } else { - Ok(Action::Call(try!(rlp.as_val()))) - } - } -} - -/// A set of information describing an externally-originating message call -/// or contract creation operation. -#[derive(Default, Debug, Clone, PartialEq, Eq)] -pub struct Transaction { - /// Nonce. - pub nonce: U256, - /// Gas price. - pub gas_price: U256, - /// Gas paid up front for transaction execution. - pub gas: U256, - /// Action, can be either call or contract create. - pub action: Action, - /// Transfered value. - pub value: U256, - /// Transaction data. - pub data: Bytes, -} - -impl Transaction { - /// Append object with a without signature into RLP stream - pub fn rlp_append_unsigned_transaction(&self, s: &mut RlpStream) { - s.begin_list(6); - s.append(&self.nonce); - s.append(&self.gas_price); - s.append(&self.gas); - match self.action { - Action::Create => s.append_empty_data(), - Action::Call(ref to) => s.append(to) - }; - s.append(&self.value); - s.append(&self.data); - } -} - -impl From for SignedTransaction { - fn from(t: ethjson::state::Transaction) -> Self { - let to: Option<_> = t.to.into(); - Transaction { - nonce: t.nonce.into(), - gas_price: t.gas_price.into(), - gas: t.gas_limit.into(), - action: match to { - Some(to) => Action::Call(to.into()), - None => Action::Create - }, - value: t.value.into(), - data: t.data.into(), - }.sign(&t.secret.into()) - } -} - -impl From for SignedTransaction { - fn from(t: ethjson::transaction::Transaction) -> Self { - let to: Option<_> = t.to.into(); - SignedTransaction { - unsigned: Transaction { - nonce: t.nonce.into(), - gas_price: t.gas_price.into(), - gas: t.gas_limit.into(), - action: match to { - Some(to) => Action::Call(to.into()), - None => Action::Create - }, - value: t.value.into(), - data: t.data.into(), - }, - r: t.r.into(), - s: t.s.into(), - v: t.v.into(), - sender: Cell::new(None), - hash: Cell::new(None) - } - } -} - -impl Transaction { - /// The message hash of the transaction. - pub fn hash(&self) -> H256 { - let mut stream = RlpStream::new(); - self.rlp_append_unsigned_transaction(&mut stream); - stream.out().sha3() - } - - /// Signs the transaction as coming from `sender`. - pub fn sign(self, secret: &Secret) -> SignedTransaction { - let sig = ec::sign(secret, &self.hash()); - let (r, s, v) = sig.unwrap().to_rsv(); - SignedTransaction { - unsigned: self, - r: r, - s: s, - v: v + 27, - hash: Cell::new(None), - sender: Cell::new(None), - } - } - - /// Useful for test incorrectly signed transactions. - #[cfg(test)] - pub fn invalid_sign(self) -> SignedTransaction { - SignedTransaction { - unsigned: self, - r: U256::zero(), - s: U256::zero(), - v: 0, - hash: Cell::new(None), - sender: Cell::new(None), - } - } - - /// Specify the sender; this won't survive the serialize/deserialize process, but can be cloned. - pub fn fake_sign(self, from: Address) -> SignedTransaction { - SignedTransaction { - unsigned: self, - r: U256::zero(), - s: U256::zero(), - v: 0, - hash: Cell::new(None), - sender: Cell::new(Some(from)), - } - } - - /// Get the transaction cost in gas for the given params. - pub fn gas_required_for(is_create: bool, data: &[u8], schedule: &Schedule) -> u64 { - data.iter().fold( - (if is_create {schedule.tx_create_gas} else {schedule.tx_gas}) as u64, - |g, b| g + (match *b { 0 => schedule.tx_data_zero_gas, _ => schedule.tx_data_non_zero_gas }) as u64 - ) - } - - /// Get the transaction cost in gas for this transaction. - pub fn gas_required(&self, schedule: &Schedule) -> u64 { - Self::gas_required_for(match self.action{Action::Create=>true, Action::Call(_)=>false}, &self.data, schedule) - } -} - -/// Signed transaction information. -#[derive(Debug, Clone, Eq)] -pub struct SignedTransaction { - /// Plain Transaction. - unsigned: Transaction, - /// The V field of the signature, either 27 or 28; helps describe the point on the curve. - v: u8, - /// The R field of the signature; helps describe the point on the curve. - r: U256, - /// The S field of the signature; helps describe the point on the curve. - s: U256, - /// Cached hash. - hash: Cell>, - /// Cached sender. - sender: Cell>, -} - -impl PartialEq for SignedTransaction { - fn eq(&self, other: &SignedTransaction) -> bool { - self.unsigned == other.unsigned && self.v == other.v && self.r == other.r && self.s == other.s - } -} - -impl Deref for SignedTransaction { - type Target = Transaction; - - fn deref(&self) -> &Self::Target { - &self.unsigned - } -} - -impl Decodable for SignedTransaction { - fn decode(decoder: &D) -> Result where D: Decoder { - let d = decoder.as_rlp(); - if d.item_count() != 9 { - return Err(DecoderError::RlpIncorrectListLen); - } - Ok(SignedTransaction { - unsigned: Transaction { - nonce: try!(d.val_at(0)), - gas_price: try!(d.val_at(1)), - gas: try!(d.val_at(2)), - action: try!(d.val_at(3)), - value: try!(d.val_at(4)), - data: try!(d.val_at(5)), - }, - v: try!(d.val_at(6)), - r: try!(d.val_at(7)), - s: try!(d.val_at(8)), - hash: Cell::new(None), - sender: Cell::new(None), - }) - } -} - -impl Encodable for SignedTransaction { - fn rlp_append(&self, s: &mut RlpStream) { self.rlp_append_sealed_transaction(s) } -} - -impl SignedTransaction { - /// Append object with a signature into RLP stream - pub fn rlp_append_sealed_transaction(&self, s: &mut RlpStream) { - s.begin_list(9); - s.append(&self.nonce); - s.append(&self.gas_price); - s.append(&self.gas); - match self.action { - Action::Create => s.append_empty_data(), - Action::Call(ref to) => s.append(to) - }; - s.append(&self.value); - s.append(&self.data); - s.append(&self.v); - s.append(&self.r); - s.append(&self.s); - } - - /// Get the hash of this header (sha3 of the RLP). - pub fn hash(&self) -> H256 { - let hash = self.hash.get(); - match hash { - Some(h) => h, - None => { - let h = self.rlp_sha3(); - self.hash.set(Some(h)); - h - } - } - } - - /// 0 is `v` is 27, 1 if 28, and 4 otherwise. - pub fn standard_v(&self) -> u8 { match self.v { 27 => 0, 28 => 1, _ => 4 } } - - /// Construct a signature object from the sig. - pub fn signature(&self) -> Signature { Signature::from_rsv(&From::from(&self.r), &From::from(&self.s), self.standard_v()) } - - /// Checks whether the signature has a low 's' value. - pub fn check_low_s(&self) -> Result<(), Error> { - if !ec::is_low_s(&self.s) { - Err(Error::Util(UtilError::Crypto(CryptoError::InvalidSignature))) - } else { - Ok(()) - } - } - - /// Returns transaction sender. - pub fn sender(&self) -> Result { - let sender = self.sender.get(); - match sender { - Some(s) => Ok(s), - None => { - let s = Address::from(try!(ec::recover(&self.signature(), &self.unsigned.hash())).sha3()); - self.sender.set(Some(s)); - Ok(s) - } - } - } - - /// Do basic validation, checking for valid signature and minimum gas, - // TODO: consider use in block validation. - #[cfg(test)] - #[cfg(feature = "json-tests")] - pub fn validate(self, schedule: &Schedule, require_low: bool) -> Result { - if require_low && !ec::is_low_s(&self.s) { - return Err(Error::Util(UtilError::Crypto(CryptoError::InvalidSignature))); - } - try!(self.sender()); - if self.gas < U256::from(self.gas_required(&schedule)) { - Err(From::from(TransactionError::InvalidGasLimit(OutOfBounds{min: Some(U256::from(self.gas_required(&schedule))), max: None, found: self.gas}))) - } else { - Ok(self) - } - } -} - -/// Signed Transaction that is a part of canon blockchain. -#[derive(Debug, PartialEq, Eq)] -pub struct LocalizedTransaction { - /// Signed part. - pub signed: SignedTransaction, - /// Block number. - pub block_number: BlockNumber, - /// Block hash. - pub block_hash: H256, - /// Transaction index within block. - pub transaction_index: usize -} - -impl Deref for LocalizedTransaction { - type Target = SignedTransaction; - - fn deref(&self) -> &Self::Target { - &self.signed - } -} - -#[test] -fn sender_test() { - let t: SignedTransaction = decode(&FromHex::from_hex("f85f800182520894095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap()); - assert_eq!(t.data, b""); - assert_eq!(t.gas, U256::from(0x5208u64)); - assert_eq!(t.gas_price, U256::from(0x01u64)); - assert_eq!(t.nonce, U256::from(0x00u64)); - if let Action::Call(ref to) = t.action { - assert_eq!(*to, address_from_hex("095e7baea6a6c7c4c2dfeb977efac326af552d87")); - } else { panic!(); } - assert_eq!(t.value, U256::from(0x0au64)); - assert_eq!(t.sender().unwrap(), address_from_hex("0f65fe9276bc9a24ae7083ae28e2660ef72df99e")); -} - -#[test] -fn signing() { - let key = KeyPair::create().unwrap(); - let t = Transaction { - action: Action::Create, - nonce: U256::from(42), - gas_price: U256::from(3000), - gas: U256::from(50_000), - value: U256::from(1), - data: b"Hello!".to_vec() - }.sign(&key.secret()); - assert_eq!(Address::from(key.public().sha3()), t.sender().unwrap()); -} - -#[test] -fn fake_signing() { - let t = Transaction { - action: Action::Create, - nonce: U256::from(42), - gas_price: U256::from(3000), - gas: U256::from(50_000), - value: U256::from(1), - data: b"Hello!".to_vec() - }.fake_sign(Address::from(0x69)); - assert_eq!(Address::from(0x69), t.sender().unwrap()); - - let t = t.clone(); - assert_eq!(Address::from(0x69), t.sender().unwrap()); -} From 271d3f3e57031ea8dc26245d3700b8414ec31859 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Thu, 5 May 2016 22:37:30 +0400 Subject: [PATCH 03/32] ids move --- ethcore/src/client/mod.rs | 3 +-- ethcore/src/{client => types}/ids.rs | 0 ethcore/src/types/mod.rs | 1 + 3 files changed, 2 insertions(+), 2 deletions(-) rename ethcore/src/{client => types}/ids.rs (100%) diff --git a/ethcore/src/client/mod.rs b/ethcore/src/client/mod.rs index 90dd78015..b030630be 100644 --- a/ethcore/src/client/mod.rs +++ b/ethcore/src/client/mod.rs @@ -18,13 +18,12 @@ mod client; mod config; -mod ids; mod test_client; mod trace; pub use self::client::*; pub use self::config::{ClientConfig, BlockQueueConfig, BlockChainConfig, Switch}; -pub use self::ids::{BlockId, TransactionId, UncleId, TraceId}; +pub use types::ids::*; pub use self::test_client::{TestBlockChainClient, EachBlockWith}; pub use self::trace::Filter as TraceFilter; pub use executive::{Executed, Executive, TransactOptions}; diff --git a/ethcore/src/client/ids.rs b/ethcore/src/types/ids.rs similarity index 100% rename from ethcore/src/client/ids.rs rename to ethcore/src/types/ids.rs diff --git a/ethcore/src/types/mod.rs b/ethcore/src/types/mod.rs index 438dbafb0..eb815ffa9 100644 --- a/ethcore/src/types/mod.rs +++ b/ethcore/src/types/mod.rs @@ -17,3 +17,4 @@ //! Types used in the public api pub mod transaction; +pub mod ids; From 7e9779e334838b04954b79d8402e31d4e5e42224 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Thu, 5 May 2016 22:56:44 +0400 Subject: [PATCH 04/32] receipt --- ethcore/src/lib.rs | 1 - ethcore/src/types/mod.rs | 1 + ethcore/src/{ => types}/receipt.rs | 0 3 files changed, 1 insertion(+), 1 deletion(-) rename ethcore/src/{ => types}/receipt.rs (100%) diff --git a/ethcore/src/lib.rs b/ethcore/src/lib.rs index 45692f556..d55628bd9 100644 --- a/ethcore/src/lib.rs +++ b/ethcore/src/lib.rs @@ -102,7 +102,6 @@ pub mod log_entry; pub mod trace; pub mod spec; pub mod views; -pub mod receipt; pub mod pod_state; mod db; diff --git a/ethcore/src/types/mod.rs b/ethcore/src/types/mod.rs index eb815ffa9..77a473211 100644 --- a/ethcore/src/types/mod.rs +++ b/ethcore/src/types/mod.rs @@ -18,3 +18,4 @@ pub mod transaction; pub mod ids; +pub mod receipt; diff --git a/ethcore/src/receipt.rs b/ethcore/src/types/receipt.rs similarity index 100% rename from ethcore/src/receipt.rs rename to ethcore/src/types/receipt.rs From b6d1801e12ab16fc5c752aa2b907b5d9b0d94ace Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Thu, 5 May 2016 23:04:59 +0400 Subject: [PATCH 05/32] tree-route --- ethcore/src/blockchain/blockchain.rs | 2 +- ethcore/src/blockchain/mod.rs | 3 +-- ethcore/src/types/mod.rs | 1 + ethcore/src/{blockchain => types}/tree_route.rs | 0 4 files changed, 3 insertions(+), 3 deletions(-) rename ethcore/src/{blockchain => types}/tree_route.rs (100%) diff --git a/ethcore/src/blockchain/blockchain.rs b/ethcore/src/blockchain/blockchain.rs index 7e5f896fd..d95152341 100644 --- a/ethcore/src/blockchain/blockchain.rs +++ b/ethcore/src/blockchain/blockchain.rs @@ -27,7 +27,7 @@ use chainfilter::{ChainFilter, BloomIndex, FilterDataSource}; use blockchain::block_info::{BlockInfo, BlockLocation, BranchBecomingCanonChainData}; use blockchain::best_block::BestBlock; use blockchain::bloom_indexer::BloomIndexer; -use blockchain::tree_route::TreeRoute; +use types::tree_route::TreeRoute; use blockchain::update::ExtrasUpdate; use blockchain::{CacheSize, ImportRoute}; use db::{Writable, Readable, Key, CacheUpdatePolicy}; diff --git a/ethcore/src/blockchain/mod.rs b/ethcore/src/blockchain/mod.rs index 29a4ee684..62196825f 100644 --- a/ethcore/src/blockchain/mod.rs +++ b/ethcore/src/blockchain/mod.rs @@ -21,7 +21,6 @@ mod best_block; mod block_info; mod bloom_indexer; mod cache; -mod tree_route; mod update; mod import_route; #[cfg(test)] @@ -29,5 +28,5 @@ mod generator; pub use self::blockchain::{BlockProvider, BlockChain, BlockChainConfig}; pub use self::cache::CacheSize; -pub use self::tree_route::TreeRoute; +pub use types::tree_route::TreeRoute; pub use self::import_route::ImportRoute; diff --git a/ethcore/src/types/mod.rs b/ethcore/src/types/mod.rs index 77a473211..ad8853216 100644 --- a/ethcore/src/types/mod.rs +++ b/ethcore/src/types/mod.rs @@ -19,3 +19,4 @@ pub mod transaction; pub mod ids; pub mod receipt; +pub mod tree_route; diff --git a/ethcore/src/blockchain/tree_route.rs b/ethcore/src/types/tree_route.rs similarity index 100% rename from ethcore/src/blockchain/tree_route.rs rename to ethcore/src/types/tree_route.rs From beb33672bd03da604295203a14dfb2fb3536fd15 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Thu, 5 May 2016 23:47:07 +0400 Subject: [PATCH 06/32] blockchain info --- ethcore/src/client/client.rs | 16 +------------- ethcore/src/types/blockchain_info.rs | 33 ++++++++++++++++++++++++++++ ethcore/src/types/mod.rs | 1 + 3 files changed, 35 insertions(+), 15 deletions(-) create mode 100644 ethcore/src/types/blockchain_info.rs diff --git a/ethcore/src/client/client.rs b/ethcore/src/client/client.rs index 23b81b34e..e9aba8415 100644 --- a/ethcore/src/client/client.rs +++ b/ethcore/src/client/client.rs @@ -44,6 +44,7 @@ use receipt::LocalizedReceipt; pub use blockchain::CacheSize as BlockChainCacheSize; use trace::{TraceDB, ImportRequest as TraceImportRequest, LocalizedTrace, Database as TraceDatabase}; use trace; +pub use types::blockchain_info::BlockChainInfo; /// General block status #[derive(Debug, Eq, PartialEq)] @@ -58,21 +59,6 @@ pub enum BlockStatus { Unknown, } -/// Information about the blockchain gathered together. -#[derive(Debug)] -pub struct BlockChainInfo { - /// Blockchain difficulty. - pub total_difficulty: U256, - /// Block queue difficulty. - pub pending_total_difficulty: U256, - /// Genesis block hash. - pub genesis_hash: H256, - /// Best blockchain block hash. - pub best_block_hash: H256, - /// Best blockchain block number. - pub best_block_number: BlockNumber -} - impl fmt::Display for BlockChainInfo { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "#{}.{}", self.best_block_number, self.best_block_hash) diff --git a/ethcore/src/types/blockchain_info.rs b/ethcore/src/types/blockchain_info.rs new file mode 100644 index 000000000..aacf77baf --- /dev/null +++ b/ethcore/src/types/blockchain_info.rs @@ -0,0 +1,33 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +use util::*; +use header::BlockNumber; + +/// Information about the blockchain gathered together. +#[derive(Debug)] +pub struct BlockChainInfo { + /// Blockchain difficulty. + pub total_difficulty: U256, + /// Block queue difficulty. + pub pending_total_difficulty: U256, + /// Genesis block hash. + pub genesis_hash: H256, + /// Best blockchain block hash. + pub best_block_hash: H256, + /// Best blockchain block number. + pub best_block_number: BlockNumber +} diff --git a/ethcore/src/types/mod.rs b/ethcore/src/types/mod.rs index ad8853216..b7f9ee3ce 100644 --- a/ethcore/src/types/mod.rs +++ b/ethcore/src/types/mod.rs @@ -20,3 +20,4 @@ pub mod transaction; pub mod ids; pub mod receipt; pub mod tree_route; +pub mod blockchain_info; From a8affa6dee3cc654f57c84805927bcf43f07ace5 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Thu, 5 May 2016 23:57:10 +0400 Subject: [PATCH 07/32] log_entry move --- ethcore/src/lib.rs | 1 - ethcore/src/{ => types}/log_entry.rs | 0 ethcore/src/types/mod.rs | 1 + 3 files changed, 1 insertion(+), 1 deletion(-) rename ethcore/src/{ => types}/log_entry.rs (100%) diff --git a/ethcore/src/lib.rs b/ethcore/src/lib.rs index d55628bd9..b18efa54d 100644 --- a/ethcore/src/lib.rs +++ b/ethcore/src/lib.rs @@ -98,7 +98,6 @@ pub mod ethereum; pub mod filter; pub mod header; pub mod service; -pub mod log_entry; pub mod trace; pub mod spec; pub mod views; diff --git a/ethcore/src/log_entry.rs b/ethcore/src/types/log_entry.rs similarity index 100% rename from ethcore/src/log_entry.rs rename to ethcore/src/types/log_entry.rs diff --git a/ethcore/src/types/mod.rs b/ethcore/src/types/mod.rs index b7f9ee3ce..7557fd89b 100644 --- a/ethcore/src/types/mod.rs +++ b/ethcore/src/types/mod.rs @@ -21,3 +21,4 @@ pub mod ids; pub mod receipt; pub mod tree_route; pub mod blockchain_info; +pub mod log_entry; From 2a721b4eda7f80f5b70e48fe226a218483c68ceb Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Fri, 6 May 2016 00:17:03 +0400 Subject: [PATCH 08/32] trace filter moved --- ethcore/src/trace/mod.rs | 5 ++--- ethcore/src/types/mod.rs | 1 + .../{trace => types/trace_types}/filter.rs | 4 ++-- ethcore/src/types/trace_types/mod.rs | 19 +++++++++++++++++++ 4 files changed, 24 insertions(+), 5 deletions(-) rename ethcore/src/{trace => types/trace_types}/filter.rs (99%) create mode 100644 ethcore/src/types/trace_types/mod.rs diff --git a/ethcore/src/trace/mod.rs b/ethcore/src/trace/mod.rs index 831a55cd5..a57e72583 100644 --- a/ethcore/src/trace/mod.rs +++ b/ethcore/src/trace/mod.rs @@ -21,8 +21,7 @@ mod bloom; mod config; mod db; mod executive_tracer; -mod filter; -mod flat; +pub mod flat; mod import; mod localized; mod noop_tracer; @@ -34,7 +33,7 @@ pub use self::db::TraceDB; pub use self::trace::Trace; pub use self::noop_tracer::NoopTracer; pub use self::executive_tracer::ExecutiveTracer; -pub use self::filter::{Filter, AddressesFilter}; +pub use types::trace_types::filter::{Filter, AddressesFilter}; pub use self::import::ImportRequest; pub use self::localized::LocalizedTrace; use util::{Bytes, Address, U256, H256}; diff --git a/ethcore/src/types/mod.rs b/ethcore/src/types/mod.rs index 7557fd89b..30b1fe801 100644 --- a/ethcore/src/types/mod.rs +++ b/ethcore/src/types/mod.rs @@ -22,3 +22,4 @@ pub mod receipt; pub mod tree_route; pub mod blockchain_info; pub mod log_entry; +pub mod trace_types; diff --git a/ethcore/src/trace/filter.rs b/ethcore/src/types/trace_types/filter.rs similarity index 99% rename from ethcore/src/trace/filter.rs rename to ethcore/src/types/trace_types/filter.rs index d1f699c52..eb6886268 100644 --- a/ethcore/src/trace/filter.rs +++ b/ethcore/src/types/trace_types/filter.rs @@ -19,8 +19,8 @@ use bloomchain::{Filter as BloomFilter, Bloom, Number}; use util::{Address, FixedHash}; use util::sha3::Hashable; use basic_types::LogBloom; -use super::flat::FlatTrace; -use super::trace::Action; +use trace::flat::FlatTrace; +use trace::trace::Action; /// Addresses filter. /// diff --git a/ethcore/src/types/trace_types/mod.rs b/ethcore/src/types/trace_types/mod.rs new file mode 100644 index 000000000..3afdbe934 --- /dev/null +++ b/ethcore/src/types/trace_types/mod.rs @@ -0,0 +1,19 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +//! Types used in the public api + +pub mod filter; From 25c88b7529edacc3fefeaebdf1a049283ec94e59 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Fri, 6 May 2016 00:33:43 +0400 Subject: [PATCH 09/32] executed & trace moved --- ethcore/src/error.rs | 42 +------ ethcore/src/executive.rs | 41 +------ ethcore/src/trace/mod.rs | 4 +- ethcore/src/types/executed.rs | 105 ++++++++++++++++++ ethcore/src/types/mod.rs | 1 + ethcore/src/types/trace_types/filter.rs | 2 +- ethcore/src/types/trace_types/mod.rs | 1 + .../src/{trace => types/trace_types}/trace.rs | 0 8 files changed, 113 insertions(+), 83 deletions(-) create mode 100644 ethcore/src/types/executed.rs rename ethcore/src/{trace => types/trace_types}/trace.rs (100%) diff --git a/ethcore/src/error.rs b/ethcore/src/error.rs index 922d72700..edec7c959 100644 --- a/ethcore/src/error.rs +++ b/ethcore/src/error.rs @@ -20,47 +20,7 @@ use util::*; use header::BlockNumber; use basic_types::LogBloom; -/// Result of executing the transaction. -#[derive(PartialEq, Debug)] -pub enum ExecutionError { - /// Returned when there gas paid for transaction execution is - /// lower than base gas required. - NotEnoughBaseGas { - /// Absolute minimum gas required. - required: U256, - /// Gas provided. - got: U256 - }, - /// Returned when block (gas_used + gas) > gas_limit. - /// - /// If gas =< gas_limit, upstream may try to execute the transaction - /// in next block. - BlockGasLimitReached { - /// Gas limit of block for transaction. - gas_limit: U256, - /// Gas used in block prior to transaction. - gas_used: U256, - /// Amount of gas in block. - gas: U256 - }, - /// Returned when transaction nonce does not match state nonce. - InvalidNonce { - /// Nonce expected. - expected: U256, - /// Nonce found. - got: U256 - }, - /// Returned when cost of transaction (value + gas_price * gas) exceeds - /// current sender balance. - NotEnoughCash { - /// Minimum required balance. - required: U512, - /// Actual balance. - got: U512 - }, - /// Returned when internal evm error occurs. - Internal -} +pub use types::executed::ExecutionError; #[derive(Debug, PartialEq)] /// Errors concerning transaction processing. diff --git a/ethcore/src/executive.rs b/ethcore/src/executive.rs index 4247114ef..10665e2ce 100644 --- a/ethcore/src/executive.rs +++ b/ethcore/src/executive.rs @@ -24,6 +24,8 @@ use substate::*; use trace::{Trace, Tracer, NoopTracer, ExecutiveTracer}; use crossbeam; +pub use types::executed::{Executed, ExecutionResult}; + /// Max depth to avoid stack overflow (when it's reached we start a new thread with VM) /// TODO [todr] We probably need some more sophisticated calculations here (limit on my machine 132) /// Maybe something like here: `https://github.com/ethereum/libethereum/blob/4db169b8504f2b87f7d5a481819cfb959fc65f6c/libethereum/ExtVM.cpp` @@ -45,45 +47,6 @@ pub struct TransactOptions { pub check_nonce: bool, } -/// Transaction execution receipt. -#[derive(Debug, PartialEq, Clone)] -pub struct Executed { - /// Gas paid up front for execution of transaction. - pub gas: U256, - - /// Gas used during execution of transaction. - pub gas_used: U256, - - /// Gas refunded after the execution of transaction. - /// To get gas that was required up front, add `refunded` and `gas_used`. - pub refunded: U256, - - /// Cumulative gas used in current block so far. - /// - /// `cumulative_gas_used = gas_used(t0) + gas_used(t1) + ... gas_used(tn)` - /// - /// where `tn` is current transaction. - pub cumulative_gas_used: U256, - - /// Vector of logs generated by transaction. - pub logs: Vec, - - /// Addresses of contracts created during execution of transaction. - /// Ordered from earliest creation. - /// - /// eg. sender creates contract A and A in constructor creates contract B - /// - /// B creation ends first, and it will be the first element of the vector. - pub contracts_created: Vec
, - /// Transaction output. - pub output: Bytes, - /// The trace of this transaction. - pub trace: Option, -} - -/// Transaction execution result. -pub type ExecutionResult = Result; - /// Transaction executor. pub struct Executive<'a> { state: &'a mut State, diff --git a/ethcore/src/trace/mod.rs b/ethcore/src/trace/mod.rs index a57e72583..44f53fa9c 100644 --- a/ethcore/src/trace/mod.rs +++ b/ethcore/src/trace/mod.rs @@ -25,12 +25,12 @@ pub mod flat; mod import; mod localized; mod noop_tracer; -pub mod trace; +pub use types::trace_types::*; pub use self::block::BlockTraces; pub use self::config::{Config, Switch}; pub use self::db::TraceDB; -pub use self::trace::Trace; +pub use types::trace_types::trace::Trace; pub use self::noop_tracer::NoopTracer; pub use self::executive_tracer::ExecutiveTracer; pub use types::trace_types::filter::{Filter, AddressesFilter}; diff --git a/ethcore/src/types/executed.rs b/ethcore/src/types/executed.rs new file mode 100644 index 000000000..92e297eec --- /dev/null +++ b/ethcore/src/types/executed.rs @@ -0,0 +1,105 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +//! Transaction execution format module. + +use util::*; +use trace::Trace; +use types::log_entry::LogEntry; + + + +/// Transaction execution receipt. +#[derive(Debug, PartialEq, Clone)] +pub struct Executed { + /// Gas paid up front for execution of transaction. + pub gas: U256, + + /// Gas used during execution of transaction. + pub gas_used: U256, + + /// Gas refunded after the execution of transaction. + /// To get gas that was required up front, add `refunded` and `gas_used`. + pub refunded: U256, + + /// Cumulative gas used in current block so far. + /// + /// `cumulative_gas_used = gas_used(t0) + gas_used(t1) + ... gas_used(tn)` + /// + /// where `tn` is current transaction. + pub cumulative_gas_used: U256, + + /// Vector of logs generated by transaction. + pub logs: Vec, + + /// Addresses of contracts created during execution of transaction. + /// Ordered from earliest creation. + /// + /// eg. sender creates contract A and A in constructor creates contract B + /// + /// B creation ends first, and it will be the first element of the vector. + pub contracts_created: Vec
, + /// Transaction output. + pub output: Bytes, + /// The trace of this transaction. + pub trace: Option, +} + +/// Result of executing the transaction. +#[derive(PartialEq, Debug)] +pub enum ExecutionError { + /// Returned when there gas paid for transaction execution is + /// lower than base gas required. + NotEnoughBaseGas { + /// Absolute minimum gas required. + required: U256, + /// Gas provided. + got: U256 + }, + /// Returned when block (gas_used + gas) > gas_limit. + /// + /// If gas =< gas_limit, upstream may try to execute the transaction + /// in next block. + BlockGasLimitReached { + /// Gas limit of block for transaction. + gas_limit: U256, + /// Gas used in block prior to transaction. + gas_used: U256, + /// Amount of gas in block. + gas: U256 + }, + /// Returned when transaction nonce does not match state nonce. + InvalidNonce { + /// Nonce expected. + expected: U256, + /// Nonce found. + got: U256 + }, + /// Returned when cost of transaction (value + gas_price * gas) exceeds + /// current sender balance. + NotEnoughCash { + /// Minimum required balance. + required: U512, + /// Actual balance. + got: U512 + }, + /// Returned when internal evm error occurs. + Internal +} + + +/// Transaction execution result. +pub type ExecutionResult = Result; diff --git a/ethcore/src/types/mod.rs b/ethcore/src/types/mod.rs index 30b1fe801..9ad2fe74b 100644 --- a/ethcore/src/types/mod.rs +++ b/ethcore/src/types/mod.rs @@ -23,3 +23,4 @@ pub mod tree_route; pub mod blockchain_info; pub mod log_entry; pub mod trace_types; +pub mod executed; diff --git a/ethcore/src/types/trace_types/filter.rs b/ethcore/src/types/trace_types/filter.rs index eb6886268..25ee5954a 100644 --- a/ethcore/src/types/trace_types/filter.rs +++ b/ethcore/src/types/trace_types/filter.rs @@ -20,7 +20,7 @@ use util::{Address, FixedHash}; use util::sha3::Hashable; use basic_types::LogBloom; use trace::flat::FlatTrace; -use trace::trace::Action; +use types::trace_types::trace::Action; /// Addresses filter. /// diff --git a/ethcore/src/types/trace_types/mod.rs b/ethcore/src/types/trace_types/mod.rs index 3afdbe934..7100e9823 100644 --- a/ethcore/src/types/trace_types/mod.rs +++ b/ethcore/src/types/trace_types/mod.rs @@ -17,3 +17,4 @@ //! Types used in the public api pub mod filter; +pub mod trace; diff --git a/ethcore/src/trace/trace.rs b/ethcore/src/types/trace_types/trace.rs similarity index 100% rename from ethcore/src/trace/trace.rs rename to ethcore/src/types/trace_types/trace.rs From e95f61019521473f2600bde06717abd12fba9bb7 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Fri, 6 May 2016 00:38:13 +0400 Subject: [PATCH 10/32] localized trace moved --- ethcore/src/trace/mod.rs | 1 - ethcore/src/{trace => types/trace_types}/localized.rs | 0 ethcore/src/types/trace_types/mod.rs | 1 + 3 files changed, 1 insertion(+), 1 deletion(-) rename ethcore/src/{trace => types/trace_types}/localized.rs (100%) diff --git a/ethcore/src/trace/mod.rs b/ethcore/src/trace/mod.rs index 44f53fa9c..01763a167 100644 --- a/ethcore/src/trace/mod.rs +++ b/ethcore/src/trace/mod.rs @@ -23,7 +23,6 @@ mod db; mod executive_tracer; pub mod flat; mod import; -mod localized; mod noop_tracer; pub use types::trace_types::*; diff --git a/ethcore/src/trace/localized.rs b/ethcore/src/types/trace_types/localized.rs similarity index 100% rename from ethcore/src/trace/localized.rs rename to ethcore/src/types/trace_types/localized.rs diff --git a/ethcore/src/types/trace_types/mod.rs b/ethcore/src/types/trace_types/mod.rs index 7100e9823..db429a8f4 100644 --- a/ethcore/src/types/trace_types/mod.rs +++ b/ethcore/src/types/trace_types/mod.rs @@ -18,3 +18,4 @@ pub mod filter; pub mod trace; +pub mod localized; From 14bcca54d2a1bf309507ce3b802d400a41032d41 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Fri, 6 May 2016 00:47:47 +0400 Subject: [PATCH 11/32] block status moved --- ethcore/src/client/client.rs | 14 +------------- ethcore/src/types/block_status.rs | 30 ++++++++++++++++++++++++++++++ ethcore/src/types/executed.rs | 2 -- ethcore/src/types/ids.rs | 3 --- ethcore/src/types/mod.rs | 1 + 5 files changed, 32 insertions(+), 18 deletions(-) create mode 100644 ethcore/src/types/block_status.rs diff --git a/ethcore/src/client/client.rs b/ethcore/src/client/client.rs index e9aba8415..168e49ec3 100644 --- a/ethcore/src/client/client.rs +++ b/ethcore/src/client/client.rs @@ -45,19 +45,7 @@ pub use blockchain::CacheSize as BlockChainCacheSize; use trace::{TraceDB, ImportRequest as TraceImportRequest, LocalizedTrace, Database as TraceDatabase}; use trace; pub use types::blockchain_info::BlockChainInfo; - -/// General block status -#[derive(Debug, Eq, PartialEq)] -pub enum BlockStatus { - /// Part of the blockchain. - InChain, - /// Queued for import. - Queued, - /// Known as bad. - Bad, - /// Unknown. - Unknown, -} +pub use types::block_status::BlockStatus; impl fmt::Display for BlockChainInfo { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { diff --git a/ethcore/src/types/block_status.rs b/ethcore/src/types/block_status.rs new file mode 100644 index 000000000..60776748c --- /dev/null +++ b/ethcore/src/types/block_status.rs @@ -0,0 +1,30 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +//! Block status description module + +/// General block status +#[derive(Debug, Eq, PartialEq)] +pub enum BlockStatus { + /// Part of the blockchain. + InChain, + /// Queued for import. + Queued, + /// Known as bad. + Bad, + /// Unknown. + Unknown, +} diff --git a/ethcore/src/types/executed.rs b/ethcore/src/types/executed.rs index 92e297eec..cd671269f 100644 --- a/ethcore/src/types/executed.rs +++ b/ethcore/src/types/executed.rs @@ -20,8 +20,6 @@ use util::*; use trace::Trace; use types::log_entry::LogEntry; - - /// Transaction execution receipt. #[derive(Debug, PartialEq, Clone)] pub struct Executed { diff --git a/ethcore/src/types/ids.rs b/ethcore/src/types/ids.rs index 39a19c82d..cdab4ee3f 100644 --- a/ethcore/src/types/ids.rs +++ b/ethcore/src/types/ids.rs @@ -60,6 +60,3 @@ pub struct UncleId ( pub usize ); -sized_binary_map!(TransactionId); -sized_binary_map!(UncleId); -sized_binary_map!(BlockId); diff --git a/ethcore/src/types/mod.rs b/ethcore/src/types/mod.rs index 9ad2fe74b..369591dfd 100644 --- a/ethcore/src/types/mod.rs +++ b/ethcore/src/types/mod.rs @@ -24,3 +24,4 @@ pub mod blockchain_info; pub mod log_entry; pub mod trace_types; pub mod executed; +pub mod block_status; From 00ce4aaa26865b63ed0a7544a49e6e40a22c49a7 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Fri, 6 May 2016 01:10:50 +0400 Subject: [PATCH 12/32] build scripts and codegen refs --- ethcore/Cargo.toml | 5 +++++ ethcore/build.rs | 34 ++++++++++++++++++++++++++++++++++ ethcore/src/types/mod.rs | 11 ++--------- ethcore/src/types/mod.rs.in | 25 +++++++++++++++++++++++++ 4 files changed, 66 insertions(+), 9 deletions(-) create mode 100644 ethcore/build.rs diff --git a/ethcore/Cargo.toml b/ethcore/Cargo.toml index b5f50b207..1b581959d 100644 --- a/ethcore/Cargo.toml +++ b/ethcore/Cargo.toml @@ -5,6 +5,11 @@ license = "GPL-3.0" name = "ethcore" version = "1.2.0" authors = ["Ethcore "] +build = "build.rs" + +[build-dependencies] +syntex = "*" +"ethcore-ipc-codegen" = { path = "../ipc/codegen" } [dependencies] log = "0.3" diff --git a/ethcore/build.rs b/ethcore/build.rs new file mode 100644 index 000000000..e0f267bba --- /dev/null +++ b/ethcore/build.rs @@ -0,0 +1,34 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +extern crate syntex; +extern crate ethcore_ipc_codegen as codegen; + +use std::env; +use std::path::Path; + +fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + // serialization pass + { + let src = Path::new("src/types/mod.rs.in"); + let dst = Path::new(&out_dir).join("types.rs"); + let mut registry = syntex::Registry::new(); + codegen::register(&mut registry); + registry.expand("", &src, &dst).unwrap(); + } + +} diff --git a/ethcore/src/types/mod.rs b/ethcore/src/types/mod.rs index 369591dfd..112f79c32 100644 --- a/ethcore/src/types/mod.rs +++ b/ethcore/src/types/mod.rs @@ -16,12 +16,5 @@ //! Types used in the public api -pub mod transaction; -pub mod ids; -pub mod receipt; -pub mod tree_route; -pub mod blockchain_info; -pub mod log_entry; -pub mod trace_types; -pub mod executed; -pub mod block_status; +#![allow(dead_code, unused_assignments, unused_variables)] // codegen issues +include!(concat!(env!("OUT_DIR"), "/types.rs")); diff --git a/ethcore/src/types/mod.rs.in b/ethcore/src/types/mod.rs.in index e69de29bb..1f67a9184 100644 --- a/ethcore/src/types/mod.rs.in +++ b/ethcore/src/types/mod.rs.in @@ -0,0 +1,25 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +pub mod transaction; +pub mod ids; +pub mod receipt; +pub mod tree_route; +pub mod blockchain_info; +pub mod log_entry; +pub mod trace_types; +pub mod executed; +pub mod block_status; From 96a4eb5b9e441a6500d2464eec4c6e698884776b Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Fri, 6 May 2016 17:01:33 +0400 Subject: [PATCH 13/32] Cargo.lock update --- Cargo.lock | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 58809ed45..1cd8383d8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -240,6 +240,7 @@ dependencies = [ "env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "ethash 1.2.0", "ethcore-devtools 1.2.0", + "ethcore-ipc-codegen 1.2.0", "ethcore-util 1.2.0", "ethjson 0.1.0", "heapsize 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", @@ -248,6 +249,7 @@ dependencies = [ "num_cpus 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)", "rust-crypto 0.2.35 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex 0.32.0 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.35 (registry+https://github.com/rust-lang/crates.io-index)", ] From 29531ae72fc6869846ad24eb1a7295322208c52a Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Fri, 6 May 2016 17:16:03 +0400 Subject: [PATCH 14/32] binary for blockstatus, blockchaininfo --- Cargo.lock | 1 + ethcore/Cargo.toml | 1 + ethcore/src/lib.rs | 1 + ethcore/src/types/block_status.rs | 5 ++++- ethcore/src/types/blockchain_info.rs | 7 +++++-- util/bigint/src/uint.rs | 8 ++++---- util/src/hash.rs | 4 ++-- 7 files changed, 18 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1cd8383d8..df305aa8c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -240,6 +240,7 @@ dependencies = [ "env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "ethash 1.2.0", "ethcore-devtools 1.2.0", + "ethcore-ipc 1.2.0", "ethcore-ipc-codegen 1.2.0", "ethcore-util 1.2.0", "ethjson 0.1.0", diff --git a/ethcore/Cargo.toml b/ethcore/Cargo.toml index 1b581959d..d0b1927f6 100644 --- a/ethcore/Cargo.toml +++ b/ethcore/Cargo.toml @@ -28,6 +28,7 @@ lazy_static = "0.1" ethcore-devtools = { path = "../devtools" } ethjson = { path = "../json" } bloomchain = "0.1" +"ethcore-ipc" = { path = "../ipc/rpc" } [features] jit = ["evmjit"] diff --git a/ethcore/src/lib.rs b/ethcore/src/lib.rs index b18efa54d..949b4100d 100644 --- a/ethcore/src/lib.rs +++ b/ethcore/src/lib.rs @@ -85,6 +85,7 @@ extern crate num_cpus; extern crate crossbeam; extern crate ethjson; extern crate bloomchain; +extern crate ethcore_ipc as ipc; #[cfg(test)] extern crate ethcore_devtools as devtools; #[cfg(feature = "jit" )] extern crate evmjit; diff --git a/ethcore/src/types/block_status.rs b/ethcore/src/types/block_status.rs index 60776748c..ca0f47227 100644 --- a/ethcore/src/types/block_status.rs +++ b/ethcore/src/types/block_status.rs @@ -16,8 +16,11 @@ //! Block status description module +use ipc::binary::BinaryConvertError; +use std::collections::VecDeque; + /// General block status -#[derive(Debug, Eq, PartialEq)] +#[derive(Debug, Eq, PartialEq, Binary)] pub enum BlockStatus { /// Part of the blockchain. InChain, diff --git a/ethcore/src/types/blockchain_info.rs b/ethcore/src/types/blockchain_info.rs index aacf77baf..076225b27 100644 --- a/ethcore/src/types/blockchain_info.rs +++ b/ethcore/src/types/blockchain_info.rs @@ -14,11 +14,14 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -use util::*; +use util::numbers::*; use header::BlockNumber; +use ipc::binary::BinaryConvertError; +use std::mem; +use std::collections::VecDeque; /// Information about the blockchain gathered together. -#[derive(Debug)] +#[derive(Debug, Binary)] pub struct BlockChainInfo { /// Blockchain difficulty. pub total_difficulty: U256, diff --git a/util/bigint/src/uint.rs b/util/bigint/src/uint.rs index be9941589..f87b494a9 100644 --- a/util/bigint/src/uint.rs +++ b/util/bigint/src/uint.rs @@ -517,7 +517,7 @@ pub trait Uint: Sized + Default + FromStr + From + fmt::Debug + fmt::Displa /// Return single byte fn byte(&self, index: usize) -> u8; /// Get this Uint as slice of bytes - fn to_bytes(&self, bytes: &mut[u8]); + fn to_raw_bytes(&self, bytes: &mut[u8]); /// Create `Uint(10**n)` fn exp10(n: usize) -> Self; @@ -621,7 +621,7 @@ macro_rules! construct_uint { (arr[index / 8] >> (((index % 8)) * 8)) as u8 } - fn to_bytes(&self, bytes: &mut[u8]) { + fn to_raw_bytes(&self, bytes: &mut[u8]) { assert!($n_words * 8 == bytes.len()); let &$name(ref arr) = self; for i in 0..bytes.len() { @@ -780,7 +780,7 @@ macro_rules! construct_uint { where S: serde::Serializer { let mut hex = "0x".to_owned(); let mut bytes = [0u8; 8 * $n_words]; - self.to_bytes(&mut bytes); + self.to_raw_bytes(&mut bytes); let len = cmp::max((self.bits() + 7) / 8, 1); hex.push_str(bytes[bytes.len() - len..].to_hex().as_ref()); serializer.serialize_str(hex.as_ref()) @@ -1482,7 +1482,7 @@ mod tests { let hex = "8090a0b0c0d0e0f00910203040506077583a2cf8264910e1436bda32571012f0"; let uint = U256::from_str(hex).unwrap(); let mut bytes = [0u8; 32]; - uint.to_bytes(&mut bytes); + uint.to_raw_bytes(&mut bytes); let uint2 = U256::from(&bytes[..]); assert_eq!(uint, uint2); } diff --git a/util/src/hash.rs b/util/src/hash.rs index 69ed17c79..e1b82b14c 100644 --- a/util/src/hash.rs +++ b/util/src/hash.rs @@ -517,7 +517,7 @@ impl From for H256 { fn from(value: U256) -> H256 { unsafe { let mut ret: H256 = ::std::mem::uninitialized(); - value.to_bytes(&mut ret); + value.to_raw_bytes(&mut ret); ret } } @@ -527,7 +527,7 @@ impl<'_> From<&'_ U256> for H256 { fn from(value: &'_ U256) -> H256 { unsafe { let mut ret: H256 = ::std::mem::uninitialized(); - value.to_bytes(&mut ret); + value.to_raw_bytes(&mut ret); ret } } From c622fc62d5481830c2a7a0d6e126ca6efdf54c64 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Fri, 6 May 2016 17:19:53 +0400 Subject: [PATCH 15/32] binary for trace --- ethcore/src/types/trace_types/trace.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/ethcore/src/types/trace_types/trace.rs b/ethcore/src/types/trace_types/trace.rs index f7efe9721..9eb6ef5ac 100644 --- a/ethcore/src/types/trace_types/trace.rs +++ b/ethcore/src/types/trace_types/trace.rs @@ -20,9 +20,12 @@ use util::rlp::*; use util::sha3::Hashable; use action_params::ActionParams; use basic_types::LogBloom; +use ipc::binary::BinaryConvertError; +use std::mem; +use std::collections::VecDeque; /// `Call` result. -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq, Default, Binary)] pub struct CallResult { /// Gas used by call. pub gas_used: U256, @@ -51,7 +54,7 @@ impl Decodable for CallResult { } /// `Create` result. -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Binary)] pub struct CreateResult { /// Gas used by create. pub gas_used: U256, @@ -84,7 +87,7 @@ impl Decodable for CreateResult { } /// Description of a _call_ action, either a `CALL` operation or a message transction. -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Binary)] pub struct Call { /// The sending account. pub from: Address, @@ -146,7 +149,7 @@ impl Call { } /// Description of a _create_ action, either a `CREATE` operation or a create transction. -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Binary)] pub struct Create { /// The address of the creator. pub from: Address, @@ -202,7 +205,7 @@ impl Create { } /// Description of an action that we trace; will be either a call or a create. -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Binary)] pub enum Action { /// It's a call action. Call(Call), @@ -249,7 +252,7 @@ impl Action { } /// The result of the performed action. -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Binary)] pub enum Res { /// Successful call action result. Call(CallResult), @@ -300,7 +303,7 @@ impl Decodable for Res { } } -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Binary)] /// A trace; includes a description of the action being traced and sub traces of each interior action. pub struct Trace { /// The number of EVM execution environments active when this action happened; 0 if it's From f9c08df235d232d1fd09587797976b74a084b639 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Fri, 6 May 2016 17:30:36 +0400 Subject: [PATCH 16/32] trace filters binary ser --- ethcore/src/types/trace_types/filter.rs | 23 ++++++++++++++-------- ethcore/src/types/trace_types/localized.rs | 5 ++++- ipc/rpc/src/binary.rs | 5 ++++- 3 files changed, 23 insertions(+), 10 deletions(-) diff --git a/ethcore/src/types/trace_types/filter.rs b/ethcore/src/types/trace_types/filter.rs index 25ee5954a..c1d237ed7 100644 --- a/ethcore/src/types/trace_types/filter.rs +++ b/ethcore/src/types/trace_types/filter.rs @@ -21,34 +21,40 @@ use util::sha3::Hashable; use basic_types::LogBloom; use trace::flat::FlatTrace; use types::trace_types::trace::Action; +use ipc::binary::BinaryConvertError; +use std::mem; +use std::collections::VecDeque; /// Addresses filter. /// /// Used to create bloom possibilities and match filters. -pub struct AddressesFilter(Vec
); +#[derive(Binary)] +pub struct AddressesFilter { + list: Vec
+} impl From> for AddressesFilter { fn from(addresses: Vec
) -> Self { - AddressesFilter(addresses) + AddressesFilter { list: addresses } } } impl AddressesFilter { /// Returns true if address matches one of the searched addresses. pub fn matches(&self, address: &Address) -> bool { - self.matches_all() || self.0.contains(address) + self.matches_all() || self.list.contains(address) } /// Returns true if this address filter matches everything. pub fn matches_all(&self) -> bool { - self.0.is_empty() + self.list.is_empty() } /// Returns blooms of this addresses filter. pub fn blooms(&self) -> Vec { - match self.0.is_empty() { + match self.list.is_empty() { true => vec![LogBloom::new()], - false => self.0.iter() + false => self.list.iter() .map(|address| LogBloom::from_bloomed(&address.sha3())) .collect() } @@ -56,11 +62,11 @@ impl AddressesFilter { /// Returns vector of blooms zipped with blooms of this addresses filter. pub fn with_blooms(&self, blooms: Vec) -> Vec { - match self.0.is_empty() { + match self.list.is_empty() { true => blooms, false => blooms .into_iter() - .flat_map(|bloom| self.0.iter() + .flat_map(|bloom| self.list.iter() .map(|address| bloom.with_bloomed(&address.sha3())) .collect::>()) .collect() @@ -68,6 +74,7 @@ impl AddressesFilter { } } +#[derive(Binary)] /// Traces filter. pub struct Filter { /// Block range. diff --git a/ethcore/src/types/trace_types/localized.rs b/ethcore/src/types/trace_types/localized.rs index ef18d6898..db4d05426 100644 --- a/ethcore/src/types/trace_types/localized.rs +++ b/ethcore/src/types/trace_types/localized.rs @@ -17,9 +17,12 @@ use util::H256; use super::trace::{Action, Res}; use header::BlockNumber; +use ipc::binary::BinaryConvertError; +use std::mem; +use std::collections::VecDeque; /// Localized trace. -#[derive(Debug, PartialEq)] +#[derive(Debug, PartialEq, Binary)] pub struct LocalizedTrace { /// Type of action performed by a transaction. pub action: Action, diff --git a/ipc/rpc/src/binary.rs b/ipc/rpc/src/binary.rs index 3ba172c6e..67a3d37e2 100644 --- a/ipc/rpc/src/binary.rs +++ b/ipc/rpc/src/binary.rs @@ -20,6 +20,7 @@ use util::bytes::Populatable; use util::numbers::{U256, H256, H2048, Address}; use std::mem; use std::collections::VecDeque; +use std::ops::Range; #[derive(Debug)] pub struct BinaryConvertError; @@ -366,7 +367,7 @@ pub fn serialize(t: &T) -> Result, BinaryConvertEr } macro_rules! binary_fixed_size { - ($target_ty: ident) => { + ($target_ty: ty) => { impl BinaryConvertable for $target_ty { fn from_bytes(bytes: &[u8], _length_stack: &mut VecDeque) -> Result { match bytes.len().cmp(&::std::mem::size_of::<$target_ty>()) { @@ -401,6 +402,8 @@ binary_fixed_size!(U256); binary_fixed_size!(H256); binary_fixed_size!(H2048); binary_fixed_size!(Address); +binary_fixed_size!(Range); +binary_fixed_size!(Range); #[test] fn vec_serialize() { From e7c4e5273a8ebdcafcf91ac395dbfaf5776d7d2e Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Fri, 6 May 2016 17:38:00 +0400 Subject: [PATCH 17/32] binary for log entries & executed --- ethcore/src/types/executed.rs | 8 ++++++-- ethcore/src/types/log_entry.rs | 14 +++++++++++--- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/ethcore/src/types/executed.rs b/ethcore/src/types/executed.rs index cd671269f..26d402409 100644 --- a/ethcore/src/types/executed.rs +++ b/ethcore/src/types/executed.rs @@ -16,12 +16,16 @@ //! Transaction execution format module. -use util::*; +use util::numbers::*; +use util::Bytes; use trace::Trace; use types::log_entry::LogEntry; +use ipc::binary::BinaryConvertError; +use std::mem; +use std::collections::VecDeque; /// Transaction execution receipt. -#[derive(Debug, PartialEq, Clone)] +#[derive(Debug, PartialEq, Clone, Binary)] pub struct Executed { /// Gas paid up front for execution of transaction. pub gas: U256, diff --git a/ethcore/src/types/log_entry.rs b/ethcore/src/types/log_entry.rs index 2a7ca080f..9017a00ef 100644 --- a/ethcore/src/types/log_entry.rs +++ b/ethcore/src/types/log_entry.rs @@ -16,13 +16,21 @@ //! Block log. -use util::*; +use util::numbers::*; +use std::ops::Deref; +use util::rlp::*; +use util::Bytes; +use util::HeapSizeOf; +use util::sha3::*; use basic_types::LogBloom; use header::BlockNumber; use ethjson; +use ipc::binary::BinaryConvertError; +use std::mem; +use std::collections::VecDeque; /// A record of execution for a `LOG` operation. -#[derive(Default, Debug, Clone, PartialEq, Eq)] +#[derive(Default, Debug, Clone, PartialEq, Eq, Binary)] pub struct LogEntry { /// The address of the contract executing at the point of the `LOG` operation. pub address: Address, @@ -77,7 +85,7 @@ impl From for LogEntry { } /// Log localized in a blockchain. -#[derive(Default, Debug, PartialEq, Clone)] +#[derive(Default, Debug, PartialEq, Clone, Binary)] pub struct LocalizedLogEntry { /// Plain log entry. pub entry: LogEntry, From 79d6c84a430cbeed8f78b414c932e0c20096212a Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Fri, 6 May 2016 17:41:17 +0400 Subject: [PATCH 18/32] binary for receipt --- ethcore/src/types/receipt.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/ethcore/src/types/receipt.rs b/ethcore/src/types/receipt.rs index 2fbd3f14c..c80407363 100644 --- a/ethcore/src/types/receipt.rs +++ b/ethcore/src/types/receipt.rs @@ -16,13 +16,21 @@ //! Receipt -use util::*; +use util::numbers::*; +use std::ops::Deref; +use util::rlp::*; +use util::Bytes; +use util::HeapSizeOf; +use util::sha3::*; use basic_types::LogBloom; use header::BlockNumber; use log_entry::{LogEntry, LocalizedLogEntry}; +use ipc::binary::BinaryConvertError; +use std::mem; +use std::collections::VecDeque; /// Information describing execution of a transaction. -#[derive(Default, Debug, Clone)] +#[derive(Default, Debug, Clone, Binary)] pub struct Receipt { /// The state root after executing the transaction. pub state_root: H256, From 889642c3d44cbac213339c13771dba4d5d60637a Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Wed, 11 May 2016 13:23:11 +0300 Subject: [PATCH 19/32] special case for u8 & transaction binary attribute --- ethcore/src/types/transaction.rs | 16 +++++-- ipc/codegen/src/serialization.rs | 71 ++++++++++++++++++++++++++------ ipc/rpc/src/binary.rs | 23 +++++++++++ 3 files changed, 94 insertions(+), 16 deletions(-) diff --git a/ethcore/src/types/transaction.rs b/ethcore/src/types/transaction.rs index ca54f26bb..2953ff896 100644 --- a/ethcore/src/types/transaction.rs +++ b/ethcore/src/types/transaction.rs @@ -16,13 +16,21 @@ //! Transaction data structure. -use util::*; +use util::numbers::*; +use std::ops::Deref; +use util::rlp::*; +use util::sha3::*; +use util::{UtilError, CryptoError, Bytes, HeapSizeOf, Signature, Secret, ec}; +use std::cell::*; use error::*; use evm::Schedule; use header::BlockNumber; use ethjson; +use ipc::binary::BinaryConvertError; +use std::mem; +use std::collections::VecDeque; -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Binary)] /// Transaction action type. pub enum Action { /// Create creates new contract. @@ -48,7 +56,7 @@ impl Decodable for Action { /// A set of information describing an externally-originating message call /// or contract creation operation. -#[derive(Default, Debug, Clone, PartialEq, Eq)] +#[derive(Default, Debug, Clone, PartialEq, Eq, Binary)] pub struct Transaction { /// Nonce. pub nonce: U256, @@ -183,7 +191,7 @@ impl Transaction { } /// Signed transaction information. -#[derive(Debug, Clone, Eq)] +#[derive(Debug, Clone, Eq, Binary)] pub struct SignedTransaction { /// Plain Transaction. unsigned: Transaction, diff --git a/ipc/codegen/src/serialization.rs b/ipc/codegen/src/serialization.rs index 6a9784790..cf8857325 100644 --- a/ipc/codegen/src/serialization.rs +++ b/ipc/codegen/src/serialization.rs @@ -175,6 +175,11 @@ fn binary_expr_struct( ) -> Result { let size_exprs: Vec> = fields.iter().enumerate().map(|(index, field)| { + + if ::syntax::print::pprust::ty_to_string(&codegen::strip_ptr(&field.ty)) == "u8" { + return quote_expr!(cx, 1); + } + let field_type_ident = builder.id( &::syntax::print::pprust::ty_to_string(&codegen::strip_ptr(&field.ty))); @@ -228,23 +233,34 @@ fn binary_expr_struct( }, }; - write_stmts.push(quote_stmt!(cx, let next_line = offset + match $field_type_ident_qualified::len_params() { - 0 => mem::size_of::<$field_type_ident>(), - _ => { let size = $member_expr .size(); length_stack.push_back(size); size }, - }).unwrap()); - - write_stmts.push(quote_stmt!(cx, - if let Err(e) = $member_expr .to_bytes(&mut buffer[offset..next_line], length_stack) { return Err(e) };).unwrap()); + if ::syntax::print::pprust::ty_to_string(&codegen::strip_ptr(&field.ty)) == "u8" { + write_stmts.push(quote_stmt!(cx, let next_line = offset + 1;).unwrap()); + write_stmts.push(quote_stmt!(cx, buffer[offset] = $member_expr; ).unwrap()); + } + else { + write_stmts.push(quote_stmt!(cx, let next_line = offset + match $field_type_ident_qualified::len_params() { + 0 => mem::size_of::<$field_type_ident>(), + _ => { let size = $member_expr .size(); length_stack.push_back(size); size }, + }).unwrap()); + write_stmts.push(quote_stmt!(cx, + if let Err(e) = $member_expr .to_bytes(&mut buffer[offset..next_line], length_stack) { return Err(e) };).unwrap()); + } write_stmts.push(quote_stmt!(cx, offset = next_line; ).unwrap()); let field_index = builder.id(&format!("{}", index)); map_stmts.push(quote_stmt!(cx, map[$field_index] = total;).unwrap()); - map_stmts.push(quote_stmt!(cx, let size = match $field_type_ident_qualified::len_params() { - 0 => mem::size_of::<$field_type_ident>(), - _ => length_stack.pop_front().unwrap(), - }).unwrap()); - map_stmts.push(quote_stmt!(cx, total = total + size;).unwrap()); + + if ::syntax::print::pprust::ty_to_string(&codegen::strip_ptr(&field.ty)) == "u8" { + map_stmts.push(quote_stmt!(cx, total = total + 1;).unwrap()); + } + else { + map_stmts.push(quote_stmt!(cx, let size = match $field_type_ident_qualified::len_params() { + 0 => mem::size_of::<$field_type_ident>(), + _ => length_stack.pop_front().unwrap(), + }).unwrap()); + map_stmts.push(quote_stmt!(cx, total = total + size;).unwrap()); + } }; let read_expr = match fields.iter().any(|f| codegen::has_ptr(&f.ty)) { @@ -381,6 +397,21 @@ fn fields_sequence( tt.push(Token(_sp, token::Colon)); } + // special case for u8, it just takes byte form sequence + if ::syntax::print::pprust::ty_to_string(&field.ty) == "u8" { + tt.push(Token(_sp, token::Ident(ext_cx.ident_of("buffer")))); + + tt.push(Token(_sp, token::OpenDelim(token::Bracket))); + tt.push(Token(_sp, token::Ident(ext_cx.ident_of("map")))); + tt.push(Token(_sp, token::OpenDelim(token::Bracket))); + tt.push(Token(_sp, token::Ident(ext_cx.ident_of(&format!("{}", idx))))); + tt.push(Token(_sp, token::CloseDelim(token::Bracket))); + tt.push(Token(_sp, token::CloseDelim(token::Bracket))); + + tt.push(Token(_sp, token::Comma)); + continue; + } + tt.push(Token(_sp, token::Ident(ext_cx.ident_of("try!")))); tt.push(Token(_sp, token::OpenDelim(token::Paren))); tt.push( @@ -393,6 +424,7 @@ fn fields_sequence( tt.push(Token(_sp, token::OpenDelim(token::Paren))); tt.push(Token(_sp, token::BinOp(token::And))); + tt.push(Token(_sp, token::Ident(ext_cx.ident_of("buffer")))); tt.push(Token(_sp, token::OpenDelim(token::Bracket))); @@ -455,6 +487,21 @@ fn named_fields_sequence( tt.push(Token(_sp, token::Ident(field.ident.clone().unwrap()))); tt.push(Token(_sp, token::Colon)); + // special case for u8, it just takes byte form sequence + if ::syntax::print::pprust::ty_to_string(&field.ty) == "u8" { + tt.push(Token(_sp, token::Ident(ext_cx.ident_of("buffer")))); + + tt.push(Token(_sp, token::OpenDelim(token::Bracket))); + tt.push(Token(_sp, token::Ident(ext_cx.ident_of("map")))); + tt.push(Token(_sp, token::OpenDelim(token::Bracket))); + tt.push(Token(_sp, token::Ident(ext_cx.ident_of(&format!("{}", idx))))); + tt.push(Token(_sp, token::CloseDelim(token::Bracket))); + tt.push(Token(_sp, token::CloseDelim(token::Bracket))); + + tt.push(Token(_sp, token::Comma)); + continue; + } + tt.push(Token(_sp, token::Ident(ext_cx.ident_of("try!")))); tt.push(Token(_sp, token::OpenDelim(token::Paren))); tt.push(Token( diff --git a/ipc/rpc/src/binary.rs b/ipc/rpc/src/binary.rs index 67a3d37e2..2d2bd21b7 100644 --- a/ipc/rpc/src/binary.rs +++ b/ipc/rpc/src/binary.rs @@ -233,6 +233,29 @@ impl BinaryConvertable for ::std::cell::RefCell where T: BinaryConvertable } } +impl BinaryConvertable for ::std::cell::Cell where T: BinaryConvertable + Copy { + fn size(&self) -> usize { + self.get().size() + } + + fn from_empty_bytes() -> Result { + Ok(::std::cell::Cell::new(try!(T::from_empty_bytes()))) + } + + fn from_bytes(buffer: &[u8], length_stack: &mut VecDeque) -> Result { + Ok(::std::cell::Cell::new(try!(T::from_bytes(buffer, length_stack)))) + } + + fn to_bytes(&self, buffer: &mut [u8], length_stack: &mut VecDeque) -> Result<(), BinaryConvertError> { + try!(self.get().to_bytes(buffer, length_stack)); + Ok(()) + } + + fn len_params() -> usize { + T::len_params() + } +} + impl BinaryConvertable for Vec { fn size(&self) -> usize { self.len() From 483687b6bf3699f9481ab1798eb9a5e0dd662b23 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Sun, 15 May 2016 00:51:02 +0300 Subject: [PATCH 20/32] resolved remaining issues & error binary serialization --- ethcore/src/types/executed.rs | 2 +- ethcore/src/types/receipt.rs | 1 + ethcore/src/types/transaction.rs | 2 ++ ipc/codegen/src/serialization.rs | 20 +++++++++++++++----- ipc/rpc/src/binary.rs | 3 ++- ipc/tests/binary.rs.in | 6 ++++++ ipc/tests/run.rs | 2 -- 7 files changed, 27 insertions(+), 9 deletions(-) diff --git a/ethcore/src/types/executed.rs b/ethcore/src/types/executed.rs index 657bcdec7..f03a1c26b 100644 --- a/ethcore/src/types/executed.rs +++ b/ethcore/src/types/executed.rs @@ -61,7 +61,7 @@ pub struct Executed { } /// Result of executing the transaction. -#[derive(PartialEq, Debug)] +#[derive(PartialEq, Debug, Binary)] pub enum ExecutionError { /// Returned when there gas paid for transaction execution is /// lower than base gas required. diff --git a/ethcore/src/types/receipt.rs b/ethcore/src/types/receipt.rs index c80407363..c851cb867 100644 --- a/ethcore/src/types/receipt.rs +++ b/ethcore/src/types/receipt.rs @@ -28,6 +28,7 @@ use log_entry::{LogEntry, LocalizedLogEntry}; use ipc::binary::BinaryConvertError; use std::mem; use std::collections::VecDeque; +use rustc_serialize::hex::FromHex; /// Information describing execution of a transaction. #[derive(Default, Debug, Clone, Binary)] diff --git a/ethcore/src/types/transaction.rs b/ethcore/src/types/transaction.rs index 2953ff896..d8454ed7a 100644 --- a/ethcore/src/types/transaction.rs +++ b/ethcore/src/types/transaction.rs @@ -29,6 +29,8 @@ use ethjson; use ipc::binary::BinaryConvertError; use std::mem; use std::collections::VecDeque; +use rustc_serialize::hex::FromHex; +use util::crypto::KeyPair; #[derive(Debug, Clone, PartialEq, Eq, Binary)] /// Transaction action type. diff --git a/ipc/codegen/src/serialization.rs b/ipc/codegen/src/serialization.rs index cf8857325..e8f3d2cd8 100644 --- a/ipc/codegen/src/serialization.rs +++ b/ipc/codegen/src/serialization.rs @@ -382,6 +382,8 @@ fn fields_sequence( use syntax::parse::token; use syntax::ast::TokenTree::Token; + let named_members = fields.iter().any(|f| f.ident.is_some()); + ::quasi::parse_expr_panic(&mut ::syntax::parse::new_parser_from_tts( ext_cx.parse_sess(), ext_cx.cfg(), @@ -389,7 +391,12 @@ fn fields_sequence( let _sp = ext_cx.call_site(); let mut tt = ::std::vec::Vec::new(); tt.push(Token(_sp, token::Ident(variant_ident.clone()))); - tt.push(Token(_sp, token::OpenDelim(token::Paren))); + if named_members { + tt.push(Token(_sp, token::OpenDelim(token::Brace))); + } + else { + tt.push(Token(_sp, token::OpenDelim(token::Paren))); + } for (idx, field) in fields.iter().enumerate() { if field.ident.is_some() { @@ -450,8 +457,12 @@ fn fields_sequence( tt.push(Token(_sp, token::CloseDelim(token::Paren))); tt.push(Token(_sp, token::Comma)); } - tt.push(Token(_sp, token::CloseDelim(token::Paren))); - + if named_members { + tt.push(Token(_sp, token::CloseDelim(token::Brace))); + } + else { + tt.push(Token(_sp, token::CloseDelim(token::Paren))); + } tt }) ).unwrap() @@ -620,7 +631,6 @@ fn binary_expr_variant( .map(|(id, field)|(field.ident.unwrap(), builder.pat().ref_id(id)))) .build(); - let binary_expr = try!(binary_expr_struct( cx, &builder, @@ -640,7 +650,7 @@ fn binary_expr_variant( let buffer = &mut buffer[1..]; $write_expr }), - read: quote_arm!(cx, $pat => { $read_expr } ), + read: quote_arm!(cx, $variant_index_ident => { $read_expr } ), }) }, } diff --git a/ipc/rpc/src/binary.rs b/ipc/rpc/src/binary.rs index 2d2bd21b7..58ab38bf1 100644 --- a/ipc/rpc/src/binary.rs +++ b/ipc/rpc/src/binary.rs @@ -17,7 +17,7 @@ //! Binary representation of types use util::bytes::Populatable; -use util::numbers::{U256, H256, H2048, Address}; +use util::numbers::{U256, U512, H256, H2048, Address}; use std::mem; use std::collections::VecDeque; use std::ops::Range; @@ -422,6 +422,7 @@ binary_fixed_size!(usize); binary_fixed_size!(i32); binary_fixed_size!(bool); binary_fixed_size!(U256); +binary_fixed_size!(U512); binary_fixed_size!(H256); binary_fixed_size!(H2048); binary_fixed_size!(Address); diff --git a/ipc/tests/binary.rs.in b/ipc/tests/binary.rs.in index 710752237..74dd39c1b 100644 --- a/ipc/tests/binary.rs.in +++ b/ipc/tests/binary.rs.in @@ -36,3 +36,9 @@ pub struct DoubleRoot { pub struct ReferenceStruct<'a> { pub ref_data: &'a u64, } + +#[derive(Binary, PartialEq, Debug)] +pub enum EnumWithStruct { + Left, + Right { how_much: u64 }, +} diff --git a/ipc/tests/run.rs b/ipc/tests/run.rs index c07145f77..cdda5275b 100644 --- a/ipc/tests/run.rs +++ b/ipc/tests/run.rs @@ -16,9 +16,7 @@ #![allow(dead_code)] -extern crate bincode; extern crate ethcore_ipc as ipc; -extern crate serde; extern crate ethcore_devtools as devtools; extern crate semver; extern crate nanomsg; From 326e1b3a42eca68b8d36d15d157b0918574eda73 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Sun, 15 May 2016 01:56:18 +0300 Subject: [PATCH 21/32] json-tests util import --- ethcore/src/types/transaction.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ethcore/src/types/transaction.rs b/ethcore/src/types/transaction.rs index d8454ed7a..cde8e2500 100644 --- a/ethcore/src/types/transaction.rs +++ b/ethcore/src/types/transaction.rs @@ -20,7 +20,7 @@ use util::numbers::*; use std::ops::Deref; use util::rlp::*; use util::sha3::*; -use util::{UtilError, CryptoError, Bytes, HeapSizeOf, Signature, Secret, ec}; +use util::{UtilError, CryptoError, Bytes, HeapSizeOf, Signature, Secret, ec, OutOfBounds}; use std::cell::*; use error::*; use evm::Schedule; From 9e7968c92eac872266a39bce2aa4c2c377a5decd Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Sun, 15 May 2016 02:13:45 +0300 Subject: [PATCH 22/32] fix warnings --- ethcore/src/trace/flat.rs | 2 ++ ethcore/src/types/blockchain_info.rs | 2 ++ ethcore/src/types/ids.rs | 1 - ethcore/src/types/log_entry.rs | 2 +- ethcore/src/types/receipt.rs | 6 +----- ethcore/src/types/trace_types/filter.rs | 2 ++ ethcore/src/types/trace_types/localized.rs | 2 ++ ethcore/src/types/trace_types/trace.rs | 1 + ethcore/src/types/transaction.rs | 10 ++++------ ethcore/src/types/tree_route.rs | 2 ++ 10 files changed, 17 insertions(+), 13 deletions(-) diff --git a/ethcore/src/trace/flat.rs b/ethcore/src/trace/flat.rs index ae3f22050..f9d3b0831 100644 --- a/ethcore/src/trace/flat.rs +++ b/ethcore/src/trace/flat.rs @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . +//! Flat trace module + use trace::BlockTraces; use super::trace::{Trace, Action, Res}; diff --git a/ethcore/src/types/blockchain_info.rs b/ethcore/src/types/blockchain_info.rs index 076225b27..4e8634dba 100644 --- a/ethcore/src/types/blockchain_info.rs +++ b/ethcore/src/types/blockchain_info.rs @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . +//! Blockhain info type definition + use util::numbers::*; use header::BlockNumber; use ipc::binary::BinaryConvertError; diff --git a/ethcore/src/types/ids.rs b/ethcore/src/types/ids.rs index cdab4ee3f..7d5a4c5fc 100644 --- a/ethcore/src/types/ids.rs +++ b/ethcore/src/types/ids.rs @@ -18,7 +18,6 @@ use util::hash::H256; use header::BlockNumber; -use util::bytes::{FromRawBytes, FromBytesError, ToBytesWithMap, Populatable}; /// Uniquely identifies block. #[derive(Debug, PartialEq, Clone, Hash, Eq)] diff --git a/ethcore/src/types/log_entry.rs b/ethcore/src/types/log_entry.rs index 9017a00ef..7d8dccc6c 100644 --- a/ethcore/src/types/log_entry.rs +++ b/ethcore/src/types/log_entry.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -//! Block log. +//! Log entry type definition. use util::numbers::*; use std::ops::Deref; diff --git a/ethcore/src/types/receipt.rs b/ethcore/src/types/receipt.rs index c851cb867..b96b34ed4 100644 --- a/ethcore/src/types/receipt.rs +++ b/ethcore/src/types/receipt.rs @@ -17,18 +17,14 @@ //! Receipt use util::numbers::*; -use std::ops::Deref; use util::rlp::*; -use util::Bytes; use util::HeapSizeOf; -use util::sha3::*; use basic_types::LogBloom; use header::BlockNumber; use log_entry::{LogEntry, LocalizedLogEntry}; use ipc::binary::BinaryConvertError; use std::mem; use std::collections::VecDeque; -use rustc_serialize::hex::FromHex; /// Information describing execution of a transaction. #[derive(Default, Debug, Clone, Binary)] @@ -107,7 +103,7 @@ pub struct LocalizedReceipt { #[test] fn test_basic() { - let expected = FromHex::from_hex("f90162a02f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee83040caeb9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000f838f794dcf421d093428b096ca501a7cd1a740855a7976fc0a00000000000000000000000000000000000000000000000000000000000000000").unwrap(); + let expected = ::rustc_serialize::hex::FromHex::from_hex("f90162a02f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee83040caeb9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000f838f794dcf421d093428b096ca501a7cd1a740855a7976fc0a00000000000000000000000000000000000000000000000000000000000000000").unwrap(); let r = Receipt::new( x!("2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee"), x!(0x40cae), diff --git a/ethcore/src/types/trace_types/filter.rs b/ethcore/src/types/trace_types/filter.rs index c1d237ed7..c02a15c03 100644 --- a/ethcore/src/types/trace_types/filter.rs +++ b/ethcore/src/types/trace_types/filter.rs @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . +//! Trace filters type definitions + use std::ops::Range; use bloomchain::{Filter as BloomFilter, Bloom, Number}; use util::{Address, FixedHash}; diff --git a/ethcore/src/types/trace_types/localized.rs b/ethcore/src/types/trace_types/localized.rs index db4d05426..334d7b518 100644 --- a/ethcore/src/types/trace_types/localized.rs +++ b/ethcore/src/types/trace_types/localized.rs @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . +//! Localized traces type definitions + use util::H256; use super::trace::{Action, Res}; use header::BlockNumber; diff --git a/ethcore/src/types/trace_types/trace.rs b/ethcore/src/types/trace_types/trace.rs index 9eb6ef5ac..f8fe07360 100644 --- a/ethcore/src/types/trace_types/trace.rs +++ b/ethcore/src/types/trace_types/trace.rs @@ -15,6 +15,7 @@ // along with Parity. If not, see . //! Tracing datatypes. + use util::{U256, Bytes, Address, FixedHash}; use util::rlp::*; use util::sha3::Hashable; diff --git a/ethcore/src/types/transaction.rs b/ethcore/src/types/transaction.rs index cde8e2500..71c77ede9 100644 --- a/ethcore/src/types/transaction.rs +++ b/ethcore/src/types/transaction.rs @@ -20,7 +20,7 @@ use util::numbers::*; use std::ops::Deref; use util::rlp::*; use util::sha3::*; -use util::{UtilError, CryptoError, Bytes, HeapSizeOf, Signature, Secret, ec, OutOfBounds}; +use util::{UtilError, CryptoError, Bytes, Signature, Secret, ec}; use std::cell::*; use error::*; use evm::Schedule; @@ -29,8 +29,6 @@ use ethjson; use ipc::binary::BinaryConvertError; use std::mem; use std::collections::VecDeque; -use rustc_serialize::hex::FromHex; -use util::crypto::KeyPair; #[derive(Debug, Clone, PartialEq, Eq, Binary)] /// Transaction action type. @@ -320,7 +318,7 @@ impl SignedTransaction { } try!(self.sender()); if self.gas < U256::from(self.gas_required(&schedule)) { - Err(From::from(TransactionError::InvalidGasLimit(OutOfBounds{min: Some(U256::from(self.gas_required(&schedule))), max: None, found: self.gas}))) + Err(From::from(TransactionError::InvalidGasLimit(::util::OutOfBounds{min: Some(U256::from(self.gas_required(&schedule))), max: None, found: self.gas}))) } else { Ok(self) } @@ -350,7 +348,7 @@ impl Deref for LocalizedTransaction { #[test] fn sender_test() { - let t: SignedTransaction = decode(&FromHex::from_hex("f85f800182520894095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap()); + let t: SignedTransaction = decode(&::rustc_serialize::hex::FromHex::from_hex("f85f800182520894095e7baea6a6c7c4c2dfeb977efac326af552d870a801ba048b55bfa915ac795c431978d8a6a992b628d557da5ff759b307d495a36649353a0efffd310ac743f371de3b9f7f9cb56c0b28ad43601b4ab949f53faa07bd2c804").unwrap()); assert_eq!(t.data, b""); assert_eq!(t.gas, U256::from(0x5208u64)); assert_eq!(t.gas_price, U256::from(0x01u64)); @@ -364,7 +362,7 @@ fn sender_test() { #[test] fn signing() { - let key = KeyPair::create().unwrap(); + let key = ::util::crypto::KeyPair::create().unwrap(); let t = Transaction { action: Action::Create, nonce: U256::from(42), diff --git a/ethcore/src/types/tree_route.rs b/ethcore/src/types/tree_route.rs index 3c4906449..2ad0aa240 100644 --- a/ethcore/src/types/tree_route.rs +++ b/ethcore/src/types/tree_route.rs @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . +//! Tree route info type definition + use util::numbers::H256; /// Represents a tree route between `from` block and `to` block: From d67d1eb35531e2ca21bcd782623a8ba61d1b4137 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Sun, 15 May 2016 02:32:53 +0300 Subject: [PATCH 23/32] ids attr --- ethcore/src/lib.rs | 2 +- ethcore/src/types/ids.rs | 9 ++++++--- ipc/rpc/src/binary.rs | 1 + 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/ethcore/src/lib.rs b/ethcore/src/lib.rs index 949b4100d..0b62ec4fb 100644 --- a/ethcore/src/lib.rs +++ b/ethcore/src/lib.rs @@ -85,7 +85,7 @@ extern crate num_cpus; extern crate crossbeam; extern crate ethjson; extern crate bloomchain; -extern crate ethcore_ipc as ipc; +#[macro_use] extern crate ethcore_ipc as ipc; #[cfg(test)] extern crate ethcore_devtools as devtools; #[cfg(feature = "jit" )] extern crate evmjit; diff --git a/ethcore/src/types/ids.rs b/ethcore/src/types/ids.rs index 7d5a4c5fc..2250c8dfe 100644 --- a/ethcore/src/types/ids.rs +++ b/ethcore/src/types/ids.rs @@ -18,9 +18,13 @@ use util::hash::H256; use header::BlockNumber; +use ipc::binary::BinaryConvertError; +use ipc::binary::BinaryConvertable; +use std::mem; +use std::collections::VecDeque; /// Uniquely identifies block. -#[derive(Debug, PartialEq, Clone, Hash, Eq)] +#[derive(Debug, PartialEq, Clone, Hash, Eq, Binary)] pub enum BlockId { /// Block's sha3. /// Querying by hash is always faster. @@ -34,7 +38,7 @@ pub enum BlockId { } /// Uniquely identifies transaction. -#[derive(Debug, PartialEq, Clone, Hash, Eq)] +#[derive(Debug, PartialEq, Clone, Hash, Eq, Binary)] pub enum TransactionId { /// Transaction's sha3. Hash(H256), @@ -58,4 +62,3 @@ pub struct UncleId ( /// Position in block. pub usize ); - diff --git a/ipc/rpc/src/binary.rs b/ipc/rpc/src/binary.rs index 58ab38bf1..4fb359f7c 100644 --- a/ipc/rpc/src/binary.rs +++ b/ipc/rpc/src/binary.rs @@ -389,6 +389,7 @@ pub fn serialize(t: &T) -> Result, BinaryConvertEr Ok(buff.into_inner()) } +#[macro_export] macro_rules! binary_fixed_size { ($target_ty: ty) => { impl BinaryConvertable for $target_ty { From 96e92f1c38b933ad4c3aeeb1d3be4033ea7dc3a1 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Sun, 15 May 2016 02:34:27 +0300 Subject: [PATCH 24/32] add missing attributes --- ethcore/src/types/receipt.rs | 2 +- ethcore/src/types/transaction.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ethcore/src/types/receipt.rs b/ethcore/src/types/receipt.rs index b96b34ed4..cc83e2f97 100644 --- a/ethcore/src/types/receipt.rs +++ b/ethcore/src/types/receipt.rs @@ -81,7 +81,7 @@ impl HeapSizeOf for Receipt { } /// Receipt with additional info. -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Binary)] pub struct LocalizedReceipt { /// Transaction hash. pub transaction_hash: H256, diff --git a/ethcore/src/types/transaction.rs b/ethcore/src/types/transaction.rs index 71c77ede9..842decd88 100644 --- a/ethcore/src/types/transaction.rs +++ b/ethcore/src/types/transaction.rs @@ -326,7 +326,7 @@ impl SignedTransaction { } /// Signed Transaction that is a part of canon blockchain. -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Binary)] pub struct LocalizedTransaction { /// Signed part. pub signed: SignedTransaction, From 994d056922316dd20a475d8bab2081a6e0fe8608 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Mon, 16 May 2016 19:16:56 +0300 Subject: [PATCH 25/32] miner will use separate spec --- ethcore/src/engine.rs | 2 ++ ethcore/src/lib.rs | 2 +- miner/src/miner.rs | 16 +++++++++++++--- parity/main.rs | 2 +- 4 files changed, 17 insertions(+), 5 deletions(-) diff --git a/ethcore/src/engine.rs b/ethcore/src/engine.rs index 344144c6e..050d5b499 100644 --- a/ethcore/src/engine.rs +++ b/ethcore/src/engine.rs @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . +//! Consensus engine specification + use common::*; use util::keys::store::AccountProvider; use block::ExecutedBlock; diff --git a/ethcore/src/lib.rs b/ethcore/src/lib.rs index 0b62ec4fb..346711327 100644 --- a/ethcore/src/lib.rs +++ b/ethcore/src/lib.rs @@ -103,6 +103,7 @@ pub mod trace; pub mod spec; pub mod views; pub mod pod_state; +pub mod engine; mod db; mod common; @@ -112,7 +113,6 @@ mod env_info; mod pod_account; mod account_diff; mod state_diff; -mod engine; mod state; mod account; mod account_db; diff --git a/miner/src/miner.rs b/miner/src/miner.rs index 33d21613f..e89fe2bf8 100644 --- a/miner/src/miner.rs +++ b/miner/src/miner.rs @@ -25,6 +25,8 @@ use ethcore::block::{ClosedBlock, IsBlock}; use ethcore::error::*; use ethcore::client::{Executive, Executed, EnvInfo, TransactOptions}; use ethcore::transaction::SignedTransaction; +use ethcore::spec::Spec; +use ethcore::engine::Engine; use super::{MinerService, MinerStatus, TransactionQueue, AccountDetails, TransactionImportResult, TransactionOrigin}; /// Keeps track of transactions using priority queue and holds currently mined block. @@ -39,6 +41,7 @@ pub struct Miner { gas_floor_target: RwLock, author: RwLock
, extra_data: RwLock, + spec: Spec, accounts: RwLock>>, // TODO: this is horrible since AccountService already contains a single RwLock field. refactor. } @@ -55,13 +58,14 @@ impl Default for Miner { author: RwLock::new(Address::default()), extra_data: RwLock::new(Vec::new()), accounts: RwLock::new(None), + spec: Spec::new_test(), } } } impl Miner { /// Creates new instance of miner - pub fn new(force_sealing: bool) -> Arc { + pub fn new(force_sealing: bool, spec: Spec) -> Arc { Arc::new(Miner { transaction_queue: Mutex::new(TransactionQueue::new()), force_sealing: force_sealing, @@ -72,11 +76,12 @@ impl Miner { author: RwLock::new(Address::default()), extra_data: RwLock::new(Vec::new()), accounts: RwLock::new(None), + spec: spec, }) } /// Creates new instance of miner - pub fn with_accounts(force_sealing: bool, accounts: Arc) -> Arc { + pub fn with_accounts(force_sealing: bool, spec: Spec, accounts: Arc) -> Arc { Arc::new(Miner { transaction_queue: Mutex::new(TransactionQueue::new()), force_sealing: force_sealing, @@ -87,9 +92,14 @@ impl Miner { author: RwLock::new(Address::default()), extra_data: RwLock::new(Vec::new()), accounts: RwLock::new(Some(accounts)), + spec: spec, }) } + fn engine(&self) -> &Engine { + self.spec.engine.deref() + } + /// Prepares new block for sealing including top transactions from queue. #[cfg_attr(feature="dev", allow(match_same_arms))] fn prepare_sealing(&self, chain: &BlockChainClient) { @@ -166,7 +176,7 @@ impl Miner { trace!(target: "miner", "prepare_sealing: block has transaction - attempting internal seal."); // block with transactions - see if we can seal immediately. let a = self.accounts.read().unwrap(); - let s = chain.generate_seal(block.block(), match *a.deref() { + let s = self.engine().generate_seal(block.block(), match *a.deref() { Some(ref x) => Some(x.deref() as &AccountProvider), None => None, }); diff --git a/parity/main.rs b/parity/main.rs index dd70d39cc..4896e42cf 100644 --- a/parity/main.rs +++ b/parity/main.rs @@ -145,7 +145,7 @@ fn execute_client(conf: Configuration) { let client = service.client(); // Miner - let miner = Miner::with_accounts(conf.args.flag_force_sealing, account_service.clone()); + let miner = Miner::with_accounts(conf.args.flag_force_sealing, conf.spec(), account_service.clone()); miner.set_author(conf.author()); miner.set_gas_floor_target(conf.gas_floor_target()); miner.set_extra_data(conf.extra_data()); From 7c28b1cef969e4d7f7261c859e59211838e65934 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Mon, 16 May 2016 19:43:48 +0300 Subject: [PATCH 26/32] removed engine retrieval from client public api --- ethcore/src/client/client.rs | 4 ---- ethcore/src/client/mod.rs | 6 ------ ethcore/src/client/test_client.rs | 4 ---- miner/src/miner.rs | 4 ++-- 4 files changed, 2 insertions(+), 16 deletions(-) diff --git a/ethcore/src/client/client.rs b/ethcore/src/client/client.rs index 0d61325d9..87b337f69 100644 --- a/ethcore/src/client/client.rs +++ b/ethcore/src/client/client.rs @@ -430,10 +430,6 @@ impl BlockChainClient for Client where V: Verifier { block.try_seal(self.engine.deref().deref(), seal) } - fn engine(&self) -> &Engine { - self.engine.deref().deref() - } - // TODO [todr] Should be moved to miner crate eventually. fn prepare_sealing(&self, author: Address, gas_floor_target: U256, extra_data: Bytes, transactions: Vec) -> (Option, HashSet) { diff --git a/ethcore/src/client/mod.rs b/ethcore/src/client/mod.rs index a748ff900..07c2722b4 100644 --- a/ethcore/src/client/mod.rs +++ b/ethcore/src/client/mod.rs @@ -134,12 +134,6 @@ pub trait BlockChainClient : Sync + Send { /// Makes a non-persistent transaction call. fn call(&self, t: &SignedTransaction) -> Result; - /// Attempt to seal the block internally. See `Engine`. - fn generate_seal(&self, block: &ExecutedBlock, accounts: Option<&AccountProvider>) -> Option> { self.engine().generate_seal(block, accounts) } - - /// Executes a function providing it with a reference to an engine. - fn engine(&self) -> &Engine; - /// Returns traces matching given filter. fn filter_traces(&self, filter: TraceFilter) -> Option>; diff --git a/ethcore/src/client/test_client.rs b/ethcore/src/client/test_client.rs index 4ec993fe5..84b800655 100644 --- a/ethcore/src/client/test_client.rs +++ b/ethcore/src/client/test_client.rs @@ -430,10 +430,6 @@ impl BlockChainClient for TestBlockChainClient { } } - fn engine(&self) -> &Engine { - unimplemented!(); - } - fn filter_traces(&self, _filter: TraceFilter) -> Option> { unimplemented!(); } diff --git a/miner/src/miner.rs b/miner/src/miner.rs index e89fe2bf8..952106ad6 100644 --- a/miner/src/miner.rs +++ b/miner/src/miner.rs @@ -121,7 +121,7 @@ impl Miner { Some(old_block) => { trace!(target: "miner", "Already have previous work; updating and returning"); // add transactions to old_block - let e = chain.engine(); + let e = self.engine(); let mut invalid_transactions = HashSet::new(); let mut block = old_block.reopen(e); let block_number = block.block().fields().header.number(); @@ -277,7 +277,7 @@ impl MinerService for Miner { state.sub_balance(&sender, &balance); state.add_balance(&sender, &U256::max_value()); let options = TransactOptions { tracing: false, check_nonce: false }; - Executive::new(&mut state, &env_info, chain.engine()).transact(t, options) + Executive::new(&mut state, &env_info, self.engine()).transact(t, options) }, None => { chain.call(t) From 8cc321fe2453e377ee087dd2e457e3b13021cdf6 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Mon, 16 May 2016 19:45:16 +0300 Subject: [PATCH 27/32] fix warnings --- ethcore/src/client/mod.rs | 4 +--- ethcore/src/client/test_client.rs | 1 - 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/ethcore/src/client/mod.rs b/ethcore/src/client/mod.rs index 07c2722b4..fa96b8f15 100644 --- a/ethcore/src/client/mod.rs +++ b/ethcore/src/client/mod.rs @@ -33,17 +33,15 @@ use std::collections::HashSet; use util::bytes::Bytes; use util::hash::{Address, H256, H2048}; use util::numbers::U256; -use util::keys::store::AccountProvider; use blockchain::TreeRoute; use block_queue::BlockQueueInfo; -use block::{ExecutedBlock, ClosedBlock, LockedBlock, SealedBlock}; +use block::{ClosedBlock, LockedBlock, SealedBlock}; use header::{BlockNumber, Header}; use transaction::{LocalizedTransaction, SignedTransaction}; use log_entry::LocalizedLogEntry; use filter::Filter; use error::{ImportResult, ExecutionError}; use receipt::LocalizedReceipt; -use engine::{Engine}; use trace::LocalizedTrace; /// Blockchain database client. Owns and manages a blockchain and a block queue. diff --git a/ethcore/src/client/test_client.rs b/ethcore/src/client/test_client.rs index 84b800655..3ee605bdf 100644 --- a/ethcore/src/client/test_client.rs +++ b/ethcore/src/client/test_client.rs @@ -32,7 +32,6 @@ use block_queue::BlockQueueInfo; use block::{SealedBlock, ClosedBlock, LockedBlock}; use executive::Executed; use error::{ExecutionError}; -use engine::Engine; use trace::LocalizedTrace; /// Test client. From f3f45a1dd90848fc8e5305b5611d05f014ef9db3 Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Mon, 16 May 2016 20:25:05 +0300 Subject: [PATCH 28/32] ethsync tests fixed --- sync/src/lib.rs | 2 +- sync/src/tests/helpers.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sync/src/lib.rs b/sync/src/lib.rs index 0b95f0b92..f1b1bb0b2 100644 --- a/sync/src/lib.rs +++ b/sync/src/lib.rs @@ -45,7 +45,7 @@ //! let mut service = NetworkService::start(NetworkConfiguration::new()).unwrap(); //! let dir = env::temp_dir(); //! let client = Client::new(ClientConfig::default(), ethereum::new_frontier(), &dir, service.io().channel()); -//! let miner = Miner::new(false); +//! let miner = Miner::new(false, ethereum::new_frontier()); //! EthSync::register(&mut service, SyncConfig::default(), client, miner); //! } //! ``` diff --git a/sync/src/tests/helpers.rs b/sync/src/tests/helpers.rs index 269362064..76f8b220e 100644 --- a/sync/src/tests/helpers.rs +++ b/sync/src/tests/helpers.rs @@ -93,7 +93,7 @@ impl TestNet { for _ in 0..n { net.peers.push(TestPeer { chain: TestBlockChainClient::new(), - sync: ChainSync::new(SyncConfig::default(), Miner::new(false)), + sync: ChainSync::new(SyncConfig::default(), Arc::new(Miner::default())), queue: VecDeque::new(), }); } From d424194bbf6ecaa2219dbc643e5d032925afa46e Mon Sep 17 00:00:00 2001 From: Nikolay Volf Date: Mon, 16 May 2016 22:32:18 +0300 Subject: [PATCH 29/32] test spec explicitly --- sync/src/tests/helpers.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/sync/src/tests/helpers.rs b/sync/src/tests/helpers.rs index 76f8b220e..0629863dd 100644 --- a/sync/src/tests/helpers.rs +++ b/sync/src/tests/helpers.rs @@ -16,6 +16,7 @@ use util::*; use ethcore::client::{TestBlockChainClient, BlockChainClient}; +use ethcore::spec::Spec; use io::SyncIo; use chain::ChainSync; use ethminer::Miner; @@ -93,7 +94,7 @@ impl TestNet { for _ in 0..n { net.peers.push(TestPeer { chain: TestBlockChainClient::new(), - sync: ChainSync::new(SyncConfig::default(), Arc::new(Miner::default())), + sync: ChainSync::new(SyncConfig::default(), Miner::new(false, Spec::new_test())), queue: VecDeque::new(), }); } From 361d36f7d69fba569da962ff621a4f3e1f0be8b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Tue, 17 May 2016 16:55:08 +0200 Subject: [PATCH 30/32] Webapps details --- Cargo.lock | 35 ++++++++++++++++------------- webapp/Cargo.toml | 20 ++++++++++++----- webapp/build.rs | 45 +++++++++++++++++++++++++++++++++++++ webapp/src/{ => api}/api.rs | 38 +++++++++++++++++++++---------- webapp/src/api/mod.rs | 28 +++++++++++++++++++++++ webapp/src/api/mod.rs.in | 20 +++++++++++++++++ webapp/src/api/response.rs | 23 +++++++++++++++++++ webapp/src/endpoint.rs | 11 +++++++++ webapp/src/lib.rs | 2 ++ webapp/src/page/mod.rs | 22 ++++++++++++++++-- 10 files changed, 210 insertions(+), 34 deletions(-) create mode 100644 webapp/build.rs rename webapp/src/{ => api}/api.rs (59%) create mode 100644 webapp/src/api/mod.rs create mode 100644 webapp/src/api/mod.rs.in create mode 100644 webapp/src/api/response.rs diff --git a/Cargo.lock b/Cargo.lock index b0c9e5eb3..d463dafe6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -356,10 +356,15 @@ dependencies = [ "jsonrpc-core 2.0.4 (registry+https://github.com/rust-lang/crates.io-index)", "jsonrpc-http-server 5.1.0 (git+https://github.com/ethcore/jsonrpc-http-server.git)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-idmanager 0.1.3 (git+https://github.com/ethcore/parity-idmanager-rs.git)", - "parity-status 0.4.1 (git+https://github.com/ethcore/parity-status.git)", - "parity-wallet 0.3.0 (git+https://github.com/ethcore/parity-wallet.git)", - "parity-webapp 0.1.0 (git+https://github.com/ethcore/parity-webapp.git)", + "parity-idmanager 0.2.0 (git+https://github.com/ethcore/parity-idmanager-rs.git)", + "parity-status 0.4.0 (git+https://github.com/ethcore/parity-status.git)", + "parity-wallet 0.4.0 (git+https://github.com/ethcore/parity-wallet.git)", + "parity-webapp 0.2.0 (git+https://github.com/ethcore/parity-webapp.git)", + "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_codegen 0.7.4 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_json 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "syntex 0.32.0 (registry+https://github.com/rust-lang/crates.io-index)", "url 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -831,32 +836,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "parity-idmanager" -version = "0.1.3" -source = "git+https://github.com/ethcore/parity-idmanager-rs.git#efb69592b87854f41d8882de75982c8f1e748666" +version = "0.2.0" +source = "git+https://github.com/ethcore/parity-idmanager-rs.git#be59a97cdd15dd733583938973ef65ff3beab463" dependencies = [ - "parity-webapp 0.1.0 (git+https://github.com/ethcore/parity-webapp.git)", + "parity-webapp 0.2.0 (git+https://github.com/ethcore/parity-webapp.git)", ] [[package]] name = "parity-status" -version = "0.4.1" -source = "git+https://github.com/ethcore/parity-status.git#f121ebd1f49986545d9fc262ba210cdf07039e6d" +version = "0.4.0" +source = "git+https://github.com/ethcore/parity-status.git#0ab708f869366543a8de953300e49098be0b7dbd" dependencies = [ - "parity-webapp 0.1.0 (git+https://github.com/ethcore/parity-webapp.git)", + "parity-webapp 0.2.0 (git+https://github.com/ethcore/parity-webapp.git)", ] [[package]] name = "parity-wallet" -version = "0.3.0" -source = "git+https://github.com/ethcore/parity-wallet.git#664fd2b85dd94ca184868bd3965e14a4ba68c03f" +version = "0.4.0" +source = "git+https://github.com/ethcore/parity-wallet.git#5391a89dc5dbf162d1beeba555f03c24bfd619bd" dependencies = [ - "parity-webapp 0.1.0 (git+https://github.com/ethcore/parity-webapp.git)", + "parity-webapp 0.2.0 (git+https://github.com/ethcore/parity-webapp.git)", ] [[package]] name = "parity-webapp" -version = "0.1.0" -source = "git+https://github.com/ethcore/parity-webapp.git#0bf133f193863ba0e88b0b824a5c330037cce3f1" +version = "0.2.0" +source = "git+https://github.com/ethcore/parity-webapp.git#f31681af69631bcadfbef89a7e60dcc49552f7c6" [[package]] name = "primal" diff --git a/webapp/Cargo.toml b/webapp/Cargo.toml index fe6fb9bf6..1d71a9126 100644 --- a/webapp/Cargo.toml +++ b/webapp/Cargo.toml @@ -4,6 +4,7 @@ name = "ethcore-webapp" version = "1.2.0" license = "GPL-3.0" authors = ["Ethcore . + +#[cfg(not(feature = "serde_macros"))] +mod inner { + extern crate syntex; + extern crate serde_codegen; + + use std::env; + use std::path::Path; + + pub fn main() { + let out_dir = env::var_os("OUT_DIR").unwrap(); + + let src = Path::new("./src/api/mod.rs.in"); + let dst = Path::new(&out_dir).join("mod.rs"); + + let mut registry = syntex::Registry::new(); + + serde_codegen::register(&mut registry); + registry.expand("", &src, &dst).unwrap(); + } +} + +#[cfg(feature = "serde_macros")] +mod inner { + pub fn main() {} +} + +fn main() { + inner::main(); +} diff --git a/webapp/src/api.rs b/webapp/src/api/api.rs similarity index 59% rename from webapp/src/api.rs rename to webapp/src/api/api.rs index 75cdb4c58..fdfef1394 100644 --- a/webapp/src/api.rs +++ b/webapp/src/api/api.rs @@ -14,15 +14,26 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -//! Simple REST API - use std::sync::Arc; -use endpoint::{Endpoint, Endpoints, ContentHandler, Handler, EndpointPath}; +use endpoint::{Endpoint, Endpoints, Handler, EndpointPath}; + +use api::response::as_json; pub struct RestApi { endpoints: Arc, } +#[derive(Debug, PartialEq, Serialize)] +struct App { + pub id: String, + pub name: String, + pub description: String, + pub version: String, + pub author: String, + #[serde(rename="iconUrl")] + pub icon_url: String, +} + impl RestApi { pub fn new(endpoints: Arc) -> Box { Box::new(RestApi { @@ -30,20 +41,23 @@ impl RestApi { }) } - fn list_pages(&self) -> String { - let mut s = "[".to_owned(); - for name in self.endpoints.keys() { - s.push_str(&format!("\"{}\",", name)); - } - s.push_str("\"rpc\""); - s.push_str("]"); - s + fn list_apps(&self) -> Vec { + self.endpoints.iter().filter_map(|(ref k, ref e)| { + e.info().map(|ref info| App { + id: k.to_owned().clone(), + name: info.name.clone(), + description: info.description.clone(), + version: info.version.clone(), + author: info.author.clone(), + icon_url: info.icon_url.clone(), + }) + }).collect() } } impl Endpoint for RestApi { fn to_handler(&self, _path: EndpointPath) -> Box { - Box::new(ContentHandler::new(self.list_pages(), "application/json".to_owned())) + as_json(&self.list_apps()) } } diff --git a/webapp/src/api/mod.rs b/webapp/src/api/mod.rs new file mode 100644 index 000000000..088d7f6b2 --- /dev/null +++ b/webapp/src/api/mod.rs @@ -0,0 +1,28 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +//! REST API + +#![warn(missing_docs)] +#![cfg_attr(feature="nightly", feature(custom_derive, custom_attribute, plugin))] +#![cfg_attr(feature="nightly", plugin(serde_macros, clippy))] + +#[cfg(feature = "serde_macros")] +include!("mod.rs.in"); + +#[cfg(not(feature = "serde_macros"))] +include!(concat!(env!("OUT_DIR"), "/mod.rs")); + diff --git a/webapp/src/api/mod.rs.in b/webapp/src/api/mod.rs.in new file mode 100644 index 000000000..0eff6b397 --- /dev/null +++ b/webapp/src/api/mod.rs.in @@ -0,0 +1,20 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +mod api; +mod response; + +pub use self::api::RestApi; diff --git a/webapp/src/api/response.rs b/webapp/src/api/response.rs new file mode 100644 index 000000000..345b8a6ee --- /dev/null +++ b/webapp/src/api/response.rs @@ -0,0 +1,23 @@ +// Copyright 2015, 2016 Ethcore (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +use serde::Serialize; +use serde_json; +use endpoint::{ContentHandler, Handler}; + +pub fn as_json(val: &T) -> Box { + Box::new(ContentHandler::new(serde_json::to_string(val).unwrap(), "application/json".to_owned())) +} diff --git a/webapp/src/endpoint.rs b/webapp/src/endpoint.rs index d367734c4..ebb665b9d 100644 --- a/webapp/src/endpoint.rs +++ b/webapp/src/endpoint.rs @@ -30,7 +30,18 @@ pub struct EndpointPath { pub port: u16, } +#[derive(Debug, PartialEq)] +pub struct EndpointInfo { + pub name: String, + pub description: String, + pub version: String, + pub author: String, + pub icon_url: String, +} + pub trait Endpoint : Send + Sync { + fn info(&self) -> Option { None } + fn to_handler(&self, path: EndpointPath) -> Box>; } diff --git a/webapp/src/lib.rs b/webapp/src/lib.rs index 819e9d362..4cf8f0764 100644 --- a/webapp/src/lib.rs +++ b/webapp/src/lib.rs @@ -47,6 +47,8 @@ extern crate log; extern crate url; extern crate hyper; +extern crate serde; +extern crate serde_json; extern crate jsonrpc_core; extern crate jsonrpc_http_server; extern crate parity_webapp; diff --git a/webapp/src/page/mod.rs b/webapp/src/page/mod.rs index 1d987c393..c4e39161c 100644 --- a/webapp/src/page/mod.rs +++ b/webapp/src/page/mod.rs @@ -22,8 +22,8 @@ use hyper::header; use hyper::status::StatusCode; use hyper::net::HttpStream; use hyper::{Decoder, Encoder, Next}; -use endpoint::{Endpoint, EndpointPath}; -use parity_webapp::WebApp; +use endpoint::{Endpoint, EndpointInfo, EndpointPath}; +use parity_webapp::{WebApp, Info}; pub struct PageEndpoint { /// Content of the files @@ -39,6 +39,7 @@ impl PageEndpoint { prefix: None, } } + pub fn with_prefix(app: T, prefix: String) -> Self { PageEndpoint { app: Arc::new(app), @@ -48,6 +49,11 @@ impl PageEndpoint { } impl Endpoint for PageEndpoint { + + fn info(&self) -> Option { + Some(EndpointInfo::from(self.app.info())) + } + fn to_handler(&self, path: EndpointPath) -> Box> { Box::new(PageHandler { app: self.app.clone(), @@ -59,6 +65,18 @@ impl Endpoint for PageEndpoint { } } +impl From for EndpointInfo { + fn from(info: Info) -> Self { + EndpointInfo { + name: info.name, + description: info.description, + author: info.author, + icon_url: info.icon_url, + version: info.version, + } + } +} + struct PageHandler { app: Arc, prefix: Option, From b9febdda3449ce1c409e5d54f945c3b52c6a892d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Wed, 18 May 2016 11:54:15 +0200 Subject: [PATCH 31/32] Home page --- Cargo.lock | 12 ++++++------ webapp/Cargo.toml | 4 ++-- webapp/src/apps.rs | 3 ++- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index d463dafe6..4ed88790c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -356,8 +356,8 @@ dependencies = [ "jsonrpc-core 2.0.4 (registry+https://github.com/rust-lang/crates.io-index)", "jsonrpc-http-server 5.1.0 (git+https://github.com/ethcore/jsonrpc-http-server.git)", "log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", - "parity-idmanager 0.2.0 (git+https://github.com/ethcore/parity-idmanager-rs.git)", - "parity-status 0.4.0 (git+https://github.com/ethcore/parity-status.git)", + "parity-idmanager 0.2.2 (git+https://github.com/ethcore/parity-idmanager-rs.git)", + "parity-status 0.4.3 (git+https://github.com/ethcore/parity-status.git)", "parity-wallet 0.4.0 (git+https://github.com/ethcore/parity-wallet.git)", "parity-webapp 0.2.0 (git+https://github.com/ethcore/parity-webapp.git)", "rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)", @@ -836,16 +836,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "parity-idmanager" -version = "0.2.0" -source = "git+https://github.com/ethcore/parity-idmanager-rs.git#be59a97cdd15dd733583938973ef65ff3beab463" +version = "0.2.2" +source = "git+https://github.com/ethcore/parity-idmanager-rs.git#a1c2ab1893d4abe801c821eb49247d89ab016d44" dependencies = [ "parity-webapp 0.2.0 (git+https://github.com/ethcore/parity-webapp.git)", ] [[package]] name = "parity-status" -version = "0.4.0" -source = "git+https://github.com/ethcore/parity-status.git#0ab708f869366543a8de953300e49098be0b7dbd" +version = "0.4.3" +source = "git+https://github.com/ethcore/parity-status.git#1d383d74010f6ebcd712b60b8fc5ff547b44f4e5" dependencies = [ "parity-webapp 0.2.0 (git+https://github.com/ethcore/parity-webapp.git)", ] diff --git a/webapp/Cargo.toml b/webapp/Cargo.toml index 1d71a9126..8f9353386 100644 --- a/webapp/Cargo.toml +++ b/webapp/Cargo.toml @@ -22,8 +22,8 @@ ethcore-rpc = { path = "../rpc" } ethcore-util = { path = "../util" } parity-webapp = { git = "https://github.com/ethcore/parity-webapp.git", version = "0.2" } # List of apps -parity-status = { git = "https://github.com/ethcore/parity-status.git", version = "0.4.0" } -parity-idmanager = { git = "https://github.com/ethcore/parity-idmanager-rs.git", version = "0.2.0" } +parity-status = { git = "https://github.com/ethcore/parity-status.git", version = "0.4.3" } +parity-idmanager = { git = "https://github.com/ethcore/parity-idmanager-rs.git", version = "0.2.2" } parity-wallet = { git = "https://github.com/ethcore/parity-wallet.git", version = "0.4.0", optional = true } clippy = { version = "0.0.67", optional = true} diff --git a/webapp/src/apps.rs b/webapp/src/apps.rs index 1c9b7e5a8..410a5bc2c 100644 --- a/webapp/src/apps.rs +++ b/webapp/src/apps.rs @@ -30,7 +30,7 @@ pub const API_PATH : &'static str = "api"; pub const UTILS_PATH : &'static str = "parity-utils"; pub fn main_page() -> &'static str { - "/status/" + "/home/" } pub fn utils() -> Box { @@ -43,6 +43,7 @@ pub fn all_endpoints() -> Endpoints { insert::(&mut pages, "status"); insert::(&mut pages, "parity"); + insert::(&mut pages, "home"); wallet_page(&mut pages); pages From ef38d9c769510e018e9331eb198aac827890f7de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomasz=20Drwi=C4=99ga?= Date: Wed, 18 May 2016 12:19:40 +0200 Subject: [PATCH 32/32] Updating idmanager --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 4ed88790c..932b077fc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -837,7 +837,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "parity-idmanager" version = "0.2.2" -source = "git+https://github.com/ethcore/parity-idmanager-rs.git#a1c2ab1893d4abe801c821eb49247d89ab016d44" +source = "git+https://github.com/ethcore/parity-idmanager-rs.git#e93ef48a78722561d52ab88c3dfcc5c1465558ac" dependencies = [ "parity-webapp 0.2.0 (git+https://github.com/ethcore/parity-webapp.git)", ]