Merge remote-tracking branch 'origin/master' into vmtracing

This commit is contained in:
Gav Wood 2016-05-29 11:13:48 +02:00
commit a5808833b1
49 changed files with 980 additions and 57 deletions

35
Cargo.lock generated
View File

@ -105,6 +105,11 @@ name = "bloomchain"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "byteorder"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "bytes"
version = "0.3.0"
@ -326,7 +331,9 @@ dependencies = [
"clippy 0.0.69 (registry+https://github.com/rust-lang/crates.io-index)",
"ethash 1.2.0",
"ethcore 1.2.0",
"ethcore-devtools 1.2.0",
"ethcore-util 1.2.0",
"ethjson 0.1.0",
"ethminer 1.2.0",
"ethsync 1.2.0",
"json-ipc-server 0.1.0 (git+https://github.com/ethcore/json-ipc-server.git)",
@ -347,9 +354,16 @@ version = "1.2.0"
dependencies = [
"clippy 0.0.69 (registry+https://github.com/rust-lang/crates.io-index)",
"env_logger 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
"ethcore-rpc 1.2.0",
"ethcore-util 1.2.0",
"log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-serialize 0.3.19 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc_version 0.1.7 (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)",
"ws 0.4.7 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@ -1161,6 +1175,14 @@ dependencies = [
"serde 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "sha1"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"byteorder 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "sha3"
version = "0.1.0"
@ -1405,6 +1427,19 @@ name = "winapi-build"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
[[package]]
name = "ws"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"httparse 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
"log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
"mio 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)",
"rand 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)",
"sha1 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"url 0.5.9 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "ws2_32-sys"
version = "0.2.1"

View File

@ -34,9 +34,9 @@
//! let io = IoHandler::new();
//! io.add_method("say_hello", SayHello);
//! let _server = Server::start_unsecure_http(
//! &"127.0.0.1:3030".parse().unwrap(),
//! Arc::new(io)
//! );
//! &"127.0.0.1:3030".parse().unwrap(),
//! Arc::new(io)
//! );
//! }
//! ```
//!

View File

@ -17,7 +17,7 @@
use bloomchain::group as bc;
use util::HeapSizeOf;
/// Represents BloomGroup position in database.
/// Represents `BloomGroup` position in database.
#[derive(PartialEq, Eq, Hash, Clone, Debug)]
pub struct GroupPosition {
/// Bloom level.

View File

@ -54,7 +54,7 @@ impl Key<BlockTraces> for H256 {
}
}
/// Wrapper around blooms::GroupPosition so it could be
/// Wrapper around `blooms::GroupPosition` so it could be
/// uniquely identified in the database.
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
struct TraceGroupPosition(blooms::GroupPosition);

View File

@ -36,6 +36,7 @@ pub enum Action {
/// Create creates new contract.
Create,
/// Calls contract at given address.
/// In the case of a transfer, this is the receiver's address.'
Call(Address),
}

View File

@ -19,6 +19,7 @@
use rustc_serialize::hex::FromHex;
use serde::{Deserialize, Deserializer, Error};
use serde::de::Visitor;
use std::ops::Deref;
/// Lenient bytes json deserialization for test json files.
#[derive(Default, Debug, PartialEq, Clone)]
@ -30,6 +31,14 @@ impl Into<Vec<u8>> for Bytes {
}
}
impl Deref for Bytes {
type Target = Vec<u8>;
fn deref(&self) -> &Vec<u8> {
&self.0
}
}
impl Deserialize for Bytes {
fn deserialize<D>(deserializer: &mut D) -> Result<Self, D::Error>
where D: Deserializer {

View File

@ -39,16 +39,47 @@ pub struct Call {
mod tests {
use serde_json;
use vm::Call;
use util::numbers::U256;
use uint::Uint;
use util::hash::Address as Hash160;
use hash::Address;
use maybe::MaybeEmpty;
use std::str::FromStr;
#[test]
fn call_deserialization() {
fn call_deserialization_empty_dest() {
let s = r#"{
"data" : "0x1111222233334444555566667777888899990000aaaabbbbccccddddeeeeffff",
"destination" : "",
"gasLimit" : "0x1748766aa5",
"value" : "0x00"
}"#;
let _deserialized: Call = serde_json::from_str(s).unwrap();
// TODO: validate all fields
let call: Call = serde_json::from_str(s).unwrap();
assert_eq!(&call.data[..],
&[0x11, 0x11, 0x22, 0x22, 0x33, 0x33, 0x44, 0x44, 0x55, 0x55, 0x66, 0x66, 0x77, 0x77,
0x88, 0x88, 0x99, 0x99, 0x00, 0x00, 0xaa, 0xaa, 0xbb, 0xbb, 0xcc, 0xcc, 0xdd, 0xdd,
0xee, 0xee, 0xff, 0xff]);
assert_eq!(call.destination, MaybeEmpty::None);
assert_eq!(call.gas_limit, Uint(U256::from(0x1748766aa5u64)));
assert_eq!(call.value, Uint(U256::from(0)));
}
#[test]
fn call_deserialization_full_dest() {
let s = r#"{
"data" : "0x1234",
"destination" : "5a39ed1020c04d4d84539975b893a4e7c53eab6c",
"gasLimit" : "0x1748766aa5",
"value" : "0x00"
}"#;
let call: Call = serde_json::from_str(s).unwrap();
assert_eq!(&call.data[..], &[0x12, 0x34]);
assert_eq!(call.destination, MaybeEmpty::Some(Address(Hash160::from_str("5a39ed1020c04d4d84539975b893a4e7c53eab6c").unwrap())));
assert_eq!(call.gas_limit, Uint(U256::from(0x1748766aa5u64)));
assert_eq!(call.value, Uint(U256::from(0)));
}
}

View File

@ -107,12 +107,12 @@ pub trait MinerService : Send + Sync {
/// Imports transactions to transaction queue.
fn import_transactions<T>(&self, transactions: Vec<SignedTransaction>, fetch_account: T) ->
Vec<Result<TransactionImportResult, Error>>
where T: Fn(&Address) -> AccountDetails;
where T: Fn(&Address) -> AccountDetails, Self: Sized;
/// Imports own (node owner) transaction to queue.
fn import_own_transaction<T>(&self, chain: &BlockChainClient, transaction: SignedTransaction, fetch_account: T) ->
Result<TransactionImportResult, Error>
where T: Fn(&Address) -> AccountDetails;
where T: Fn(&Address) -> AccountDetails, Self: Sized;
/// Returns hashes of transactions currently in pending
fn pending_transactions_hashes(&self) -> Vec<H256>;
@ -131,7 +131,8 @@ pub trait MinerService : Send + Sync {
fn submit_seal(&self, chain: &BlockChainClient, pow_hash: H256, seal: Vec<Bytes>) -> Result<(), Error>;
/// Get the sealing work package and if `Some`, apply some transform.
fn map_sealing_work<F, T>(&self, chain: &BlockChainClient, f: F) -> Option<T> where F: FnOnce(&ClosedBlock) -> T;
fn map_sealing_work<F, T>(&self, chain: &BlockChainClient, f: F) -> Option<T>
where F: FnOnce(&ClosedBlock) -> T, Self: Sized;
/// Query pending transactions for hash.
fn transaction(&self, hash: &H256) -> Option<SignedTransaction>;

View File

@ -97,6 +97,11 @@ API and Console Options:
--dapps-pass PASSWORD Specify password for Dapps server. Use only in
conjunction with --dapps-user.
--signer Enable Trusted Signer WebSocket endpoint used by
System UIs.
--signer-port PORT Specify the port of Trusted Signer server
[default: 8180].
Sealing/Mining Options:
--force-sealing Force the node to author new blocks as if it were
always sealing/mining.
@ -234,6 +239,8 @@ pub struct Args {
pub flag_dapps_interface: String,
pub flag_dapps_user: Option<String>,
pub flag_dapps_pass: Option<String>,
pub flag_signer: bool,
pub flag_signer_port: u16,
pub flag_force_sealing: bool,
pub flag_author: String,
pub flag_usd_per_tx: String,

View File

@ -50,6 +50,9 @@ extern crate ethcore_rpc;
#[cfg(feature = "dapps")]
extern crate ethcore_dapps;
#[cfg(feature = "ethcore-signer")]
extern crate ethcore_signer;
#[macro_use]
mod die;
mod price_info;
@ -63,6 +66,7 @@ mod io_handler;
mod cli;
mod configuration;
mod migration;
mod signer;
use std::io::{Write, Read, BufReader, BufRead};
use std::ops::Deref;
@ -89,6 +93,7 @@ use informant::Informant;
use die::*;
use cli::print_version;
use rpc::RpcServer;
use signer::SignerServer;
use dapps::WebappServer;
use io_handler::ClientIoHandler;
use configuration::Configuration;
@ -231,6 +236,14 @@ fn execute_client(conf: Configuration, spec: Spec, client_config: ClientConfig)
settings: network_settings.clone(),
});
// Set up a signer
let signer_server = signer::start(signer::Configuration {
enabled: conf.args.flag_signer,
port: conf.args.flag_signer_port,
}, signer::Dependencies {
panic_handler: panic_handler.clone(),
});
// Register IO handler
let io_handler = Arc::new(ClientIoHandler {
client: service.client(),
@ -241,7 +254,7 @@ fn execute_client(conf: Configuration, spec: Spec, client_config: ClientConfig)
service.io().register_handler(io_handler).expect("Error registering IO handler");
// Handle exit
wait_for_exit(panic_handler, rpc_server, dapps_server);
wait_for_exit(panic_handler, rpc_server, dapps_server, signer_server);
}
fn flush_stdout() {
@ -453,7 +466,12 @@ fn execute_account_cli(conf: Configuration) {
}
}
fn wait_for_exit(panic_handler: Arc<PanicHandler>, _rpc_server: Option<RpcServer>, _dapps_server: Option<WebappServer>) {
fn wait_for_exit(
panic_handler: Arc<PanicHandler>,
_rpc_server: Option<RpcServer>,
_dapps_server: Option<WebappServer>,
_signer_server: Option<SignerServer>
) {
let exit = Arc::new(Condvar::new());
// Handle possible exits

View File

@ -73,7 +73,7 @@ fn version_file_path(path: &PathBuf) -> PathBuf {
}
/// Reads current database version from the file at given path.
/// If the file does not exist returns DEFAULT_VERSION.
/// If the file does not exist returns `DEFAULT_VERSION`.
fn current_version(path: &PathBuf) -> Result<u32, Error> {
match File::open(version_file_path(path)) {
Err(ref err) if err.kind() == ErrorKind::NotFound => Ok(DEFAULT_VERSION),

View File

@ -27,6 +27,8 @@ pub fn setup_log(init: &Option<String>) -> Arc<RotatingLogger> {
let mut levels = String::new();
let mut builder = LogBuilder::new();
// Disable ws info logging by default.
builder.filter(Some("ws"), LogLevelFilter::Warn);
builder.filter(None, LogLevelFilter::Info);
if env::var("RUST_LOG").is_ok() {

67
parity/signer.rs Normal file
View File

@ -0,0 +1,67 @@
// 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 <http://www.gnu.org/licenses/>.
use std::sync::Arc;
use util::panics::{PanicHandler, ForwardPanic};
use die::*;
#[cfg(feature = "ethcore-signer")]
use ethcore_signer as signer;
#[cfg(feature = "ethcore-signer")]
pub use ethcore_signer::Server as SignerServer;
#[cfg(not(feature = "ethcore-signer"))]
pub struct SignerServer;
pub struct Configuration {
pub enabled: bool,
pub port: u16,
}
pub struct Dependencies {
pub panic_handler: Arc<PanicHandler>,
}
#[cfg(feature = "ethcore-signer")]
pub fn start(conf: Configuration, deps: Dependencies) -> Option<SignerServer> {
if !conf.enabled {
return None;
}
let addr = format!("127.0.0.1:{}", conf.port).parse().unwrap_or_else(|_| die!("Invalid port specified: {}", conf.port));
let start_result = signer::Server::start(addr);
match start_result {
Err(signer::ServerError::IoError(err)) => die_with_io_error("Trusted Signer", err),
Err(e) => die!("Trusted Signer: {:?}", e),
Ok(server) => {
deps.panic_handler.forward_from(&server);
Some(server)
},
}
}
#[cfg(not(feature = "ethcore-signer"))]
pub fn start(conf: Configuration) -> Option<SignerServer> {
if !conf.enabled {
return None;
}
die!("Your Parity version has been compiled without Trusted Signer support.")
}

View File

@ -19,6 +19,8 @@ ethcore = { path = "../ethcore" }
ethash = { path = "../ethash" }
ethsync = { path = "../sync" }
ethminer = { path = "../miner" }
ethjson = { path = "../json" }
ethcore-devtools = { path = "../devtools" }
rustc-serialize = "0.3"
transient-hashmap = "0.1"
serde_macros = { version = "0.7.0", optional = true }

View File

@ -34,6 +34,11 @@ extern crate ethminer;
extern crate transient_hashmap;
extern crate json_ipc_server as ipc;
#[cfg(test)]
extern crate ethjson;
#[cfg(test)]
extern crate ethcore_devtools as devtools;
use std::sync::Arc;
use std::net::SocketAddr;
use self::jsonrpc_core::{IoHandler, IoDelegate};

View File

@ -22,8 +22,8 @@ use std::sync::{Arc, Weak};
use std::ops::Deref;
use std::collections::BTreeMap;
use jsonrpc_core::*;
use ethminer::{MinerService};
use ethcore::client::{BlockChainClient};
use ethminer::MinerService;
use ethcore::client::BlockChainClient;
use ethcore::trace::VMTrace;
use ethcore::transaction::{Transaction as EthTransaction, SignedTransaction, Action};
use ethcore::get_info;

View File

@ -18,12 +18,12 @@
//!
//! Compliant with ethereum rpc.
pub mod traits;
mod impls;
mod types;
mod helpers;
pub mod traits;
pub mod tests;
pub mod types;
pub use self::traits::{Web3, Eth, EthFilter, Personal, Net, Ethcore, Traces, Rpc};
pub use self::impls::*;

229
rpc/src/v1/tests/eth.rs Normal file
View File

@ -0,0 +1,229 @@
// Copyright 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 <http://www.gnu.org/licenses/>.
//! rpc integration tests.
use std::collections::HashMap;
use std::sync::Arc;
use std::str::FromStr;
use ethcore::client::{BlockChainClient, Client, ClientConfig};
use ethcore::spec::Genesis;
use ethcore::block::Block;
use ethcore::ethereum;
use ethcore::transaction::{Transaction, Action};
use ethminer::{MinerService, ExternalMiner};
use devtools::RandomTempPath;
use util::io::IoChannel;
use util::hash::{Address, FixedHash};
use util::numbers::{Uint, U256};
use util::keys::{AccountProvider, TestAccount, TestAccountProvider};
use jsonrpc_core::IoHandler;
use ethjson::blockchain::BlockChain;
use v1::traits::eth::Eth;
use v1::impls::EthClient;
use v1::tests::helpers::{TestSyncProvider, Config, TestMinerService};
struct EthTester {
_client: Arc<BlockChainClient>,
_miner: Arc<MinerService>,
accounts: Arc<TestAccountProvider>,
handler: IoHandler,
}
#[test]
fn harness_works() {
let chain: BlockChain = extract_chain!("BlockchainTests/bcUncleTest");
chain_harness(chain, |_| {});
}
#[test]
fn eth_get_balance() {
let chain = extract_chain!("BlockchainTests/bcWalletTest", "wallet2outOf3txs");
chain_harness(chain, |tester| {
// final account state
let req_latest = r#"{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": ["0xaaaf5374fce5edbc8e2a8697c15331677e6ebaaa", "latest"],
"id": 1
}"#;
let res_latest = r#"{"jsonrpc":"2.0","result":"0x09","id":1}"#.to_owned();
assert_eq!(tester.handler.handle_request(req_latest).unwrap(), res_latest);
// non-existant account
let req_new_acc = r#"{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": ["0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"],
"id": 3
}"#;
let res_new_acc = r#"{"jsonrpc":"2.0","result":"0x00","id":3}"#.to_owned();
assert_eq!(tester.handler.handle_request(req_new_acc).unwrap(), res_new_acc);
});
}
#[test]
fn eth_block_number() {
let chain = extract_chain!("BlockchainTests/bcRPC_API_Test");
chain_harness(chain, |tester| {
let req_number = r#"{
"jsonrpc": "2.0",
"method": "eth_blockNumber",
"params": [],
"id": 1
}"#;
let res_number = r#"{"jsonrpc":"2.0","result":"0x20","id":1}"#.to_owned();
assert_eq!(tester.handler.handle_request(req_number).unwrap(), res_number);
});
}
#[cfg(test)]
#[test]
fn eth_transaction_count() {
let chain = extract_chain!("BlockchainTests/bcRPC_API_Test");
chain_harness(chain, |tester| {
let address = tester.accounts.new_account("123").unwrap();
let secret = tester.accounts.account_secret(&address).unwrap();
let req_before = r#"{
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [""#.to_owned() + format!("0x{:?}", address).as_ref() + r#"", "latest"],
"id": 15
}"#;
let res_before = r#"{"jsonrpc":"2.0","result":"0x00","id":15}"#;
assert_eq!(tester.handler.handle_request(&req_before).unwrap(), res_before);
let t = Transaction {
nonce: U256::zero(),
gas_price: U256::from(0x9184e72a000u64),
gas: U256::from(0x76c0),
action: Action::Call(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
value: U256::from(0x9184e72au64),
data: vec![]
}.sign(&secret);
let req_send_trans = r#"{
"jsonrpc": "2.0",
"method": "eth_sendTransaction",
"params": [{
"from": ""#.to_owned() + format!("0x{:?}", address).as_ref() + r#"",
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
"gas": "0x76c0",
"gasPrice": "0x9184e72a000",
"value": "0x9184e72a"
}],
"id": 16
}"#;
let res_send_trans = r#"{"jsonrpc":"2.0","result":""#.to_owned() + format!("0x{:?}", t.hash()).as_ref() + r#"","id":16}"#;
// dispatch the transaction.
assert_eq!(tester.handler.handle_request(&req_send_trans).unwrap(), res_send_trans);
// we have submitted the transaction -- but this shouldn't be reflected in a "latest" query.
let req_after_latest = r#"{
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [""#.to_owned() + format!("0x{:?}", address).as_ref() + r#"", "latest"],
"id": 17
}"#;
let res_after_latest = r#"{"jsonrpc":"2.0","result":"0x00","id":17}"#;
assert_eq!(&tester.handler.handle_request(&req_after_latest).unwrap(), res_after_latest);
// the pending transactions should have been updated.
let req_after_pending = r#"{
"jsonrpc": "2.0",
"method": "eth_getTransactionCount",
"params": [""#.to_owned() + format!("0x{:?}", address).as_ref() + r#"", "pending"],
"id": 18
}"#;
let res_after_pending = r#"{"jsonrpc":"2.0","result":"0x01","id":18}"#;
assert_eq!(&tester.handler.handle_request(&req_after_pending).unwrap(), res_after_pending);
});
}
fn account_provider() -> Arc<TestAccountProvider> {
let mut accounts = HashMap::new();
accounts.insert(Address::from(1), TestAccount::new("test"));
let ap = TestAccountProvider::new(accounts);
Arc::new(ap)
}
fn sync_provider() -> Arc<TestSyncProvider> {
Arc::new(TestSyncProvider::new(Config {
network_id: U256::from(3),
num_peers: 120,
}))
}
fn miner_service() -> Arc<TestMinerService> {
Arc::new(TestMinerService::default())
}
// given a blockchain, this harness will create an EthClient wrapping it
// which tests can pass specially crafted requests to.
fn chain_harness<F, U>(chain: BlockChain, mut cb: F) -> U
where F: FnMut(&EthTester) -> U {
let genesis = Genesis::from(chain.genesis());
let mut spec = ethereum::new_frontier_test();
let state = chain.pre_state.clone().into();
spec.set_genesis_state(state);
spec.overwrite_genesis_params(genesis);
assert!(spec.is_state_root_valid());
let dir = RandomTempPath::new();
let client = Client::new(ClientConfig::default(), spec, dir.as_path(), IoChannel::disconnected()).unwrap();
let sync_provider = sync_provider();
let miner_service = miner_service();
let account_provider = account_provider();
let external_miner = Arc::new(ExternalMiner::default());
for b in &chain.blocks_rlp() {
if Block::is_good(&b) {
let _ = client.import_block(b.clone());
client.flush_queue();
client.import_verified_blocks(&IoChannel::disconnected());
}
}
assert!(client.chain_info().best_block_hash == chain.best_block.into());
let eth_client = EthClient::new(&client, &sync_provider, &account_provider,
&miner_service, &external_miner);
let handler = IoHandler::new();
let delegate = eth_client.to_delegate();
handler.add_delegate(delegate);
let tester = EthTester {
_miner: miner_service,
_client: client,
accounts: account_provider,
handler: handler,
};
cb(&tester)
}

View File

@ -115,12 +115,16 @@ impl MinerService for TestMinerService {
}
/// Imports transactions to transaction queue.
fn import_transactions<T>(&self, transactions: Vec<SignedTransaction>, _fetch_account: T) ->
fn import_transactions<T>(&self, transactions: Vec<SignedTransaction>, fetch_account: T) ->
Vec<Result<TransactionImportResult, Error>>
where T: Fn(&Address) -> AccountDetails {
// lets assume that all txs are valid
self.imported_transactions.lock().unwrap().extend_from_slice(&transactions);
for sender in transactions.iter().filter_map(|t| t.sender().ok()) {
let nonce = self.last_nonce(&sender).unwrap_or(fetch_account(&sender).nonce);
self.last_nonces.write().unwrap().insert(sender, nonce + U256::from(1));
}
transactions
.iter()
.map(|_| Ok(TransactionImportResult::Current))
@ -128,9 +132,16 @@ impl MinerService for TestMinerService {
}
/// Imports transactions to transaction queue.
fn import_own_transaction<T>(&self, _chain: &BlockChainClient, transaction: SignedTransaction, _fetch_account: T) ->
fn import_own_transaction<T>(&self, chain: &BlockChainClient, transaction: SignedTransaction, _fetch_account: T) ->
Result<TransactionImportResult, Error>
where T: Fn(&Address) -> AccountDetails {
// keep the pending nonces up to date
if let Ok(ref sender) = transaction.sender() {
let nonce = self.last_nonce(sender).unwrap_or(chain.latest_nonce(sender));
self.last_nonces.write().unwrap().insert(sender.clone(), nonce + U256::from(1));
}
// lets assume that all txs are valid
self.imported_transactions.lock().unwrap().push(transaction);
@ -200,7 +211,9 @@ impl MinerService for TestMinerService {
}
fn nonce(&self, _chain: &BlockChainClient, address: &Address) -> U256 {
self.latest_closed_block.lock().unwrap().as_ref().map_or_else(U256::zero, |b| b.block().fields().state.nonce(address).clone())
// we assume all transactions are in a pending block, ignoring the
// reality of gas limits.
self.last_nonce(address).unwrap_or(U256::zero())
}
fn code(&self, _chain: &BlockChainClient, address: &Address) -> Option<Bytes> {

View File

@ -20,4 +20,4 @@ mod sync_provider;
mod miner_service;
pub use self::sync_provider::{Config, TestSyncProvider};
pub use self::miner_service::{TestMinerService};
pub use self::miner_service::TestMinerService;

View File

@ -16,9 +16,9 @@
//! Test implementation of SyncProvider.
use util::{U256};
use util::U256;
use ethsync::{SyncProvider, SyncStatus, SyncState};
use std::sync::{RwLock};
use std::sync::RwLock;
/// TestSyncProvider config.
pub struct Config {

View File

@ -14,7 +14,8 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! RPC serialization tests.
//! RPC mocked tests. Most of these test that the RPC server is serializing and forwarding
//! method calls properly.
mod eth;
mod net;

View File

@ -2,5 +2,40 @@
pub mod helpers;
// extract a chain from the given JSON file,
// stored in ethcore/res/ethereum/tests/.
//
// usage:
// `extract_chain!("Folder/File")` will load Folder/File.json and extract
// the first block chain stored within.
//
// `extract_chain!("Folder/File", "with_name")` will load Folder/File.json and
// extract the chain with that name. This will panic if no chain by that name
// is found.
macro_rules! extract_chain {
($file:expr, $name:expr) => {{
const RAW_DATA: &'static [u8] =
include_bytes!(concat!("../../../../ethcore/res/ethereum/tests/", $file, ".json"));
let mut chain = None;
for (name, c) in ::ethjson::blockchain::Test::load(RAW_DATA).unwrap() {
if name == $name {
chain = Some(c);
break;
}
}
chain.unwrap()
}};
($file:expr) => {{
const RAW_DATA: &'static [u8] =
include_bytes!(concat!("../../../../ethcore/res/ethereum/tests/", $file, ".json"));
::ethjson::blockchain::Test::load(RAW_DATA)
.unwrap().into_iter().next().unwrap().1
}};
}
#[cfg(test)]
mod mocked;
mod mocked;
#[cfg(test)]
mod eth;

View File

@ -18,9 +18,12 @@ use serde::{Serialize, Serializer};
use util::numbers::*;
use v1::types::{Bytes, Transaction, OptionalValue};
/// Block Transactions
#[derive(Debug)]
pub enum BlockTransactions {
/// Only hashes
Hashes(Vec<H256>),
/// Full transactions
Full(Vec<Transaction>)
}
@ -34,38 +37,58 @@ impl Serialize for BlockTransactions {
}
}
/// Block representation
#[derive(Debug, Serialize)]
pub struct Block {
/// Hash of the block
pub hash: OptionalValue<H256>,
/// Hash of the parent
#[serde(rename="parentHash")]
pub parent_hash: H256,
/// Hash of the uncles
#[serde(rename="sha3Uncles")]
pub uncles_hash: H256,
/// Authors address
pub author: Address,
// TODO: get rid of this one
/// ?
pub miner: Address,
/// State root hash
#[serde(rename="stateRoot")]
pub state_root: H256,
/// Transactions root hash
#[serde(rename="transactionsRoot")]
pub transactions_root: H256,
/// Transactions receipts root hash
#[serde(rename="receiptsRoot")]
pub receipts_root: H256,
/// Block number
pub number: OptionalValue<U256>,
/// Gas Used
#[serde(rename="gasUsed")]
pub gas_used: U256,
/// Gas Limit
#[serde(rename="gasLimit")]
pub gas_limit: U256,
/// Extra data
#[serde(rename="extraData")]
pub extra_data: Bytes,
/// Logs bloom
#[serde(rename="logsBloom")]
pub logs_bloom: H2048,
/// Timestamp
pub timestamp: U256,
/// Difficulty
pub difficulty: U256,
/// Total difficulty
#[serde(rename="totalDifficulty")]
pub total_difficulty: U256,
/// Seal fields
#[serde(rename="sealFields")]
pub seal_fields: Vec<Bytes>,
/// Uncles' hashes
pub uncles: Vec<H256>,
/// Transactions
pub transactions: BlockTransactions
}

View File

@ -21,9 +21,13 @@ use ethcore::client::BlockID;
/// Represents rpc api block number param.
#[derive(Debug, PartialEq, Clone)]
pub enum BlockNumber {
/// Number
Num(u64),
/// Latest block
Latest,
/// Earliest block (genesis)
Earliest,
/// Pending block (being mined)
Pending
}

View File

@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Serializable wrapper around vector of bytes
use rustc_serialize::hex::ToHex;
use serde::{Serialize, Serializer, Deserialize, Deserializer, Error};
use serde::de::Visitor;
@ -28,7 +30,10 @@ impl Bytes {
pub fn new(bytes: Vec<u8>) -> Bytes {
Bytes(bytes)
}
pub fn to_vec(self) -> Vec<u8> { self.0 }
/// Convert back to vector
pub fn to_vec(self) -> Vec<u8> {
self.0
}
}
impl Serialize for Bytes {
@ -80,4 +85,3 @@ mod tests {
}
}

View File

@ -18,15 +18,23 @@ use util::hash::Address;
use util::numbers::U256;
use v1::types::Bytes;
/// Call request
#[derive(Debug, Default, PartialEq, Deserialize)]
pub struct CallRequest {
/// From
pub from: Option<Address>,
/// To
pub to: Option<Address>,
/// Gas Price
#[serde(rename="gasPrice")]
pub gas_price: Option<U256>,
/// Gas
pub gas: Option<U256>,
/// Value
pub value: Option<U256>,
/// Data
pub data: Option<Bytes>,
/// Nonce
pub nonce: Option<U256>,
}

View File

@ -22,10 +22,14 @@ use v1::types::BlockNumber;
use ethcore::filter::Filter as EthFilter;
use ethcore::client::BlockID;
/// Variadic value
#[derive(Debug, PartialEq, Clone)]
pub enum VariadicValue<T> where T: Deserialize {
/// Single
Single(T),
/// List
Multiple(Vec<T>),
/// None
Null,
}
@ -44,17 +48,24 @@ impl<T> Deserialize for VariadicValue<T> where T: Deserialize {
}
}
/// Filter Address
pub type FilterAddress = VariadicValue<Address>;
/// Topic
pub type Topic = VariadicValue<H256>;
/// Filter
#[derive(Debug, PartialEq, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Filter {
/// From Block
#[serde(rename="fromBlock")]
pub from_block: Option<BlockNumber>,
/// To Block
#[serde(rename="toBlock")]
pub to_block: Option<BlockNumber>,
/// Address
pub address: Option<FilterAddress>,
/// Topics
pub topics: Option<Vec<Topic>>,
}

View File

@ -22,6 +22,7 @@ use serde::de::Visitor;
pub struct Index(usize);
impl Index {
/// Convert to usize
pub fn value(&self) -> usize {
self.0
}

View File

@ -18,21 +18,31 @@ use util::numbers::*;
use ethcore::log_entry::{LocalizedLogEntry, LogEntry};
use v1::types::Bytes;
/// Log
#[derive(Debug, Serialize, PartialEq, Eq, Hash, Clone)]
pub struct Log {
/// Address
pub address: Address,
/// Topics
pub topics: Vec<H256>,
/// Data
pub data: Bytes,
/// Block Hash
#[serde(rename="blockHash")]
pub block_hash: Option<H256>,
/// Block Number
#[serde(rename="blockNumber")]
pub block_number: Option<U256>,
/// Transaction Hash
#[serde(rename="transactionHash")]
pub transaction_hash: Option<H256>,
/// Transaction Index
#[serde(rename="transactionIndex")]
pub transaction_index: Option<U256>,
/// Log Index
#[serde(rename="logIndex")]
pub log_index: Option<U256>,
/// Log Type
#[serde(rename="type")]
pub log_type: String,
}

View File

@ -14,6 +14,8 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Structures used in RPC communication
#[cfg(feature = "serde_macros")]
include!("mod.rs.in");

View File

@ -14,9 +14,9 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
mod bytes;
mod block;
mod block_number;
mod bytes;
mod filter;
mod index;
mod log;
@ -29,9 +29,9 @@ mod receipt;
mod trace;
mod trace_filter;
pub use self::bytes::Bytes;
pub use self::block::{Block, BlockTransactions};
pub use self::block_number::BlockNumber;
pub use self::bytes::Bytes;
pub use self::filter::Filter;
pub use self::index::Index;
pub use self::log::Log;

View File

@ -17,9 +17,12 @@
use serde::{Serialize, Serializer};
use serde_json::Value;
/// Optional value
#[derive(Debug)]
pub enum OptionalValue<T> where T: Serialize {
/// Some
Value(T),
/// None
Null
}

View File

@ -19,22 +19,31 @@ use util::hash::{Address, H256};
use v1::types::Log;
use ethcore::receipt::LocalizedReceipt;
/// Receipt
#[derive(Debug, Serialize)]
pub struct Receipt {
/// Transaction Hash
#[serde(rename="transactionHash")]
pub transaction_hash: H256,
/// Transaction index
#[serde(rename="transactionIndex")]
pub transaction_index: U256,
/// Block hash
#[serde(rename="blockHash")]
pub block_hash: H256,
/// Block number
#[serde(rename="blockNumber")]
pub block_number: U256,
/// Cumulative gas used
#[serde(rename="cumulativeGasUsed")]
pub cumulative_gas_used: U256,
/// Gas used
#[serde(rename="gasUsed")]
pub gas_used: U256,
/// Contract address
#[serde(rename="contractAddress")]
pub contract_address: Option<Address>,
/// Logs
pub logs: Vec<Log>,
}

View File

@ -17,19 +17,26 @@
use serde::{Serialize, Serializer};
use util::numbers::*;
/// Sync info
#[derive(Default, Debug, Serialize, PartialEq)]
pub struct SyncInfo {
/// Starting block
#[serde(rename="startingBlock")]
pub starting_block: U256,
/// Current block
#[serde(rename="currentBlock")]
pub current_block: U256,
/// Highest block seen so far
#[serde(rename="highestBlock")]
pub highest_block: U256,
}
/// Sync status
#[derive(Debug, PartialEq)]
pub enum SyncStatus {
/// Info when syncing
Info(SyncInfo),
/// Not syncing
None
}

View File

@ -19,11 +19,16 @@ use ethcore::trace::trace;
use ethcore::trace::LocalizedTrace;
use v1::types::Bytes;
/// Create response
#[derive(Debug, Serialize)]
pub struct Create {
/// Sender
from: Address,
/// Value
value: U256,
/// Gas
gas: U256,
/// Initialization code
init: Bytes,
}
@ -38,12 +43,18 @@ impl From<trace::Create> for Create {
}
}
/// Call response
#[derive(Debug, Serialize)]
pub struct Call {
/// Sender
from: Address,
/// Recipient
to: Address,
/// Transfered Value
value: U256,
/// Gas
gas: U256,
/// Input data
input: Bytes,
}
@ -59,10 +70,13 @@ impl From<trace::Call> for Call {
}
}
/// Action
#[derive(Debug, Serialize)]
pub enum Action {
/// Call
#[serde(rename="call")]
Call(Call),
/// Create
#[serde(rename="create")]
Create(Create),
}
@ -76,10 +90,13 @@ impl From<trace::Action> for Action {
}
}
/// Call Result
#[derive(Debug, Serialize)]
pub struct CallResult {
/// Gas used
#[serde(rename="gasUsed")]
gas_used: U256,
/// Output bytes
output: Bytes,
}
@ -92,11 +109,15 @@ impl From<trace::CallResult> for CallResult {
}
}
/// Craete Result
#[derive(Debug, Serialize)]
pub struct CreateResult {
/// Gas used
#[serde(rename="gasUsed")]
gas_used: U256,
/// Code
code: Bytes,
/// Assigned address
address: Address,
}
@ -110,14 +131,19 @@ impl From<trace::CreateResult> for CreateResult {
}
}
/// Response
#[derive(Debug, Serialize)]
pub enum Res {
/// Call
#[serde(rename="call")]
Call(CallResult),
/// Create
#[serde(rename="create")]
Create(CreateResult),
/// Call failure
#[serde(rename="failedCall")]
FailedCall,
/// Creation failure
#[serde(rename="failedCreate")]
FailedCreate,
}
@ -133,19 +159,28 @@ impl From<trace::Res> for Res {
}
}
/// Trace
#[derive(Debug, Serialize)]
pub struct Trace {
/// Action
action: Action,
/// Result
result: Res,
/// Trace address
#[serde(rename="traceAddress")]
trace_address: Vec<U256>,
/// Subtraces
subtraces: U256,
/// Transaction position
#[serde(rename="transactionPosition")]
transaction_position: U256,
/// Transaction hash
#[serde(rename="transactionHash")]
transaction_hash: H256,
/// Block Number
#[serde(rename="blockNumber")]
block_number: U256,
/// Block Hash
#[serde(rename="blockHash")]
block_hash: H256,
}

View File

@ -21,14 +21,19 @@ use ethcore::client::BlockID;
use ethcore::client;
use super::BlockNumber;
/// Trace filter
#[derive(Debug, PartialEq, Deserialize)]
pub struct TraceFilter {
/// From block
#[serde(rename="fromBlock")]
pub from_block: Option<BlockNumber>,
/// To block
#[serde(rename="toBlock")]
pub to_block: Option<BlockNumber>,
/// From address
#[serde(rename="fromAddress")]
pub from_address: Option<Vec<Address>>,
/// To address
#[serde(rename="toAddress")]
pub to_address: Option<Vec<Address>>,
}

View File

@ -18,22 +18,34 @@ use util::numbers::*;
use ethcore::transaction::{LocalizedTransaction, Action, SignedTransaction};
use v1::types::{Bytes, OptionalValue};
/// Transaction
#[derive(Debug, Default, Serialize)]
pub struct Transaction {
/// Hash
pub hash: H256,
/// Nonce
pub nonce: U256,
/// Block hash
#[serde(rename="blockHash")]
pub block_hash: OptionalValue<H256>,
/// Block number
#[serde(rename="blockNumber")]
pub block_number: OptionalValue<U256>,
/// Transaction Index
#[serde(rename="transactionIndex")]
pub transaction_index: OptionalValue<U256>,
/// Sender
pub from: Address,
/// Recipient
pub to: OptionalValue<Address>,
/// Transfered value
pub value: U256,
/// Gas Price
#[serde(rename="gasPrice")]
pub gas_price: U256,
/// Gas
pub gas: U256,
/// Data
pub input: Bytes
}

View File

@ -14,19 +14,29 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! `TransactionRequest` type
use util::hash::Address;
use util::numbers::U256;
use v1::types::Bytes;
use v1::types::bytes::Bytes;
#[derive(Debug, Default, PartialEq, Deserialize)]
/// Transaction request coming from RPC
#[derive(Debug, Clone, Default, Eq, PartialEq, Hash, Deserialize)]
pub struct TransactionRequest {
/// Sender
pub from: Address,
/// Recipient
pub to: Option<Address>,
/// Gas Price
#[serde(rename="gasPrice")]
pub gas_price: Option<U256>,
/// Gas
pub gas: Option<U256>,
/// Value of transaction in wei
pub value: Option<U256>,
/// Additional data sent with transaction
pub data: Option<Bytes>,
/// Transaction's nonce
pub nonce: Option<U256>,
}
@ -37,7 +47,7 @@ mod tests {
use serde_json;
use util::numbers::{U256};
use util::hash::Address;
use v1::types::Bytes;
use v1::types::bytes::Bytes;
use super::*;
#[test]
@ -126,3 +136,4 @@ mod tests {
});
}
}

View File

@ -9,13 +9,23 @@ build = "build.rs"
[build-dependencies]
rustc_version = "0.1"
serde_codegen = { version = "0.7.0", optional = true }
syntex = "^0.32.0"
[dependencies]
ethcore-util = { path = "../util" }
serde = "0.7.0"
serde_json = "0.7.0"
rustc-serialize = "0.3"
log = "0.3"
env_logger = "0.3"
ws = "0.4.7"
ethcore-util = { path = "../util" }
ethcore-rpc = { path = "../rpc" }
serde_macros = { version = "0.7.0", optional = true }
clippy = { version = "0.0.69", optional = true}
[features]
default = []
default = ["serde_codegen"]
nightly = ["serde_macros"]
dev = ["clippy"]

View File

@ -19,7 +19,34 @@ extern crate rustc_version;
use rustc_version::{version_meta, Channel};
fn main() {
serde::main();
if let Channel::Nightly = version_meta().channel {
println!("cargo:rustc-cfg=nightly");
}
}
#[cfg(not(feature = "serde_macros"))]
mod serde {
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/types/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 serde {
pub fn main() {}
}

View File

@ -17,6 +17,8 @@
#![warn(missing_docs)]
#![cfg_attr(all(nightly, feature="dev"), feature(plugin))]
#![cfg_attr(all(nightly, feature="dev"), plugin(clippy))]
// Generated by serde
#![cfg_attr(all(nightly, feature="dev"), allow(redundant_closure_call))]
//! Signer module
//!
@ -28,12 +30,33 @@
//! and their responsibility is to confirm (or confirm and sign)
//! the transaction for you.
//!
//! ```
//! extern crate ethcore_signer;
//!
//! use ethcore_signer::Server;
//!
//! fn main() {
//! let _server = Server::start("127.0.0.1:8084".parse().unwrap());
//! }
//! ```
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate serde;
extern crate serde_json;
extern crate rustc_serialize;
extern crate ethcore_util as util;
extern crate ethcore_rpc as rpc;
extern crate ws;
mod signing_queue;
mod ws_server;
pub use ws_server::*;
#[cfg(test)]
mod tests {
#[test]

View File

@ -0,0 +1,74 @@
// 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 <http://www.gnu.org/licenses/>.
use std::collections::HashSet;
use rpc::v1::types::TransactionRequest;
pub trait SigningQueue {
fn add_request(&mut self, transaction: TransactionRequest);
fn remove_request(&mut self, id: TransactionRequest);
fn requests(&self) -> &HashSet<TransactionRequest>;
}
impl SigningQueue for HashSet<TransactionRequest> {
fn add_request(&mut self, transaction: TransactionRequest) {
self.insert(transaction);
}
fn remove_request(&mut self, id: TransactionRequest) {
self.remove(&id);
}
fn requests(&self) -> &HashSet<TransactionRequest> {
self
}
}
#[cfg(test)]
mod test {
use std::collections::HashSet;
use util::hash::Address;
use util::numbers::U256;
use rpc::v1::types::TransactionRequest;
use super::*;
#[test]
fn should_work_for_hashset() {
// given
let mut queue = HashSet::new();
let request = TransactionRequest {
from: Address::from(1),
to: Some(Address::from(2)),
gas_price: None,
gas: None,
value: Some(U256::from(10_000_000)),
data: None,
nonce: None,
};
// when
queue.add_request(request.clone());
let all = queue.requests();
// then
assert_eq!(all.len(), 1);
assert!(all.contains(&request));
}
}

23
signer/src/types/mod.rs Normal file
View File

@ -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 <http://www.gnu.org/licenses/>.
//! Reusable types with JSON Serialization.
#[cfg(feature = "serde_macros")]
include!("mod.rs.in");
#[cfg(not(feature = "serde_macros"))]
include!(concat!(env!("OUT_DIR"), "/mod.rs"));

View File

@ -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 <http://www.gnu.org/licenses/>.
// TODO [ToDr] Types are empty for now. But they are about to come.

128
signer/src/ws_server.rs Normal file
View File

@ -0,0 +1,128 @@
// 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 <http://www.gnu.org/licenses/>.
//! `WebSockets` server.
use ws;
use std;
use std::thread;
use std::ops::Drop;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::net::SocketAddr;
use util::panics::{PanicHandler, OnPanicListener, MayPanic};
/// Signer startup error
#[derive(Debug)]
pub enum ServerError {
/// Wrapped `std::io::Error`
IoError(std::io::Error),
/// Other `ws-rs` error
WebSocket(ws::Error)
}
impl From<ws::Error> for ServerError {
fn from(err: ws::Error) -> Self {
match err.kind {
ws::ErrorKind::Io(e) => ServerError::IoError(e),
_ => ServerError::WebSocket(err),
}
}
}
/// `WebSockets` server implementation.
pub struct Server {
handle: Option<thread::JoinHandle<ws::WebSocket<Factory>>>,
broadcaster: ws::Sender,
panic_handler: Arc<PanicHandler>,
}
impl Server {
/// Starts a new `WebSocket` server in separate thread.
/// Returns a `Server` handle which closes the server when droped.
pub fn start(addr: SocketAddr) -> Result<Server, ServerError> {
let config = {
let mut config = ws::Settings::default();
config.max_connections = 5;
config.method_strict = true;
config
};
// Create WebSocket
let session_id = Arc::new(AtomicUsize::new(1));
let ws = try!(ws::Builder::new().with_settings(config).build(Factory {
session_id: session_id,
}));
let panic_handler = PanicHandler::new_in_arc();
let ph = panic_handler.clone();
let broadcaster = ws.broadcaster();
// Spawn a thread with event loop
let handle = thread::spawn(move || {
ph.catch_panic(move || {
ws.listen(addr).unwrap()
}).unwrap()
});
// Return a handle
Ok(Server {
handle: Some(handle),
broadcaster: broadcaster,
panic_handler: panic_handler,
})
}
}
impl MayPanic for Server {
fn on_panic<F>(&self, closure: F) where F: OnPanicListener {
self.panic_handler.on_panic(closure);
}
}
impl Drop for Server {
fn drop(&mut self) {
self.broadcaster.shutdown().expect("WsServer should close nicely.");
self.handle.take().unwrap().join().unwrap();
}
}
struct Session {
id: usize,
out: ws::Sender,
}
impl ws::Handler for Session {
fn on_open(&mut self, _shake: ws::Handshake) -> ws::Result<()> {
try!(self.out.send(format!("Hello client no: {}. We are not implemented yet.", self.id)));
try!(self.out.close(ws::CloseCode::Normal));
Ok(())
}
}
struct Factory {
session_id: Arc<AtomicUsize>,
}
impl ws::Factory for Factory {
type Handler = Session;
fn connection_made(&mut self, sender: ws::Sender) -> Self::Handler {
Session {
id: self.session_id.fetch_add(1, Ordering::SeqCst),
out: sender,
}
}
}

View File

@ -38,13 +38,10 @@ lazy_static! {
impl Signature {
/// Create a new signature from the R, S and V componenets.
pub fn from_rsv(r: &H256, s: &H256, v: u8) -> Signature {
use std::ptr;
let mut ret: Signature = Signature::new();
unsafe {
let retslice: &mut [u8] = &mut ret;
ptr::copy(r.as_ptr(), retslice.as_mut_ptr(), 32);
ptr::copy(s.as_ptr(), retslice.as_mut_ptr().offset(32), 32);
}
(&mut ret[0..32]).copy_from_slice(r);
(&mut ret[32..64]).copy_from_slice(s);
ret[64] = v;
ret
}
@ -145,7 +142,10 @@ impl KeyPair {
let (sec, publ) = try!(context.generate_keypair(&mut rng));
let serialized = publ.serialize_vec(context, false);
let p: Public = Public::from_slice(&serialized[1..65]);
let s: Secret = unsafe { ::std::mem::transmute(sec) };
let mut s = Secret::new();
s.copy_from_slice(&sec[0..32]);
Ok(KeyPair {
secret: s,
public: p,
@ -193,12 +193,14 @@ pub mod ec {
/// Returns siganture of message hash.
pub fn sign(secret: &Secret, message: &H256) -> Result<Signature, CryptoError> {
// TODO: allow creation of only low-s signatures.
use secp256k1::*;
use secp256k1::{Message, key};
let context = &crypto::SECP256K1;
// no way to create from raw byte array.
let sec: &key::SecretKey = unsafe { ::std::mem::transmute(secret) };
let s = try!(context.sign_recoverable(&try!(Message::from_slice(&message)), sec));
let (rec_id, data) = s.serialize_compact(context);
let mut signature: crypto::Signature = unsafe { ::std::mem::uninitialized() };
let mut signature = crypto::Signature::new();
signature.clone_from_slice(&data);
signature[64] = rec_id.to_i32() as u8;
@ -217,10 +219,12 @@ pub mod ec {
let rsig = try!(RecoverableSignature::from_compact(context, &signature[0..64], try!(RecoveryId::from_i32(signature[64] as i32))));
let sig = rsig.to_standard(context);
let mut pdata: [u8; 65] = [4u8; 65];
let ptr = pdata[1..].as_mut_ptr();
let src = public.as_ptr();
unsafe { ::std::ptr::copy_nonoverlapping(src, ptr, 64) };
let pdata: [u8; 65] = {
let mut temp = [4u8; 65];
(&mut temp[1..65]).copy_from_slice(public);
temp
};
let publ = try!(key::PublicKey::from_slice(context, &pdata));
match context.verify(&try!(Message::from_slice(&message)), &sig, &publ) {
Ok(_) => Ok(true),
@ -252,21 +256,27 @@ pub mod ec {
/// ECDH functions
#[cfg_attr(feature="dev", allow(similar_names))]
pub mod ecdh {
use crypto::*;
use crypto::{self};
use hash::FixedHash;
use crypto::{self, Secret, Public, CryptoError};
/// Agree on a shared secret
pub fn agree(secret: &Secret, public: &Public, ) -> Result<Secret, CryptoError> {
use secp256k1::*;
pub fn agree(secret: &Secret, public: &Public) -> Result<Secret, CryptoError> {
use secp256k1::{ecdh, key};
let context = &crypto::SECP256K1;
let mut pdata: [u8; 65] = [4u8; 65];
let ptr = pdata[1..].as_mut_ptr();
let src = public.as_ptr();
unsafe { ::std::ptr::copy_nonoverlapping(src, ptr, 64) };
let pdata = {
let mut temp = [4u8; 65];
(&mut temp[1..65]).copy_from_slice(&public[0..64]);
temp
};
let publ = try!(key::PublicKey::from_slice(context, &pdata));
// no way to create SecretKey from raw byte array.
let sec: &key::SecretKey = unsafe { ::std::mem::transmute(secret) };
let shared = ecdh::SharedSecret::new_raw(context, &publ, &sec);
let s: Secret = unsafe { ::std::mem::transmute(shared) };
let mut s = crypto::Secret::new();
s.copy_from_slice(&shared[0..32]);
Ok(s)
}
}

View File

@ -75,6 +75,7 @@ pub fn clean_0x(s: &str) -> &str {
macro_rules! impl_hash {
($from: ident, $size: expr) => {
#[derive(Eq)]
#[repr(C)]
/// Unformatted binary data of fixed length.
pub struct $from (pub [u8; $size]);

View File

@ -21,4 +21,5 @@ pub mod store;
mod geth_import;
mod test_account_provider;
pub use self::store::AccountProvider;
pub use self::test_account_provider::{TestAccount, TestAccountProvider};