Dapps port RPC (#2819)

This commit is contained in:
Tomasz Drwięga 2016-10-24 12:21:15 +02:00 committed by Gav Wood
parent 8cf9934cab
commit e5f86c62ad
13 changed files with 223 additions and 223 deletions

View File

@ -58,7 +58,7 @@ pub fn new(configuration: Configuration, deps: Dependencies) -> Result<Option<We
return Ok(None); return Ok(None);
} }
let signer_port = deps.apis.signer_port.clone(); let signer_port = deps.apis.signer_service.port();
let url = format!("{}:{}", configuration.interface, configuration.port); let url = format!("{}:{}", configuration.interface, configuration.port);
let addr = try!(url.parse().map_err(|_| format!("Invalid Webapps listen host/port given: {}", url))); let addr = try!(url.parse().map_err(|_| format!("Invalid Webapps listen host/port given: {}", url)));

View File

@ -93,7 +93,6 @@ impl FromStr for ApiSet {
} }
pub struct Dependencies { pub struct Dependencies {
pub signer_port: Option<u16>,
pub signer_service: Arc<SignerService>, pub signer_service: Arc<SignerService>,
pub client: Arc<Client>, pub client: Arc<Client>,
pub sync: Arc<SyncProvider>, pub sync: Arc<SyncProvider>,
@ -105,6 +104,7 @@ pub struct Dependencies {
pub settings: Arc<NetworkSettings>, pub settings: Arc<NetworkSettings>,
pub net_service: Arc<ManageNetwork>, pub net_service: Arc<ManageNetwork>,
pub geth_compatibility: bool, pub geth_compatibility: bool,
pub dapps_port: Option<u16>,
} }
fn to_modules(apis: &[Api]) -> BTreeMap<String, String> { fn to_modules(apis: &[Api]) -> BTreeMap<String, String> {
@ -172,21 +172,33 @@ pub fn setup_rpc<T: Extendable>(server: T, deps: Arc<Dependencies>, apis: ApiSet
let filter_client = EthFilterClient::new(&deps.client, &deps.miner); let filter_client = EthFilterClient::new(&deps.client, &deps.miner);
server.add_delegate(filter_client.to_delegate()); server.add_delegate(filter_client.to_delegate());
if deps.signer_port.is_some() { if deps.signer_service.is_enabled() {
server.add_delegate(EthSigningQueueClient::new(&deps.signer_service, &deps.client, &deps.miner, &deps.secret_store).to_delegate()); server.add_delegate(EthSigningQueueClient::new(&deps.signer_service, &deps.client, &deps.miner, &deps.secret_store).to_delegate());
} else { } else {
server.add_delegate(EthSigningUnsafeClient::new(&deps.client, &deps.secret_store, &deps.miner).to_delegate()); server.add_delegate(EthSigningUnsafeClient::new(&deps.client, &deps.secret_store, &deps.miner).to_delegate());
} }
}, },
Api::Personal => { Api::Personal => {
server.add_delegate(PersonalClient::new(&deps.secret_store, &deps.client, &deps.miner, deps.signer_port, deps.geth_compatibility).to_delegate()); server.add_delegate(PersonalClient::new(&deps.secret_store, &deps.client, &deps.miner, deps.geth_compatibility).to_delegate());
}, },
Api::Signer => { Api::Signer => {
server.add_delegate(SignerClient::new(&deps.secret_store, &deps.client, &deps.miner, &deps.signer_service).to_delegate()); server.add_delegate(SignerClient::new(&deps.secret_store, &deps.client, &deps.miner, &deps.signer_service).to_delegate());
}, },
Api::Ethcore => { Api::Ethcore => {
let signer = deps.signer_port.map(|_| deps.signer_service.clone()); let signer = match deps.signer_service.is_enabled() {
server.add_delegate(EthcoreClient::new(&deps.client, &deps.miner, &deps.sync, &deps.net_service, deps.logger.clone(), deps.settings.clone(), signer).to_delegate()) true => Some(deps.signer_service.clone()),
false => None,
};
server.add_delegate(EthcoreClient::new(
&deps.client,
&deps.miner,
&deps.sync,
&deps.net_service,
deps.logger.clone(),
deps.settings.clone(),
signer,
deps.dapps_port,
).to_delegate())
}, },
Api::EthcoreSet => { Api::EthcoreSet => {
server.add_delegate(EthcoreSetClient::new(&deps.client, &deps.miner, &deps.net_service).to_delegate()) server.add_delegate(EthcoreSetClient::new(&deps.client, &deps.miner, &deps.net_service).to_delegate())

View File

@ -246,10 +246,9 @@ pub fn execute(cmd: RunCmd) -> Result<(), String> {
// set up dependencies for rpc servers // set up dependencies for rpc servers
let signer_path = cmd.signer_conf.signer_path.clone(); let signer_path = cmd.signer_conf.signer_path.clone();
let deps_for_rpc_apis = Arc::new(rpc_apis::Dependencies { let deps_for_rpc_apis = Arc::new(rpc_apis::Dependencies {
signer_port: cmd.signer_port,
signer_service: Arc::new(rpc_apis::SignerService::new(move || { signer_service: Arc::new(rpc_apis::SignerService::new(move || {
signer::generate_new_token(signer_path.clone()).map_err(|e| format!("{:?}", e)) signer::generate_new_token(signer_path.clone()).map_err(|e| format!("{:?}", e))
})), }, cmd.signer_port)),
client: client.clone(), client: client.clone(),
sync: sync_provider.clone(), sync: sync_provider.clone(),
net: manage_network.clone(), net: manage_network.clone(),
@ -260,6 +259,10 @@ pub fn execute(cmd: RunCmd) -> Result<(), String> {
settings: Arc::new(cmd.net_settings.clone()), settings: Arc::new(cmd.net_settings.clone()),
net_service: manage_network.clone(), net_service: manage_network.clone(),
geth_compatibility: cmd.geth_compatibility, geth_compatibility: cmd.geth_compatibility,
dapps_port: match cmd.dapps_conf.enabled {
true => Some(cmd.dapps_conf.port),
false => None,
},
}); });
let dependencies = rpc::Dependencies { let dependencies = rpc::Dependencies {

View File

@ -39,6 +39,7 @@ mod codes {
pub const PASSWORD_INVALID: i64 = -32021; pub const PASSWORD_INVALID: i64 = -32021;
pub const ACCOUNT_ERROR: i64 = -32023; pub const ACCOUNT_ERROR: i64 = -32023;
pub const SIGNER_DISABLED: i64 = -32030; pub const SIGNER_DISABLED: i64 = -32030;
pub const DAPPS_DISABLED: i64 = -32031;
pub const REQUEST_REJECTED: i64 = -32040; pub const REQUEST_REJECTED: i64 = -32040;
pub const REQUEST_REJECTED_LIMIT: i64 = -32041; pub const REQUEST_REJECTED_LIMIT: i64 = -32041;
pub const REQUEST_NOT_FOUND: i64 = -32042; pub const REQUEST_NOT_FOUND: i64 = -32042;
@ -167,6 +168,14 @@ pub fn signer_disabled() -> Error {
} }
} }
pub fn dapps_disabled() -> Error {
Error {
code: ErrorCode::ServerError(codes::DAPPS_DISABLED),
message: "Dapps Server is disabled. This API is not available.".into(),
data: None
}
}
pub fn encryption_error<T: fmt::Debug>(error: T) -> Error { pub fn encryption_error<T: fmt::Debug>(error: T) -> Error {
Error { Error {
code: ErrorCode::ServerError(codes::ENCRYPTION_ERROR), code: ErrorCode::ServerError(codes::ENCRYPTION_ERROR),

View File

@ -22,16 +22,18 @@ use v1::helpers::signing_queue::{ConfirmationsQueue};
pub struct SignerService { pub struct SignerService {
queue: Arc<ConfirmationsQueue>, queue: Arc<ConfirmationsQueue>,
generate_new_token: Box<Fn() -> Result<String, String> + Send + Sync + 'static>, generate_new_token: Box<Fn() -> Result<String, String> + Send + Sync + 'static>,
port: Option<u16>,
} }
impl SignerService { impl SignerService {
/// Creates new Signer Service given function to generate new tokens. /// Creates new Signer Service given function to generate new tokens.
pub fn new<F>(new_token: F) -> Self pub fn new<F>(new_token: F, port: Option<u16>) -> Self
where F: Fn() -> Result<String, String> + Send + Sync + 'static { where F: Fn() -> Result<String, String> + Send + Sync + 'static {
SignerService { SignerService {
queue: Arc::new(ConfirmationsQueue::default()), queue: Arc::new(ConfirmationsQueue::default()),
generate_new_token: Box::new(new_token), generate_new_token: Box::new(new_token),
port: port,
} }
} }
@ -45,10 +47,20 @@ impl SignerService {
self.queue.clone() self.queue.clone()
} }
/// Returns signer port (if signer enabled) or `None` otherwise
pub fn port(&self) -> Option<u16> {
self.port
}
/// Returns true if Signer is enabled.
pub fn is_enabled(&self) -> bool {
self.port.is_some()
}
#[cfg(test)] #[cfg(test)]
/// Creates new Signer Service for tests. /// Creates new Signer Service for tests.
pub fn new_test() -> Self { pub fn new_test(port: Option<u16>) -> Self {
SignerService::new(|| Ok("new_token".into())) SignerService::new(|| Ok("new_token".into()), port)
} }
} }

View File

@ -52,7 +52,8 @@ pub struct EthcoreClient<C, M, S: ?Sized, F=FetchClient> where
logger: Arc<RotatingLogger>, logger: Arc<RotatingLogger>,
settings: Arc<NetworkSettings>, settings: Arc<NetworkSettings>,
signer: Option<Arc<SignerService>>, signer: Option<Arc<SignerService>>,
fetch: Mutex<F> fetch: Mutex<F>,
dapps_port: Option<u16>,
} }
impl<C, M, S: ?Sized> EthcoreClient<C, M, S> where impl<C, M, S: ?Sized> EthcoreClient<C, M, S> where
@ -67,9 +68,10 @@ impl<C, M, S: ?Sized> EthcoreClient<C, M, S> where
net: &Arc<ManageNetwork>, net: &Arc<ManageNetwork>,
logger: Arc<RotatingLogger>, logger: Arc<RotatingLogger>,
settings: Arc<NetworkSettings>, settings: Arc<NetworkSettings>,
signer: Option<Arc<SignerService>> signer: Option<Arc<SignerService>>,
dapps_port: Option<u16>,
) -> Self { ) -> Self {
Self::with_fetch(client, miner, sync, net, logger, settings, signer) Self::with_fetch(client, miner, sync, net, logger, settings, signer, dapps_port)
} }
} }
@ -87,7 +89,8 @@ impl<C, M, S: ?Sized, F> EthcoreClient<C, M, S, F> where
net: &Arc<ManageNetwork>, net: &Arc<ManageNetwork>,
logger: Arc<RotatingLogger>, logger: Arc<RotatingLogger>,
settings: Arc<NetworkSettings>, settings: Arc<NetworkSettings>,
signer: Option<Arc<SignerService>> signer: Option<Arc<SignerService>>,
dapps_port: Option<u16>,
) -> Self { ) -> Self {
EthcoreClient { EthcoreClient {
client: Arc::downgrade(client), client: Arc::downgrade(client),
@ -98,6 +101,7 @@ impl<C, M, S: ?Sized, F> EthcoreClient<C, M, S, F> where
settings: settings, settings: settings,
signer: signer, signer: signer,
fetch: Mutex::new(F::default()), fetch: Mutex::new(F::default()),
dapps_port: dapps_port,
} }
} }
@ -314,4 +318,20 @@ impl<C, M, S: ?Sized, F> Ethcore for EthcoreClient<C, M, S, F> where
} }
} }
} }
fn signer_port(&self) -> Result<u16, Error> {
try!(self.active());
self.signer
.clone()
.and_then(|signer| signer.port())
.ok_or_else(|| errors::signer_disabled())
}
fn dapps_port(&self) -> Result<u16, Error> {
try!(self.active());
self.dapps_port
.ok_or_else(|| errors::dapps_disabled())
}
} }

View File

@ -34,18 +34,16 @@ pub struct PersonalClient<C, M> where C: MiningBlockChainClient, M: MinerService
accounts: Weak<AccountProvider>, accounts: Weak<AccountProvider>,
client: Weak<C>, client: Weak<C>,
miner: Weak<M>, miner: Weak<M>,
signer_port: Option<u16>,
allow_perm_unlock: bool, allow_perm_unlock: bool,
} }
impl<C, M> PersonalClient<C, M> where C: MiningBlockChainClient, M: MinerService { impl<C, M> PersonalClient<C, M> where C: MiningBlockChainClient, M: MinerService {
/// Creates new PersonalClient /// Creates new PersonalClient
pub fn new(store: &Arc<AccountProvider>, client: &Arc<C>, miner: &Arc<M>, signer_port: Option<u16>, allow_perm_unlock: bool) -> Self { pub fn new(store: &Arc<AccountProvider>, client: &Arc<C>, miner: &Arc<M>, allow_perm_unlock: bool) -> Self {
PersonalClient { PersonalClient {
accounts: Arc::downgrade(store), accounts: Arc::downgrade(store),
client: Arc::downgrade(client), client: Arc::downgrade(client),
miner: Arc::downgrade(miner), miner: Arc::downgrade(miner),
signer_port: signer_port,
allow_perm_unlock: allow_perm_unlock, allow_perm_unlock: allow_perm_unlock,
} }
} }
@ -59,15 +57,6 @@ impl<C, M> PersonalClient<C, M> where C: MiningBlockChainClient, M: MinerService
impl<C: 'static, M: 'static> Personal for PersonalClient<C, M> where C: MiningBlockChainClient, M: MinerService { impl<C: 'static, M: 'static> Personal for PersonalClient<C, M> where C: MiningBlockChainClient, M: MinerService {
fn signer_enabled(&self, params: Params) -> Result<Value, Error> {
try!(self.active());
try!(expect_no_params(params));
Ok(self.signer_port
.map(|v| to_value(&v))
.unwrap_or_else(|| to_value(&false)))
}
fn accounts(&self, params: Params) -> Result<Value, Error> { fn accounts(&self, params: Params) -> Result<Value, Error> {
try!(self.active()); try!(self.active());
try!(expect_no_params(params)); try!(expect_no_params(params));

View File

@ -41,7 +41,7 @@ struct EthSigningTester {
impl Default for EthSigningTester { impl Default for EthSigningTester {
fn default() -> Self { fn default() -> Self {
let signer = Arc::new(SignerService::new_test()); let signer = Arc::new(SignerService::new_test(None));
let client = Arc::new(TestBlockChainClient::default()); let client = Arc::new(TestBlockChainClient::default());
let miner = Arc::new(TestMinerService::default()); let miner = Arc::new(TestMinerService::default());
let accounts = Arc::new(AccountProvider::transient_provider()); let accounts = Arc::new(AccountProvider::transient_provider());
@ -272,10 +272,8 @@ fn should_dispatch_transaction_if_account_is_unlock() {
fn should_decrypt_message_if_account_is_unlocked() { fn should_decrypt_message_if_account_is_unlocked() {
// given // given
let tester = eth_signing(); let tester = eth_signing();
let sync = ethcore::sync_provider(); let ethcore = ethcore::Dependencies::new();
let net = ethcore::network_service(); tester.io.add_delegate(ethcore.client(None).to_delegate());
let ethcore_client = ethcore::ethcore_client(&tester.client, &tester.miner, &sync, &net);
tester.io.add_delegate(ethcore_client.to_delegate());
let (address, public) = tester.accounts.new_account_and_public("test").unwrap(); let (address, public) = tester.accounts.new_account_and_public("test").unwrap();
tester.accounts.unlock_account_permanently(address, "test".into()).unwrap(); tester.accounts.unlock_account_permanently(address, "test".into()).unwrap();

View File

@ -27,59 +27,72 @@ use v1::helpers::{SignerService, NetworkSettings};
use v1::tests::helpers::{TestSyncProvider, Config, TestMinerService, TestFetch}; use v1::tests::helpers::{TestSyncProvider, Config, TestMinerService, TestFetch};
use super::manage_network::TestManageNetwork; use super::manage_network::TestManageNetwork;
fn miner_service() -> Arc<TestMinerService> {
Arc::new(TestMinerService::default())
}
fn client_service() -> Arc<TestBlockChainClient> {
Arc::new(TestBlockChainClient::default())
}
pub fn sync_provider() -> Arc<TestSyncProvider> {
Arc::new(TestSyncProvider::new(Config {
network_id: U256::from(3),
num_peers: 120,
}))
}
fn logger() -> Arc<RotatingLogger> {
Arc::new(RotatingLogger::new("rpc=trace".to_owned()))
}
fn settings() -> Arc<NetworkSettings> {
Arc::new(NetworkSettings {
name: "mynode".to_owned(),
chain: "testchain".to_owned(),
network_port: 30303,
rpc_enabled: true,
rpc_interface: "all".to_owned(),
rpc_port: 8545,
})
}
pub fn network_service() -> Arc<ManageNetwork> {
Arc::new(TestManageNetwork)
}
pub type TestEthcoreClient = EthcoreClient<TestBlockChainClient, TestMinerService, TestSyncProvider, TestFetch>; pub type TestEthcoreClient = EthcoreClient<TestBlockChainClient, TestMinerService, TestSyncProvider, TestFetch>;
pub fn ethcore_client( pub struct Dependencies {
client: &Arc<TestBlockChainClient>, pub miner: Arc<TestMinerService>,
miner: &Arc<TestMinerService>, pub client: Arc<TestBlockChainClient>,
sync: &Arc<TestSyncProvider>, pub sync: Arc<TestSyncProvider>,
net: &Arc<ManageNetwork>) pub logger: Arc<RotatingLogger>,
-> TestEthcoreClient { pub settings: Arc<NetworkSettings>,
EthcoreClient::with_fetch(client, miner, sync, net, logger(), settings(), None) pub network: Arc<ManageNetwork>,
pub dapps_port: Option<u16>,
}
impl Dependencies {
pub fn new() -> Self {
Dependencies {
miner: Arc::new(TestMinerService::default()),
client: Arc::new(TestBlockChainClient::default()),
sync: Arc::new(TestSyncProvider::new(Config {
network_id: U256::from(3),
num_peers: 120,
})),
logger: Arc::new(RotatingLogger::new("rpc=trace".to_owned())),
settings: Arc::new(NetworkSettings {
name: "mynode".to_owned(),
chain: "testchain".to_owned(),
network_port: 30303,
rpc_enabled: true,
rpc_interface: "all".to_owned(),
rpc_port: 8545,
}),
network: Arc::new(TestManageNetwork),
dapps_port: Some(18080),
}
}
pub fn client(&self, signer: Option<Arc<SignerService>>) -> TestEthcoreClient {
EthcoreClient::with_fetch(
&self.client,
&self.miner,
&self.sync,
&self.network,
self.logger.clone(),
self.settings.clone(),
signer,
self.dapps_port,
)
}
fn default_client(&self) -> IoHandler {
let io = IoHandler::new();
io.add_delegate(self.client(None).to_delegate());
io
}
fn with_signer(&self, signer: SignerService) -> IoHandler {
let io = IoHandler::new();
io.add_delegate(self.client(Some(Arc::new(signer))).to_delegate());
io
}
} }
#[test] #[test]
fn rpc_ethcore_extra_data() { fn rpc_ethcore_extra_data() {
let miner = miner_service(); let deps = Dependencies::new();
let client = client_service(); let io = deps.default_client();
let sync = sync_provider();
let net = network_service();
let io = IoHandler::new();
io.add_delegate(ethcore_client(&client, &miner, &sync, &net).to_delegate());
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_extraData", "params": [], "id": 1}"#; let request = r#"{"jsonrpc": "2.0", "method": "ethcore_extraData", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"0x01020304","id":1}"#; let response = r#"{"jsonrpc":"2.0","result":"0x01020304","id":1}"#;
@ -92,12 +105,8 @@ fn rpc_ethcore_default_extra_data() {
use util::misc; use util::misc;
use util::ToPretty; use util::ToPretty;
let miner = miner_service(); let deps = Dependencies::new();
let client = client_service(); let io = deps.default_client();
let sync = sync_provider();
let net = network_service();
let io = IoHandler::new();
io.add_delegate(ethcore_client(&client, &miner, &sync, &net).to_delegate());
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_defaultExtraData", "params": [], "id": 1}"#; let request = r#"{"jsonrpc": "2.0", "method": "ethcore_defaultExtraData", "params": [], "id": 1}"#;
let response = format!(r#"{{"jsonrpc":"2.0","result":"0x{}","id":1}}"#, misc::version_data().to_hex()); let response = format!(r#"{{"jsonrpc":"2.0","result":"0x{}","id":1}}"#, misc::version_data().to_hex());
@ -107,12 +116,8 @@ fn rpc_ethcore_default_extra_data() {
#[test] #[test]
fn rpc_ethcore_gas_floor_target() { fn rpc_ethcore_gas_floor_target() {
let miner = miner_service(); let deps = Dependencies::new();
let client = client_service(); let io = deps.default_client();
let sync = sync_provider();
let net = network_service();
let io = IoHandler::new();
io.add_delegate(ethcore_client(&client, &miner, &sync, &net).to_delegate());
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_gasFloorTarget", "params": [], "id": 1}"#; let request = r#"{"jsonrpc": "2.0", "method": "ethcore_gasFloorTarget", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"0x3039","id":1}"#; let response = r#"{"jsonrpc":"2.0","result":"0x3039","id":1}"#;
@ -122,12 +127,8 @@ fn rpc_ethcore_gas_floor_target() {
#[test] #[test]
fn rpc_ethcore_min_gas_price() { fn rpc_ethcore_min_gas_price() {
let miner = miner_service(); let deps = Dependencies::new();
let client = client_service(); let io = deps.default_client();
let sync = sync_provider();
let net = network_service();
let io = IoHandler::new();
io.add_delegate(ethcore_client(&client, &miner, &sync, &net).to_delegate());
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_minGasPrice", "params": [], "id": 1}"#; let request = r#"{"jsonrpc": "2.0", "method": "ethcore_minGasPrice", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"0x1312d00","id":1}"#; let response = r#"{"jsonrpc":"2.0","result":"0x1312d00","id":1}"#;
@ -137,16 +138,11 @@ fn rpc_ethcore_min_gas_price() {
#[test] #[test]
fn rpc_ethcore_dev_logs() { fn rpc_ethcore_dev_logs() {
let miner = miner_service(); let deps = Dependencies::new();
let client = client_service(); deps.logger.append("a".to_owned());
let sync = sync_provider(); deps.logger.append("b".to_owned());
let net = network_service();
let logger = logger(); let io = deps.default_client();
logger.append("a".to_owned());
logger.append("b".to_owned());
let ethcore: TestEthcoreClient = EthcoreClient::with_fetch(&client, &miner, &sync, &net, logger.clone(), settings(), None);
let io = IoHandler::new();
io.add_delegate(ethcore.to_delegate());
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_devLogs", "params":[], "id": 1}"#; let request = r#"{"jsonrpc": "2.0", "method": "ethcore_devLogs", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":["b","a"],"id":1}"#; let response = r#"{"jsonrpc":"2.0","result":["b","a"],"id":1}"#;
@ -156,12 +152,8 @@ fn rpc_ethcore_dev_logs() {
#[test] #[test]
fn rpc_ethcore_dev_logs_levels() { fn rpc_ethcore_dev_logs_levels() {
let miner = miner_service(); let deps = Dependencies::new();
let client = client_service(); let io = deps.default_client();
let sync = sync_provider();
let net = network_service();
let io = IoHandler::new();
io.add_delegate(ethcore_client(&client, &miner, &sync, &net).to_delegate());
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_devLogsLevels", "params":[], "id": 1}"#; let request = r#"{"jsonrpc": "2.0", "method": "ethcore_devLogsLevels", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"rpc=trace","id":1}"#; let response = r#"{"jsonrpc":"2.0","result":"rpc=trace","id":1}"#;
@ -171,12 +163,8 @@ fn rpc_ethcore_dev_logs_levels() {
#[test] #[test]
fn rpc_ethcore_transactions_limit() { fn rpc_ethcore_transactions_limit() {
let miner = miner_service(); let deps = Dependencies::new();
let client = client_service(); let io = deps.default_client();
let sync = sync_provider();
let net = network_service();
let io = IoHandler::new();
io.add_delegate(ethcore_client(&client, &miner, &sync, &net).to_delegate());
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_transactionsLimit", "params":[], "id": 1}"#; let request = r#"{"jsonrpc": "2.0", "method": "ethcore_transactionsLimit", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":1024,"id":1}"#; let response = r#"{"jsonrpc":"2.0","result":1024,"id":1}"#;
@ -186,12 +174,8 @@ fn rpc_ethcore_transactions_limit() {
#[test] #[test]
fn rpc_ethcore_net_chain() { fn rpc_ethcore_net_chain() {
let miner = miner_service(); let deps = Dependencies::new();
let client = client_service(); let io = deps.default_client();
let sync = sync_provider();
let net = network_service();
let io = IoHandler::new();
io.add_delegate(ethcore_client(&client, &miner, &sync, &net).to_delegate());
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_netChain", "params":[], "id": 1}"#; let request = r#"{"jsonrpc": "2.0", "method": "ethcore_netChain", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"testchain","id":1}"#; let response = r#"{"jsonrpc":"2.0","result":"testchain","id":1}"#;
@ -201,12 +185,8 @@ fn rpc_ethcore_net_chain() {
#[test] #[test]
fn rpc_ethcore_net_peers() { fn rpc_ethcore_net_peers() {
let miner = miner_service(); let deps = Dependencies::new();
let client = client_service(); let io = deps.default_client();
let sync = sync_provider();
let net = network_service();
let io = IoHandler::new();
io.add_delegate(ethcore_client(&client, &miner, &sync, &net).to_delegate());
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_netPeers", "params":[], "id": 1}"#; let request = r#"{"jsonrpc": "2.0", "method": "ethcore_netPeers", "params":[], "id": 1}"#;
let response = "{\"jsonrpc\":\"2.0\",\"result\":{\"active\":0,\"connected\":120,\"max\":50,\"peers\":[{\"caps\":[\"eth/62\",\"eth/63\"],\ let response = "{\"jsonrpc\":\"2.0\",\"result\":{\"active\":0,\"connected\":120,\"max\":50,\"peers\":[{\"caps\":[\"eth/62\",\"eth/63\"],\
@ -221,12 +201,8 @@ fn rpc_ethcore_net_peers() {
#[test] #[test]
fn rpc_ethcore_net_port() { fn rpc_ethcore_net_port() {
let miner = miner_service(); let deps = Dependencies::new();
let client = client_service(); let io = deps.default_client();
let sync = sync_provider();
let net = network_service();
let io = IoHandler::new();
io.add_delegate(ethcore_client(&client, &miner, &sync, &net).to_delegate());
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_netPort", "params":[], "id": 1}"#; let request = r#"{"jsonrpc": "2.0", "method": "ethcore_netPort", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":30303,"id":1}"#; let response = r#"{"jsonrpc":"2.0","result":30303,"id":1}"#;
@ -236,12 +212,8 @@ fn rpc_ethcore_net_port() {
#[test] #[test]
fn rpc_ethcore_rpc_settings() { fn rpc_ethcore_rpc_settings() {
let miner = miner_service(); let deps = Dependencies::new();
let client = client_service(); let io = deps.default_client();
let sync = sync_provider();
let net = network_service();
let io = IoHandler::new();
io.add_delegate(ethcore_client(&client, &miner, &sync, &net).to_delegate());
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_rpcSettings", "params":[], "id": 1}"#; let request = r#"{"jsonrpc": "2.0", "method": "ethcore_rpcSettings", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":{"enabled":true,"interface":"all","port":8545},"id":1}"#; let response = r#"{"jsonrpc":"2.0","result":{"enabled":true,"interface":"all","port":8545},"id":1}"#;
@ -251,12 +223,8 @@ fn rpc_ethcore_rpc_settings() {
#[test] #[test]
fn rpc_ethcore_node_name() { fn rpc_ethcore_node_name() {
let miner = miner_service(); let deps = Dependencies::new();
let client = client_service(); let io = deps.default_client();
let sync = sync_provider();
let net = network_service();
let io = IoHandler::new();
io.add_delegate(ethcore_client(&client, &miner, &sync, &net).to_delegate());
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_nodeName", "params":[], "id": 1}"#; let request = r#"{"jsonrpc": "2.0", "method": "ethcore_nodeName", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"mynode","id":1}"#; let response = r#"{"jsonrpc":"2.0","result":"mynode","id":1}"#;
@ -266,14 +234,8 @@ fn rpc_ethcore_node_name() {
#[test] #[test]
fn rpc_ethcore_unsigned_transactions_count() { fn rpc_ethcore_unsigned_transactions_count() {
let miner = miner_service(); let deps = Dependencies::new();
let client = client_service(); let io = deps.with_signer(SignerService::new_test(Some(18180)));
let sync = sync_provider();
let net = network_service();
let io = IoHandler::new();
let signer = Arc::new(SignerService::new_test());
let ethcore: TestEthcoreClient = EthcoreClient::with_fetch(&client, &miner, &sync, &net, logger(), settings(), Some(signer));
io.add_delegate(ethcore.to_delegate());
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_unsignedTransactionsCount", "params":[], "id": 1}"#; let request = r#"{"jsonrpc": "2.0", "method": "ethcore_unsignedTransactionsCount", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":0,"id":1}"#; let response = r#"{"jsonrpc":"2.0","result":0,"id":1}"#;
@ -283,12 +245,8 @@ fn rpc_ethcore_unsigned_transactions_count() {
#[test] #[test]
fn rpc_ethcore_unsigned_transactions_count_when_signer_disabled() { fn rpc_ethcore_unsigned_transactions_count_when_signer_disabled() {
let miner = miner_service(); let deps = Dependencies::new();
let client = client_service(); let io = deps.default_client();
let sync = sync_provider();
let net = network_service();
let io = IoHandler::new();
io.add_delegate(ethcore_client(&client, &miner, &sync, &net).to_delegate());
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_unsignedTransactionsCount", "params":[], "id": 1}"#; let request = r#"{"jsonrpc": "2.0", "method": "ethcore_unsignedTransactionsCount", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","error":{"code":-32030,"message":"Trusted Signer is disabled. This API is not available.","data":null},"id":1}"#; let response = r#"{"jsonrpc":"2.0","error":{"code":-32030,"message":"Trusted Signer is disabled. This API is not available.","data":null},"id":1}"#;
@ -298,12 +256,8 @@ fn rpc_ethcore_unsigned_transactions_count_when_signer_disabled() {
#[test] #[test]
fn rpc_ethcore_hash_content() { fn rpc_ethcore_hash_content() {
let miner = miner_service(); let deps = Dependencies::new();
let client = client_service(); let io = deps.default_client();
let sync = sync_provider();
let net = network_service();
let io = IoHandler::new();
io.add_delegate(ethcore_client(&client, &miner, &sync, &net).to_delegate());
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_hashContent", "params":["https://ethcore.io/assets/images/ethcore-black-horizontal.png"], "id": 1}"#; let request = r#"{"jsonrpc": "2.0", "method": "ethcore_hashContent", "params":["https://ethcore.io/assets/images/ethcore-black-horizontal.png"], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":"0x2be00befcf008bc0e7d9cdefc194db9c75352e8632f48498b5a6bfce9f02c88e","id":1}"#; let response = r#"{"jsonrpc":"2.0","result":"0x2be00befcf008bc0e7d9cdefc194db9c75352e8632f48498b5a6bfce9f02c88e","id":1}"#;
@ -313,12 +267,8 @@ fn rpc_ethcore_hash_content() {
#[test] #[test]
fn rpc_ethcore_pending_transactions() { fn rpc_ethcore_pending_transactions() {
let miner = miner_service(); let deps = Dependencies::new();
let client = client_service(); let io = deps.default_client();
let sync = sync_provider();
let net = network_service();
let io = IoHandler::new();
io.add_delegate(ethcore_client(&client, &miner, &sync, &net).to_delegate());
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_pendingTransactions", "params":[], "id": 1}"#; let request = r#"{"jsonrpc": "2.0", "method": "ethcore_pendingTransactions", "params":[], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":[],"id":1}"#; let response = r#"{"jsonrpc":"2.0","result":[],"id":1}"#;
@ -328,14 +278,45 @@ fn rpc_ethcore_pending_transactions() {
#[test] #[test]
fn rpc_ethcore_encrypt() { fn rpc_ethcore_encrypt() {
let miner = miner_service(); let deps = Dependencies::new();
let client = client_service(); let io = deps.default_client();
let sync = sync_provider();
let net = network_service();
let io = IoHandler::new();
io.add_delegate(ethcore_client(&client, &miner, &sync, &net).to_delegate());
let key = format!("{:?}", Random.generate().unwrap().public()); let key = format!("{:?}", Random.generate().unwrap().public());
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_encryptMessage", "params":["0x"#.to_owned() + &key + r#"", "0x01"], "id": 1}"#; let request = r#"{"jsonrpc": "2.0", "method": "ethcore_encryptMessage", "params":["0x"#.to_owned() + &key + r#"", "0x01"], "id": 1}"#;
assert!(io.handle_request_sync(&request).unwrap().contains("result"), "Should return success."); assert!(io.handle_request_sync(&request).unwrap().contains("result"), "Should return success.");
} }
#[test]
fn rpc_ethcore_signer_port() {
// given
let deps = Dependencies::new();
let io1 = deps.with_signer(SignerService::new_test(Some(18180)));
let io2 = deps.default_client();
// when
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_signerPort", "params": [], "id": 1}"#;
let response1 = r#"{"jsonrpc":"2.0","result":18180,"id":1}"#;
let response2 = r#"{"jsonrpc":"2.0","error":{"code":-32030,"message":"Trusted Signer is disabled. This API is not available.","data":null},"id":1}"#;
// then
assert_eq!(io1.handle_request_sync(request), Some(response1.to_owned()));
assert_eq!(io2.handle_request_sync(request), Some(response2.to_owned()));
}
#[test]
fn rpc_ethcore_dapps_port() {
// given
let mut deps = Dependencies::new();
let io1 = deps.default_client();
deps.dapps_port = None;
let io2 = deps.default_client();
// when
let request = r#"{"jsonrpc": "2.0", "method": "ethcore_dappsPort", "params": [], "id": 1}"#;
let response1 = r#"{"jsonrpc":"2.0","result":18080,"id":1}"#;
let response2 = r#"{"jsonrpc":"2.0","error":{"code":-32031,"message":"Dapps Server is disabled. This API is not available.","data":null},"id":1}"#;
// then
assert_eq!(io1.handle_request_sync(request), Some(response1.to_owned()));
assert_eq!(io2.handle_request_sync(request), Some(response2.to_owned()));
}

View File

@ -46,11 +46,11 @@ fn miner_service() -> Arc<TestMinerService> {
Arc::new(TestMinerService::default()) Arc::new(TestMinerService::default())
} }
fn setup(signer: Option<u16>) -> PersonalTester { fn setup() -> PersonalTester {
let accounts = accounts_provider(); let accounts = accounts_provider();
let client = blockchain_client(); let client = blockchain_client();
let miner = miner_service(); let miner = miner_service();
let personal = PersonalClient::new(&accounts, &client, &miner, signer, false); let personal = PersonalClient::new(&accounts, &client, &miner, false);
let io = IoHandler::new(); let io = IoHandler::new();
io.add_delegate(personal.to_delegate()); io.add_delegate(personal.to_delegate());
@ -65,37 +65,9 @@ fn setup(signer: Option<u16>) -> PersonalTester {
tester tester
} }
#[test]
fn should_return_false_if_signer_is_disabled() {
// given
let tester = setup(None);
// when
let request = r#"{"jsonrpc": "2.0", "method": "personal_signerEnabled", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":false,"id":1}"#;
// then
assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned()));
}
#[test]
fn should_return_port_number_if_signer_is_enabled() {
// given
let tester = setup(Some(8180));
// when
let request = r#"{"jsonrpc": "2.0", "method": "personal_signerEnabled", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":8180,"id":1}"#;
// then
assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned()));
}
#[test] #[test]
fn accounts() { fn accounts() {
let tester = setup(None); let tester = setup();
let address = tester.accounts.new_account("").unwrap(); let address = tester.accounts.new_account("").unwrap();
let request = r#"{"jsonrpc": "2.0", "method": "personal_listAccounts", "params": [], "id": 1}"#; let request = r#"{"jsonrpc": "2.0", "method": "personal_listAccounts", "params": [], "id": 1}"#;
let response = r#"{"jsonrpc":"2.0","result":[""#.to_owned() + &format!("0x{:?}", address) + r#""],"id":1}"#; let response = r#"{"jsonrpc":"2.0","result":[""#.to_owned() + &format!("0x{:?}", address) + r#""],"id":1}"#;
@ -105,7 +77,7 @@ fn accounts() {
#[test] #[test]
fn new_account() { fn new_account() {
let tester = setup(None); let tester = setup();
let request = r#"{"jsonrpc": "2.0", "method": "personal_newAccount", "params": ["pass"], "id": 1}"#; let request = r#"{"jsonrpc": "2.0", "method": "personal_newAccount", "params": ["pass"], "id": 1}"#;
let res = tester.io.handle_request_sync(request); let res = tester.io.handle_request_sync(request);
@ -120,7 +92,7 @@ fn new_account() {
#[test] #[test]
fn should_be_able_to_get_account_info() { fn should_be_able_to_get_account_info() {
let tester = setup(None); let tester = setup();
tester.accounts.new_account("").unwrap(); tester.accounts.new_account("").unwrap();
let accounts = tester.accounts.accounts().unwrap(); let accounts = tester.accounts.accounts().unwrap();
assert_eq!(accounts.len(), 1); assert_eq!(accounts.len(), 1);
@ -138,7 +110,7 @@ fn should_be_able_to_get_account_info() {
#[test] #[test]
fn should_be_able_to_set_name() { fn should_be_able_to_set_name() {
let tester = setup(None); let tester = setup();
tester.accounts.new_account("").unwrap(); tester.accounts.new_account("").unwrap();
let accounts = tester.accounts.accounts().unwrap(); let accounts = tester.accounts.accounts().unwrap();
assert_eq!(accounts.len(), 1); assert_eq!(accounts.len(), 1);
@ -159,7 +131,7 @@ fn should_be_able_to_set_name() {
#[test] #[test]
fn should_be_able_to_set_meta() { fn should_be_able_to_set_meta() {
let tester = setup(None); let tester = setup();
tester.accounts.new_account("").unwrap(); tester.accounts.new_account("").unwrap();
let accounts = tester.accounts.accounts().unwrap(); let accounts = tester.accounts.accounts().unwrap();
assert_eq!(accounts.len(), 1); assert_eq!(accounts.len(), 1);
@ -180,7 +152,7 @@ fn should_be_able_to_set_meta() {
#[test] #[test]
fn sign_and_send_transaction_with_invalid_password() { fn sign_and_send_transaction_with_invalid_password() {
let tester = setup(None); let tester = setup();
let address = tester.accounts.new_account("password123").unwrap(); let address = tester.accounts.new_account("password123").unwrap();
let request = r#"{ let request = r#"{
"jsonrpc": "2.0", "jsonrpc": "2.0",
@ -202,7 +174,7 @@ fn sign_and_send_transaction_with_invalid_password() {
#[test] #[test]
fn sign_and_send_transaction() { fn sign_and_send_transaction() {
let tester = setup(None); let tester = setup();
let address = tester.accounts.new_account("password123").unwrap(); let address = tester.accounts.new_account("password123").unwrap();
let request = r#"{ let request = r#"{

View File

@ -49,7 +49,7 @@ fn miner_service() -> Arc<TestMinerService> {
} }
fn signer_tester() -> PersonalSignerTester { fn signer_tester() -> PersonalSignerTester {
let signer = Arc::new(SignerService::new_test()); let signer = Arc::new(SignerService::new_test(None));
let accounts = accounts_provider(); let accounts = accounts_provider();
let client = blockchain_client(); let client = blockchain_client();
let miner = miner_service(); let miner = miner_service();

View File

@ -117,5 +117,13 @@ build_rpc_trait! {
/// Hash a file content under given URL. /// Hash a file content under given URL.
#[rpc(async, name = "ethcore_hashContent")] #[rpc(async, name = "ethcore_hashContent")]
fn hash_content(&self, Ready<H256>, String); fn hash_content(&self, Ready<H256>, String);
/// Returns current Trusted Signer port or an error if signer is disabled.
#[rpc(name = "ethcore_signerPort")]
fn signer_port(&self) -> Result<u16, Error>;
/// Returns current Dapps Server port or an error if dapps server is disabled.
#[rpc(name = "ethcore_dappsPort")]
fn dapps_port(&self) -> Result<u16, Error>;
} }
} }

View File

@ -50,9 +50,6 @@ pub trait Personal: Sized + Send + Sync + 'static {
/// Sends transaction and signs it in single call. The account is not unlocked in such case. /// Sends transaction and signs it in single call. The account is not unlocked in such case.
fn sign_and_send_transaction(&self, _: Params) -> Result<Value, Error>; fn sign_and_send_transaction(&self, _: Params) -> Result<Value, Error>;
/// Returns `true` if Trusted Signer is enabled, `false` otherwise.
fn signer_enabled(&self, _: Params) -> Result<Value, Error>;
/// Set an account's name. /// Set an account's name.
fn set_account_name(&self, _: Params) -> Result<Value, Error>; fn set_account_name(&self, _: Params) -> Result<Value, Error>;
@ -71,7 +68,6 @@ pub trait Personal: Sized + Send + Sync + 'static {
/// Should be used to convert object to io delegate. /// Should be used to convert object to io delegate.
fn to_delegate(self) -> IoDelegate<Self> { fn to_delegate(self) -> IoDelegate<Self> {
let mut delegate = IoDelegate::new(Arc::new(self)); let mut delegate = IoDelegate::new(Arc::new(self));
delegate.add_method("personal_signerEnabled", Personal::signer_enabled);
delegate.add_method("personal_listAccounts", Personal::accounts); delegate.add_method("personal_listAccounts", Personal::accounts);
delegate.add_method("personal_newAccount", Personal::new_account); delegate.add_method("personal_newAccount", Personal::new_account);
delegate.add_method("personal_newAccountFromPhrase", Personal::new_account_from_phrase); delegate.add_method("personal_newAccountFromPhrase", Personal::new_account_from_phrase);