From f67b25ee500285ef9e7f6c78fdc5f958716af963 Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Thu, 12 Jul 2018 19:27:50 +0800 Subject: [PATCH 1/9] Completely remove all dapps struct from rpc --- rpc/src/lib.rs | 2 +- rpc/src/v1/helpers/dapps.rs | 27 ------------ rpc/src/v1/helpers/errors.rs | 8 ---- rpc/src/v1/helpers/mod.rs | 1 - rpc/src/v1/impls/light/parity.rs | 4 -- rpc/src/v1/impls/light/parity_set.rs | 10 +---- rpc/src/v1/impls/parity.rs | 8 +--- rpc/src/v1/impls/parity_set.rs | 10 +---- rpc/src/v1/mod.rs | 6 --- rpc/src/v1/tests/mocked/parity.rs | 14 ------ rpc/src/v1/tests/mocked/parity_set.rs | 15 ------- rpc/src/v1/traits/parity.rs | 5 --- rpc/src/v1/traits/parity_set.rs | 11 +---- rpc/src/v1/types/dapps.rs | 61 --------------------------- rpc/src/v1/types/mod.rs | 2 - 15 files changed, 6 insertions(+), 178 deletions(-) delete mode 100644 rpc/src/v1/helpers/dapps.rs delete mode 100644 rpc/src/v1/types/dapps.rs diff --git a/rpc/src/lib.rs b/rpc/src/lib.rs index 98d743881ed..bef7d9effb4 100644 --- a/rpc/src/lib.rs +++ b/rpc/src/lib.rs @@ -118,7 +118,7 @@ pub use http::{ AccessControlAllowOrigin, Host, DomainsValidation }; -pub use v1::{NetworkSettings, Metadata, Origin, informant, dispatch, signer, dapps}; +pub use v1::{NetworkSettings, Metadata, Origin, informant, dispatch, signer}; pub use v1::block_import::is_major_importing; pub use v1::extractors::{RpcExtractor, WsExtractor, WsStats, WsDispatcher}; pub use authcodes::{AuthCodes, TimeProvider}; diff --git a/rpc/src/v1/helpers/dapps.rs b/rpc/src/v1/helpers/dapps.rs deleted file mode 100644 index 88a9cce6fbc..00000000000 --- a/rpc/src/v1/helpers/dapps.rs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (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 . - -//! Dapps Service - -use v1::types::LocalDapp; - -/// Dapps Server service. -pub trait DappsService: Send + Sync + 'static { - /// List available local dapps. - fn list_dapps(&self) -> Vec; - /// Refresh local dapps list - fn refresh_local_dapps(&self) -> bool; -} diff --git a/rpc/src/v1/helpers/errors.rs b/rpc/src/v1/helpers/errors.rs index 6207d4542fc..710f7d7497a 100644 --- a/rpc/src/v1/helpers/errors.rs +++ b/rpc/src/v1/helpers/errors.rs @@ -211,14 +211,6 @@ pub fn signer_disabled() -> Error { } } -pub fn dapps_disabled() -> Error { - Error { - code: ErrorCode::ServerError(codes::UNSUPPORTED_REQUEST), - message: "Dapps Server is disabled. This API is not available.".into(), - data: None, - } -} - pub fn ws_disabled() -> Error { Error { code: ErrorCode::ServerError(codes::UNSUPPORTED_REQUEST), diff --git a/rpc/src/v1/helpers/mod.rs b/rpc/src/v1/helpers/mod.rs index 5b62087ab38..ba8356334b3 100644 --- a/rpc/src/v1/helpers/mod.rs +++ b/rpc/src/v1/helpers/mod.rs @@ -18,7 +18,6 @@ pub mod errors; pub mod block_import; -pub mod dapps; pub mod dispatch; pub mod fake_sign; pub mod ipfs; diff --git a/rpc/src/v1/impls/light/parity.rs b/rpc/src/v1/impls/light/parity.rs index f722781111e..f9ec03cd378 100644 --- a/rpc/src/v1/impls/light/parity.rs +++ b/rpc/src/v1/impls/light/parity.rs @@ -326,10 +326,6 @@ impl Parity for ParityClient { Ok(map) } - fn dapps_url(&self) -> Result { - Err(errors::dapps_disabled()) - } - fn ws_url(&self) -> Result { helpers::to_url(&self.ws_address) .ok_or_else(|| errors::ws_disabled()) diff --git a/rpc/src/v1/impls/light/parity_set.rs b/rpc/src/v1/impls/light/parity_set.rs index dfe90a8ac8d..6eadea43ab5 100644 --- a/rpc/src/v1/impls/light/parity_set.rs +++ b/rpc/src/v1/impls/light/parity_set.rs @@ -29,7 +29,7 @@ use jsonrpc_core::{Result, BoxFuture}; use jsonrpc_core::futures::Future; use v1::helpers::errors; use v1::traits::ParitySet; -use v1::types::{Bytes, H160, H256, U256, ReleaseInfo, Transaction, LocalDapp}; +use v1::types::{Bytes, H160, H256, U256, ReleaseInfo, Transaction}; /// Parity-specific rpc interface for operations altering the settings. pub struct ParitySetClient { @@ -137,14 +137,6 @@ impl ParitySet for ParitySetClient { Box::new(self.pool.spawn(future)) } - fn dapps_refresh(&self) -> Result { - Err(errors::dapps_disabled()) - } - - fn dapps_list(&self) -> Result> { - Err(errors::dapps_disabled()) - } - fn upgrade_ready(&self) -> Result> { Err(errors::light_unimplemented(None)) } diff --git a/rpc/src/v1/impls/parity.rs b/rpc/src/v1/impls/parity.rs index ac4bb11525b..93560836f9c 100644 --- a/rpc/src/v1/impls/parity.rs +++ b/rpc/src/v1/impls/parity.rs @@ -139,11 +139,11 @@ impl Parity for ParityClient where .collect() ) } - + fn locked_hardware_accounts_info(&self) -> Result> { self.accounts.locked_hardware_accounts().map_err(|e| errors::account("Error communicating with hardware wallet.", e)) } - + fn default_account(&self, meta: Self::Metadata) -> Result { let dapp_id = meta.dapp_id(); @@ -347,10 +347,6 @@ impl Parity for ParityClient where ) } - fn dapps_url(&self) -> Result { - Err(errors::dapps_disabled()) - } - fn ws_url(&self) -> Result { helpers::to_url(&self.ws_address) .ok_or_else(|| errors::ws_disabled()) diff --git a/rpc/src/v1/impls/parity_set.rs b/rpc/src/v1/impls/parity_set.rs index 82880f7207d..c811b3e5daf 100644 --- a/rpc/src/v1/impls/parity_set.rs +++ b/rpc/src/v1/impls/parity_set.rs @@ -31,7 +31,7 @@ use jsonrpc_core::{BoxFuture, Result}; use jsonrpc_core::futures::Future; use v1::helpers::errors; use v1::traits::ParitySet; -use v1::types::{Bytes, H160, H256, U256, ReleaseInfo, Transaction, LocalDapp}; +use v1::types::{Bytes, H160, H256, U256, ReleaseInfo, Transaction}; /// Parity-specific rpc interface for operations altering the settings. pub struct ParitySetClient { @@ -182,14 +182,6 @@ impl ParitySet for ParitySetClient where Box::new(self.pool.spawn(future)) } - fn dapps_refresh(&self) -> Result { - Err(errors::dapps_disabled()) - } - - fn dapps_list(&self) -> Result> { - Err(errors::dapps_disabled()) - } - fn upgrade_ready(&self) -> Result> { Ok(self.updater.upgrade_ready().map(Into::into)) } diff --git a/rpc/src/v1/mod.rs b/rpc/src/v1/mod.rs index cb510ae2941..a0b74aa5aa4 100644 --- a/rpc/src/v1/mod.rs +++ b/rpc/src/v1/mod.rs @@ -53,9 +53,3 @@ pub mod signer { pub use super::helpers::{SigningQueue, SignerService, ConfirmationsQueue}; pub use super::types::{ConfirmationRequest, TransactionModification, U256, TransactionCondition}; } - -/// Dapps integration utilities -pub mod dapps { - pub use super::helpers::dapps::DappsService; - pub use super::types::LocalDapp; -} diff --git a/rpc/src/v1/tests/mocked/parity.rs b/rpc/src/v1/tests/mocked/parity.rs index f8322f8fe79..ca241140640 100644 --- a/rpc/src/v1/tests/mocked/parity.rs +++ b/rpc/src/v1/tests/mocked/parity.rs @@ -425,20 +425,6 @@ fn rpc_parity_ws_address() { assert_eq!(io2.handle_request_sync(request), Some(response2.to_owned())); } -#[test] -fn rpc_parity_dapps_address() { - // given - let deps = Dependencies::new(); - let io1 = deps.default_client(); - - // when - let request = r#"{"jsonrpc": "2.0", "method": "parity_dappsUrl", "params": [], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"Dapps Server is disabled. This API is not available."},"id":1}"#; - - // then - assert_eq!(io1.handle_request_sync(request), Some(response.to_owned())); -} - #[test] fn rpc_parity_next_nonce() { let deps = Dependencies::new(); diff --git a/rpc/src/v1/tests/mocked/parity_set.rs b/rpc/src/v1/tests/mocked/parity_set.rs index 0347da39ad6..5aca2827e12 100644 --- a/rpc/src/v1/tests/mocked/parity_set.rs +++ b/rpc/src/v1/tests/mocked/parity_set.rs @@ -238,18 +238,3 @@ fn rpc_parity_remove_transaction() { miner.pending_transactions.lock().insert(hash, signed); assert_eq!(io.handle_request_sync(&request), Some(response.to_owned())); } - -#[test] -fn rpc_parity_set_dapps_list() { - let miner = miner_service(); - let client = client_service(); - let network = network_service(); - let updater = updater_service(); - let mut io = IoHandler::new(); - io.extend_with(parity_set_client(&client, &miner, &updater, &network).to_delegate()); - - let request = r#"{"jsonrpc": "2.0", "method": "parity_dappsList", "params":[], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","error":{"code":-32000,"message":"Dapps Server is disabled. This API is not available."},"id":1}"#; - - assert_eq!(io.handle_request_sync(request), Some(response.to_owned())); -} diff --git a/rpc/src/v1/traits/parity.rs b/rpc/src/v1/traits/parity.rs index 56634cc158c..2f2eef90741 100644 --- a/rpc/src/v1/traits/parity.rs +++ b/rpc/src/v1/traits/parity.rs @@ -161,11 +161,6 @@ build_rpc_trait! { #[rpc(name = "parity_localTransactions")] fn local_transactions(&self) -> Result>; - /// Returns current Dapps Server interface and port or an error if dapps server is disabled. - /// (deprecated, should always return an error now). - #[rpc(name = "parity_dappsUrl")] - fn dapps_url(&self) -> Result; - /// Returns current WS Server interface and port or an error if ws server is disabled. #[rpc(name = "parity_wsUrl")] fn ws_url(&self) -> Result; diff --git a/rpc/src/v1/traits/parity_set.rs b/rpc/src/v1/traits/parity_set.rs index dfd0ad5541f..707758920f6 100644 --- a/rpc/src/v1/traits/parity_set.rs +++ b/rpc/src/v1/traits/parity_set.rs @@ -18,7 +18,7 @@ use jsonrpc_core::{BoxFuture, Result}; -use v1::types::{Bytes, H160, H256, U256, ReleaseInfo, Transaction, LocalDapp}; +use v1::types::{Bytes, H160, H256, U256, ReleaseInfo, Transaction}; build_rpc_trait! { /// Parity-specific rpc interface for operations altering the settings. @@ -95,15 +95,6 @@ build_rpc_trait! { #[rpc(name = "parity_hashContent")] fn hash_content(&self, String) -> BoxFuture; - /// Returns true if refresh successful, error if unsuccessful or server is disabled - /// (deprecated, should always return an error now). - #[rpc(name = "parity_dappsRefresh")] - fn dapps_refresh(&self) -> Result; - - /// Returns a list of local dapps (deprecated, should always return an error now). - #[rpc(name = "parity_dappsList")] - fn dapps_list(&self) -> Result>; - /// Is there a release ready for install? #[rpc(name = "parity_upgradeReady")] fn upgrade_ready(&self) -> Result>; diff --git a/rpc/src/v1/types/dapps.rs b/rpc/src/v1/types/dapps.rs deleted file mode 100644 index 81339fb1dc2..00000000000 --- a/rpc/src/v1/types/dapps.rs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (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 . - -/// Local Dapp -#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct LocalDapp { - /// ID of local dapp - pub id: String, - /// Dapp name - pub name: String, - /// Dapp description - pub description: String, - /// Dapp version string - pub version: String, - /// Dapp author - pub author: String, - /// Dapp icon - #[serde(rename="iconUrl")] - pub icon_url: String, - /// Local development Url - #[serde(rename="localUrl")] - pub local_url: Option, -} - -#[cfg(test)] -mod tests { - use serde_json; - use super::LocalDapp; - - #[test] - fn dapp_serialization() { - let s = r#"{"id":"skeleton","name":"Skeleton","description":"A skeleton dapp","version":"0.1","author":"Parity Technologies Ltd","iconUrl":"title.png","localUrl":"http://localhost:5000"}"#; - - let dapp = LocalDapp { - id: "skeleton".into(), - name: "Skeleton".into(), - description: "A skeleton dapp".into(), - version: "0.1".into(), - author: "Parity Technologies Ltd".into(), - icon_url: "title.png".into(), - local_url: Some("http://localhost:5000".into()), - }; - - let serialized = serde_json::to_string(&dapp).unwrap(); - assert_eq!(serialized, s); - } -} diff --git a/rpc/src/v1/types/mod.rs b/rpc/src/v1/types/mod.rs index 7bf72d9c739..0f21e2f7b5b 100644 --- a/rpc/src/v1/types/mod.rs +++ b/rpc/src/v1/types/mod.rs @@ -23,7 +23,6 @@ mod bytes; mod call_request; mod confirmations; mod consensus_status; -mod dapps; mod derivation; mod filter; mod hash; @@ -57,7 +56,6 @@ pub use self::confirmations::{ TransactionModification, SignRequest, DecryptRequest, Either }; pub use self::consensus_status::*; -pub use self::dapps::LocalDapp; pub use self::derivation::{DeriveHash, DeriveHierarchical, Derive}; pub use self::filter::{Filter, FilterChanges}; pub use self::hash::{H64, H160, H256, H512, H520, H2048}; From 0359e3dea7928dc90e311af8d02d1e1645a75282 Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Thu, 12 Jul 2018 19:37:49 +0800 Subject: [PATCH 2/9] Remove unused pub use --- parity/rpc_apis.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/parity/rpc_apis.rs b/parity/rpc_apis.rs index ade6c696946..cf9f6d2dd59 100644 --- a/parity/rpc_apis.rs +++ b/parity/rpc_apis.rs @@ -20,7 +20,6 @@ use std::str::FromStr; use std::sync::{Arc, Weak}; pub use parity_rpc::signer::SignerService; -pub use parity_rpc::dapps::LocalDapp; use ethcore_service::PrivateTxService; use ethcore::account_provider::AccountProvider; From ad20fb398497da6d768dc402a814cd157ead8a6f Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Fri, 13 Jul 2018 22:40:11 +0800 Subject: [PATCH 3/9] Remove dapp policy/permission func in ethcore --- ethcore/src/account_provider/mod.rs | 289 +------------------------ ethcore/src/account_provider/stores.rs | 281 +----------------------- json/src/misc/dapps_settings.rs | 53 ----- json/src/misc/mod.rs | 2 - parity/lib.rs | 3 - 5 files changed, 9 insertions(+), 619 deletions(-) delete mode 100644 json/src/misc/dapps_settings.rs diff --git a/ethcore/src/account_provider/mod.rs b/ethcore/src/account_provider/mod.rs index e4289c60a57..7c7022df976 100644 --- a/ethcore/src/account_provider/mod.rs +++ b/ethcore/src/account_provider/mod.rs @@ -18,9 +18,9 @@ mod stores; -use self::stores::{AddressBook, DappsSettingsStore, NewDappsPolicy}; +use self::stores::AddressBook; -use std::collections::{HashMap, HashSet}; +use std::collections::HashMap; use std::fmt; use std::time::{Instant, Duration}; @@ -96,20 +96,6 @@ impl From for SignError { /// `AccountProvider` errors. pub type Error = SSError; -/// Dapp identifier -#[derive(Default, Debug, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)] -pub struct DappId(String); - -impl From for String { - fn from(id: DappId) -> String { id.0 } -} -impl From for DappId { - fn from(id: String) -> DappId { DappId(id) } -} -impl<'a> From<&'a str> for DappId { - fn from(id: &'a str) -> DappId { DappId(id.to_owned()) } -} - fn transient_sstore() -> EthMultiStore { EthMultiStore::open(Box::new(MemoryDirectory::default())).expect("MemoryDirectory load always succeeds; qed") } @@ -125,8 +111,6 @@ pub struct AccountProvider { unlocked: RwLock>, /// Address book. address_book: RwLock, - /// Dapps settings. - dapps_settings: RwLock, /// Accounts on disk sstore: Box, /// Accounts unlocked with rolling tokens @@ -167,7 +151,7 @@ impl AccountProvider { /// Creates new account provider. pub fn new(sstore: Box, settings: AccountProviderSettings) -> Self { let mut hardware_store = None; - + if settings.enable_hardware_wallets { match HardwareWalletManager::new() { Ok(manager) => { @@ -195,7 +179,6 @@ impl AccountProvider { unlocked_secrets: RwLock::new(HashMap::new()), unlocked: RwLock::new(HashMap::new()), address_book: RwLock::new(address_book), - dapps_settings: RwLock::new(DappsSettingsStore::new(&sstore.local_path())), sstore: sstore, transient_sstore: transient_sstore(), hardware_store: hardware_store, @@ -210,7 +193,6 @@ impl AccountProvider { unlocked_secrets: RwLock::new(HashMap::new()), unlocked: RwLock::new(HashMap::new()), address_book: RwLock::new(AddressBook::transient()), - dapps_settings: RwLock::new(DappsSettingsStore::transient()), sstore: Box::new(EthStore::open(Box::new(MemoryDirectory::default())).expect("MemoryDirectory load always succeeds; qed")), transient_sstore: transient_sstore(), hardware_store: None, @@ -292,7 +274,7 @@ impl AccountProvider { /// Returns addresses of hardware accounts. pub fn hardware_accounts(&self) -> Result, Error> { - if let Some(accounts) = self.hardware_store.as_ref().map(|h| h.list_wallets()) { + if let Some(accounts) = self.hardware_store.as_ref().map(|h| h.list_wallets()) { if !accounts.is_empty() { return Ok(accounts.into_iter().map(|a| a.address).collect()); } @@ -308,7 +290,7 @@ impl AccountProvider { Some(Ok(s)) => Ok(s), } } - + /// Provide a pin to a locked hardware wallet on USB path to unlock it pub fn hardware_pin_matrix_ack(&self, path: &str, pin: &str) -> Result { match self.hardware_store.as_ref().map(|h| h.pin_matrix_ack(path, pin)) { @@ -318,175 +300,6 @@ impl AccountProvider { } } - /// Sets addresses of accounts exposed for unknown dapps. - /// `None` means that all accounts will be visible. - /// If not `None` or empty it will also override default account. - pub fn set_new_dapps_addresses(&self, accounts: Option>) -> Result<(), Error> { - let current_default = self.new_dapps_default_address()?; - - self.dapps_settings.write().set_policy(match accounts { - None => NewDappsPolicy::AllAccounts { - default: current_default, - }, - Some(accounts) => NewDappsPolicy::Whitelist(accounts), - }); - Ok(()) - } - - /// Gets addresses of accounts exposed for unknown dapps. - /// `None` means that all accounts will be visible. - pub fn new_dapps_addresses(&self) -> Result>, Error> { - Ok(match self.dapps_settings.read().policy() { - NewDappsPolicy::AllAccounts { .. } => None, - NewDappsPolicy::Whitelist(accounts) => Some(accounts), - }) - } - - /// Sets a default account for unknown dapps. - /// This account will always be returned as the first one. - pub fn set_new_dapps_default_address(&self, address: Address) -> Result<(), Error> { - if !self.valid_addresses()?.contains(&address) { - return Err(SSError::InvalidAccount.into()); - } - - let mut settings = self.dapps_settings.write(); - let new_policy = match settings.policy() { - NewDappsPolicy::AllAccounts { .. } => NewDappsPolicy::AllAccounts { default: address }, - NewDappsPolicy::Whitelist(list) => NewDappsPolicy::Whitelist(Self::insert_default(list, address)), - }; - settings.set_policy(new_policy); - - Ok(()) - } - - /// Inserts given address as first in the vector, preventing duplicates. - fn insert_default(mut addresses: Vec
, default: Address) -> Vec
{ - if let Some(position) = addresses.iter().position(|address| address == &default) { - addresses.swap(0, position); - } else { - addresses.insert(0, default); - } - - addresses - } - - /// Returns a list of accounts that new dapp should see. - /// First account is always the default account. - fn new_dapps_addresses_list(&self) -> Result, Error> { - match self.dapps_settings.read().policy() { - NewDappsPolicy::AllAccounts { default } => if default.is_zero() { - self.accounts() - } else { - Ok(Self::insert_default(self.accounts()?, default)) - }, - NewDappsPolicy::Whitelist(accounts) => { - let addresses = self.filter_addresses(accounts)?; - if addresses.is_empty() { - Ok(vec![self.accounts()?.get(0).cloned().unwrap_or(0.into())]) - } else { - Ok(addresses) - } - }, - } - } - - /// Gets a default account for new dapps - /// Will return zero address in case the default is not set and there are no accounts configured. - pub fn new_dapps_default_address(&self) -> Result { - Ok(self.new_dapps_addresses_list()? - .get(0) - .cloned() - .unwrap_or(0.into()) - ) - } - - /// Gets a list of dapps recently requesting accounts. - pub fn recent_dapps(&self) -> Result, Error> { - Ok(self.dapps_settings.read().recent_dapps()) - } - - /// Marks dapp as recently used. - pub fn note_dapp_used(&self, dapp: DappId) -> Result<(), Error> { - let mut dapps = self.dapps_settings.write(); - dapps.mark_dapp_used(dapp.clone()); - Ok(()) - } - - /// Gets addresses visible for given dapp. - pub fn dapp_addresses(&self, dapp: DappId) -> Result, Error> { - let accounts = self.dapps_settings.read().settings().get(&dapp).map(|settings| { - (settings.accounts.clone(), settings.default.clone()) - }); - - match accounts { - Some((Some(accounts), Some(default))) => self.filter_addresses(Self::insert_default(accounts, default)), - Some((Some(accounts), None)) => self.filter_addresses(accounts), - Some((None, Some(default))) => self.filter_addresses(Self::insert_default(self.new_dapps_addresses_list()?, default)), - _ => self.new_dapps_addresses_list(), - } - } - - /// Returns default account for particular dapp falling back to other allowed accounts if necessary. - pub fn dapp_default_address(&self, dapp: DappId) -> Result { - let dapp_default = self.dapp_addresses(dapp)? - .get(0) - .cloned(); - - match dapp_default { - Some(default) => Ok(default), - None => self.new_dapps_default_address(), - } - } - - /// Sets default address for given dapp. - /// Does not alter dapp addresses, but this account will always be returned as the first one. - pub fn set_dapp_default_address(&self, dapp: DappId, address: Address) -> Result<(), Error> { - if !self.valid_addresses()?.contains(&address) { - return Err(SSError::InvalidAccount.into()); - } - - self.dapps_settings.write().set_default(dapp, address); - Ok(()) - } - - /// Sets addresses visible for given dapp. - /// If `None` - falls back to dapps addresses - /// If not `None` and not empty it will also override default account. - pub fn set_dapp_addresses(&self, dapp: DappId, addresses: Option>) -> Result<(), Error> { - let (addresses, default) = match addresses { - Some(addresses) => { - let addresses = self.filter_addresses(addresses)?; - let default = addresses.get(0).cloned(); - (Some(addresses), default) - }, - None => (None, None), - }; - - let mut settings = self.dapps_settings.write(); - if let Some(default) = default { - settings.set_default(dapp.clone(), default); - } - settings.set_accounts(dapp, addresses); - Ok(()) - } - - fn valid_addresses(&self) -> Result, Error> { - Ok(self.addresses_info().into_iter() - .map(|(address, _)| address) - .chain(self.accounts()?) - .collect()) - } - - /// Removes addresses that are neither accounts nor in address book. - fn filter_addresses(&self, addresses: Vec
) -> Result, Error> { - let valid = self.valid_addresses()?; - - Ok(addresses.into_iter() - .filter(|a| valid.contains(&a)) - .collect() - ) - } - /// Returns each address along with metadata. pub fn addresses_info(&self) -> HashMap { self.address_book.read().get() @@ -849,7 +662,7 @@ impl AccountProvider { #[cfg(test)] mod tests { - use super::{AccountProvider, Unlock, DappId}; + use super::{AccountProvider, Unlock}; use std::time::{Duration, Instant}; use ethstore::ethkey::{Generator, Random, Address}; use ethstore::{StoreAccountRef, Derivation}; @@ -977,96 +790,6 @@ mod tests { assert!(ap.sign_with_token(kp.address(), token, Default::default()).is_err(), "Second usage of the same token should fail."); } - #[test] - fn should_reset_dapp_addresses_to_default() { - // given - let ap = AccountProvider::transient_provider(); - let app = DappId("app1".into()); - // add accounts to address book - ap.set_address_name(1.into(), "1".into()); - ap.set_address_name(2.into(), "2".into()); - // set `AllAccounts` policy - ap.set_new_dapps_addresses(Some(vec![1.into(), 2.into()])).unwrap(); - assert_eq!(ap.dapp_addresses(app.clone()).unwrap(), vec![1.into(), 2.into()]); - - // Alter and check - ap.set_dapp_addresses(app.clone(), Some(vec![1.into(), 3.into()])).unwrap(); - assert_eq!(ap.dapp_addresses(app.clone()).unwrap(), vec![1.into()]); - - // Reset back to default - ap.set_dapp_addresses(app.clone(), None).unwrap(); - assert_eq!(ap.dapp_addresses(app.clone()).unwrap(), vec![1.into(), 2.into()]); - } - - #[test] - fn should_set_dapps_default_address() { - // given - let ap = AccountProvider::transient_provider(); - let app = DappId("app1".into()); - // set `AllAccounts` policy - ap.set_new_dapps_addresses(None).unwrap(); - // add accounts to address book - ap.set_address_name(1.into(), "1".into()); - ap.set_address_name(2.into(), "2".into()); - - ap.set_dapp_addresses(app.clone(), Some(vec![1.into(), 2.into(), 3.into()])).unwrap(); - assert_eq!(ap.dapp_addresses(app.clone()).unwrap(), vec![1.into(), 2.into()]); - assert_eq!(ap.dapp_default_address("app1".into()).unwrap(), 1.into()); - - // when setting empty list - ap.set_dapp_addresses(app.clone(), Some(vec![])).unwrap(); - - // then default account is intact - assert_eq!(ap.dapp_addresses(app.clone()).unwrap(), vec![1.into()]); - assert_eq!(ap.dapp_default_address("app1".into()).unwrap(), 1.into()); - - // alter default account - ap.set_dapp_default_address("app1".into(), 2.into()).unwrap(); - assert_eq!(ap.dapp_addresses(app.clone()).unwrap(), vec![2.into()]); - assert_eq!(ap.dapp_default_address("app1".into()).unwrap(), 2.into()); - } - - #[test] - fn should_set_dapps_policy_and_default_account() { - // given - let ap = AccountProvider::transient_provider(); - - // default_account should be always available - assert_eq!(ap.new_dapps_default_address().unwrap(), 0.into()); - - let address = ap.new_account(&"test".into()).unwrap(); - ap.set_address_name(1.into(), "1".into()); - - // Default account set to first account by default - assert_eq!(ap.new_dapps_default_address().unwrap(), address); - assert_eq!(ap.dapp_default_address("app1".into()).unwrap(), address); - - // Even when returning nothing - ap.set_new_dapps_addresses(Some(vec![])).unwrap(); - // Default account is still returned - assert_eq!(ap.dapp_addresses("app1".into()).unwrap(), vec![address]); - - // change to all - ap.set_new_dapps_addresses(None).unwrap(); - assert_eq!(ap.dapp_addresses("app1".into()).unwrap(), vec![address]); - - // change to non-existent account - ap.set_new_dapps_addresses(Some(vec![2.into()])).unwrap(); - assert_eq!(ap.dapp_addresses("app1".into()).unwrap(), vec![address]); - - // change to a addresses - ap.set_new_dapps_addresses(Some(vec![1.into()])).unwrap(); - assert_eq!(ap.dapp_addresses("app1".into()).unwrap(), vec![1.into()]); - - // it overrides default account - assert_eq!(ap.new_dapps_default_address().unwrap(), 1.into()); - assert_eq!(ap.dapp_default_address("app1".into()).unwrap(), 1.into()); - - ap.set_new_dapps_default_address(address).unwrap(); - assert_eq!(ap.new_dapps_default_address().unwrap(), address); - assert_eq!(ap.dapp_default_address("app1".into()).unwrap(), address); - } - #[test] fn should_not_return_blacklisted_account() { // given diff --git a/ethcore/src/account_provider/stores.rs b/ethcore/src/account_provider/stores.rs index d7725deb7e3..7124e91e23a 100644 --- a/ethcore/src/account_provider/stores.rs +++ b/ethcore/src/account_provider/stores.rs @@ -14,21 +14,14 @@ // You should have received a copy of the GNU General Public License // along with Parity. If not, see . -//! Address Book and Dapps Settings Store +//! Address Book Store use std::{fs, fmt, hash, ops}; -use std::sync::atomic::{self, AtomicUsize}; use std::collections::HashMap; use std::path::{Path, PathBuf}; use ethstore::ethkey::Address; -use ethjson::misc::{ - AccountMeta, - DappsSettings as JsonSettings, - DappsHistory as JsonDappsHistory, - NewDappsPolicy as JsonNewDappsPolicy, -}; -use account_provider::DappId; +use ethjson::misc::AccountMeta; /// Disk-backed map from Address to String. Uses JSON. pub struct AddressBook { @@ -88,214 +81,6 @@ impl AddressBook { } } -/// Dapps user settings -#[derive(Debug, Default, Clone, Eq, PartialEq)] -pub struct DappsSettings { - /// A list of visible accounts - pub accounts: Option>, - /// Default account - pub default: Option
, -} - -impl From for DappsSettings { - fn from(s: JsonSettings) -> Self { - DappsSettings { - accounts: s.accounts.map(|accounts| accounts.into_iter().map(Into::into).collect()), - default: s.default.map(Into::into), - } - } -} - -impl From for JsonSettings { - fn from(s: DappsSettings) -> Self { - JsonSettings { - accounts: s.accounts.map(|accounts| accounts.into_iter().map(Into::into).collect()), - default: s.default.map(Into::into), - } - } -} - -/// Dapps user settings -#[derive(Debug, Clone, Eq, PartialEq)] -pub enum NewDappsPolicy { - AllAccounts { - default: Address, - }, - Whitelist(Vec
), -} - -impl From for NewDappsPolicy { - fn from(s: JsonNewDappsPolicy) -> Self { - match s { - JsonNewDappsPolicy::AllAccounts { default } => NewDappsPolicy::AllAccounts { - default: default.into(), - }, - JsonNewDappsPolicy::Whitelist(accounts) => NewDappsPolicy::Whitelist( - accounts.into_iter().map(Into::into).collect() - ), - } - } -} - -impl From for JsonNewDappsPolicy { - fn from(s: NewDappsPolicy) -> Self { - match s { - NewDappsPolicy::AllAccounts { default } => JsonNewDappsPolicy::AllAccounts { - default: default.into(), - }, - NewDappsPolicy::Whitelist(accounts) => JsonNewDappsPolicy::Whitelist( - accounts.into_iter().map(Into::into).collect() - ), - } - } -} - -/// Transient dapps data -#[derive(Default, Debug, Clone, Eq, PartialEq)] -pub struct TransientDappsData { - /// Timestamp of last access - pub last_accessed: u64, -} - -impl From for TransientDappsData { - fn from(s: JsonDappsHistory) -> Self { - TransientDappsData { - last_accessed: s.last_accessed, - } - } -} - -impl From for JsonDappsHistory { - fn from(s: TransientDappsData) -> Self { - JsonDappsHistory { - last_accessed: s.last_accessed, - } - } -} - -enum TimeProvider { - Clock, - Incremenetal(AtomicUsize) -} - -impl TimeProvider { - fn get(&self) -> u64 { - match *self { - TimeProvider::Clock => { - ::std::time::UNIX_EPOCH.elapsed() - .expect("Correct time is required to be set") - .as_secs() - - }, - TimeProvider::Incremenetal(ref time) => { - time.fetch_add(1, atomic::Ordering::SeqCst) as u64 - }, - } - } -} - -const MAX_RECENT_DAPPS: usize = 50; - -/// Disk-backed map from DappId to Settings. Uses JSON. -pub struct DappsSettingsStore { - /// Dapps Settings - settings: DiskMap, - /// New Dapps Policy - policy: DiskMap, - /// Transient Data of recently Accessed Dapps - history: DiskMap, - /// Time - time: TimeProvider, -} - -impl DappsSettingsStore { - /// Creates new store at given directory path. - pub fn new(path: &Path) -> Self { - let mut r = DappsSettingsStore { - settings: DiskMap::new(path, "dapps_accounts.json".into()), - policy: DiskMap::new(path, "dapps_policy.json".into()), - history: DiskMap::new(path, "dapps_history.json".into()), - time: TimeProvider::Clock, - }; - r.settings.revert(JsonSettings::read); - r.policy.revert(JsonNewDappsPolicy::read); - r.history.revert(JsonDappsHistory::read); - r - } - - /// Creates transient store (no changes are saved to disk). - pub fn transient() -> Self { - DappsSettingsStore { - settings: DiskMap::transient(), - policy: DiskMap::transient(), - history: DiskMap::transient(), - time: TimeProvider::Incremenetal(AtomicUsize::new(1)), - } - } - - /// Get copy of the dapps settings - pub fn settings(&self) -> HashMap { - self.settings.clone() - } - - /// Returns current new dapps policy - pub fn policy(&self) -> NewDappsPolicy { - self.policy.get("default").cloned().unwrap_or(NewDappsPolicy::AllAccounts { - default: 0.into(), - }) - } - - /// Returns recent dapps with last accessed timestamp - pub fn recent_dapps(&self) -> HashMap { - self.history.iter().map(|(k, v)| (k.clone(), v.last_accessed)).collect() - } - - /// Marks recent dapp as used - pub fn mark_dapp_used(&mut self, dapp: DappId) { - { - let entry = self.history.entry(dapp).or_insert_with(|| Default::default()); - entry.last_accessed = self.time.get(); - } - // Clear extraneous entries - while self.history.len() > MAX_RECENT_DAPPS { - let min = self.history.iter() - .min_by_key(|&(_, ref v)| v.last_accessed) - .map(|(ref k, _)| k.clone()) - .cloned(); - - match min { - Some(k) => self.history.remove(&k), - None => break, - }; - } - self.history.save(JsonDappsHistory::write); - } - - /// Sets current new dapps policy - pub fn set_policy(&mut self, policy: NewDappsPolicy) { - self.policy.insert("default".into(), policy); - self.policy.save(JsonNewDappsPolicy::write); - } - - /// Sets accounts for specific dapp. - pub fn set_accounts(&mut self, id: DappId, accounts: Option>) { - { - let settings = self.settings.entry(id).or_insert_with(DappsSettings::default); - settings.accounts = accounts; - } - self.settings.save(JsonSettings::write); - } - - /// Sets a default account for specific dapp. - pub fn set_default(&mut self, id: DappId, default: Address) { - { - let settings = self.settings.entry(id).or_insert_with(DappsSettings::default); - settings.default = Some(default); - } - self.settings.save(JsonSettings::write); - } -} - /// Disk-serializable HashMap #[derive(Debug)] struct DiskMap { @@ -366,8 +151,7 @@ impl DiskMap { #[cfg(test)] mod tests { - use super::{AddressBook, DappsSettingsStore, DappsSettings, NewDappsPolicy}; - use account_provider::DappId; + use super::AddressBook; use std::collections::HashMap; use ethjson::misc::AccountMeta; use tempdir::TempDir; @@ -398,63 +182,4 @@ mod tests { 3.into() => AccountMeta{name: "Three".to_owned(), meta: "{}".to_owned(), uuid: None} ]); } - - #[test] - fn should_save_and_reload_dapps_settings() { - // given - let tempdir = TempDir::new("").unwrap(); - let mut b = DappsSettingsStore::new(tempdir.path()); - - // when - b.set_accounts("dappOne".into(), Some(vec![1.into(), 2.into()])); - - // then - let b = DappsSettingsStore::new(tempdir.path()); - assert_eq!(b.settings(), hash_map![ - "dappOne".into() => DappsSettings { - accounts: Some(vec![1.into(), 2.into()]), - default: None, - } - ]); - } - - #[test] - fn should_maintain_a_map_of_recent_dapps() { - let mut store = DappsSettingsStore::transient(); - assert!(store.recent_dapps().is_empty(), "Initially recent dapps should be empty."); - - let dapp1: DappId = "dapp1".into(); - let dapp2: DappId = "dapp2".into(); - store.mark_dapp_used(dapp1.clone()); - let recent = store.recent_dapps(); - assert_eq!(recent.len(), 1); - assert_eq!(recent.get(&dapp1), Some(&1)); - - store.mark_dapp_used(dapp2.clone()); - let recent = store.recent_dapps(); - assert_eq!(recent.len(), 2); - assert_eq!(recent.get(&dapp1), Some(&1)); - assert_eq!(recent.get(&dapp2), Some(&2)); - } - - #[test] - fn should_store_dapps_policy() { - // given - let tempdir = TempDir::new("").unwrap(); - let mut store = DappsSettingsStore::new(tempdir.path()); - - // Test default policy - assert_eq!(store.policy(), NewDappsPolicy::AllAccounts { - default: 0.into(), - }); - - // when - store.set_policy(NewDappsPolicy::Whitelist(vec![1.into(), 2.into()])); - - // then - let store = DappsSettingsStore::new(tempdir.path()); - assert_eq!(store.policy.clone(), hash_map![ - "default".into() => NewDappsPolicy::Whitelist(vec![1.into(), 2.into()]) - ]); - } } diff --git a/json/src/misc/dapps_settings.rs b/json/src/misc/dapps_settings.rs deleted file mode 100644 index f59f5f1cf6d..00000000000 --- a/json/src/misc/dapps_settings.rs +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2015-2018 Parity Technologies (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 . - -//! Dapps settings de/serialization. - -use hash; - -/// Settings for specific dapp. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct DappsSettings { - /// A list of accounts this Dapp can see. - pub accounts: Option>, - /// Default account - pub default: Option, -} - -impl_serialization!(String => DappsSettings); - -/// History for specific dapp. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub struct DappsHistory { - /// Last accessed timestamp - pub last_accessed: u64, -} - -impl_serialization!(String => DappsHistory); - -/// Accounts policy for new dapps. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub enum NewDappsPolicy { - /// All accounts are exposed by default. - AllAccounts { - /// Default account, which should be returned as the first one. - default: hash::Address, - }, - /// Only accounts listed here are exposed by default for new dapps. - Whitelist(Vec), -} - -impl_serialization!(String => NewDappsPolicy); diff --git a/json/src/misc/mod.rs b/json/src/misc/mod.rs index 836094f0c08..ae7dd80e1fa 100644 --- a/json/src/misc/mod.rs +++ b/json/src/misc/mod.rs @@ -48,7 +48,5 @@ macro_rules! impl_serialization { } mod account_meta; -mod dapps_settings; -pub use self::dapps_settings::{DappsSettings, DappsHistory, NewDappsPolicy}; pub use self::account_meta::AccountMeta; diff --git a/parity/lib.rs b/parity/lib.rs index b1b385a1a31..2384b159e03 100644 --- a/parity/lib.rs +++ b/parity/lib.rs @@ -80,9 +80,6 @@ extern crate log as rlog; #[cfg(feature = "secretstore")] extern crate ethcore_secretstore; -#[cfg(feature = "dapps")] -extern crate parity_dapps; - #[cfg(test)] #[macro_use] extern crate pretty_assertions; From 82ac92639e4c35209c394ffae1972a7e8e70bb78 Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Fri, 13 Jul 2018 23:45:48 +0800 Subject: [PATCH 4/9] Remove all dapps settings from rpc --- ethcore/src/account_provider/mod.rs | 5 ++ rpc/src/v1/extractors.rs | 30 ++----- rpc/src/v1/helpers/signing_queue.rs | 11 +-- rpc/src/v1/impls/eth.rs | 24 ++--- rpc/src/v1/impls/light/eth.rs | 10 +-- rpc/src/v1/impls/light/parity.rs | 14 ++- rpc/src/v1/impls/parity.rs | 17 ++-- rpc/src/v1/impls/parity_accounts.rs | 57 +----------- rpc/src/v1/impls/personal.rs | 4 +- rpc/src/v1/impls/signing.rs | 11 ++- rpc/src/v1/impls/signing_unsafe.rs | 13 ++- rpc/src/v1/metadata.rs | 19 +--- rpc/src/v1/tests/mocked/eth.rs | 7 +- rpc/src/v1/tests/mocked/parity.rs | 1 - rpc/src/v1/tests/mocked/parity_accounts.rs | 100 --------------------- rpc/src/v1/tests/mocked/signer.rs | 2 +- rpc/src/v1/traits/parity.rs | 4 +- rpc/src/v1/traits/parity_accounts.rs | 53 +---------- rpc/src/v1/types/confirmations.rs | 3 +- rpc/src/v1/types/mod.rs | 2 +- rpc/src/v1/types/provenance.rs | 84 +---------------- 21 files changed, 59 insertions(+), 412 deletions(-) diff --git a/ethcore/src/account_provider/mod.rs b/ethcore/src/account_provider/mod.rs index 7c7022df976..04bc4f4099d 100644 --- a/ethcore/src/account_provider/mod.rs +++ b/ethcore/src/account_provider/mod.rs @@ -272,6 +272,11 @@ impl AccountProvider { ) } + /// Returns the address of default account. + pub fn default_account(&self) -> Result { + Ok(self.accounts()?.first().cloned().unwrap_or_default()) + } + /// Returns addresses of hardware accounts. pub fn hardware_accounts(&self) -> Result, Error> { if let Some(accounts) = self.hardware_store.as_ref().map(|h| h.list_wallets()) { diff --git a/rpc/src/v1/extractors.rs b/rpc/src/v1/extractors.rs index c69c41dddf3..67a1c9fdfa8 100644 --- a/rpc/src/v1/extractors.rs +++ b/rpc/src/v1/extractors.rs @@ -36,13 +36,11 @@ pub struct RpcExtractor; impl HttpMetaExtractor for RpcExtractor { type Metadata = Metadata; - fn read_metadata(&self, origin: Option, user_agent: Option, dapps_origin: Option) -> Metadata { + fn read_metadata(&self, _origin: Option, user_agent: Option, _dapps_origin: Option) -> Metadata { Metadata { - origin: match (origin.as_ref().map(|s| s.as_str()), user_agent, dapps_origin) { - (Some("null"), _, Some(dapp)) => Origin::Dapps(dapp.into()), - (Some(dapp), _, _) => Origin::Dapps(dapp.to_owned().into()), - (None, Some(service), _) => Origin::Rpc(service.into()), - (None, _, _) => Origin::Rpc("unknown".into()), + origin: match user_agent { + Some(service) => Origin::Rpc(service.into()), + None => Origin::Rpc("unknown".into()), }, session: None, } @@ -76,16 +74,15 @@ impl ws::MetaExtractor for WsExtractor { fn extract(&self, req: &ws::RequestContext) -> Metadata { let id = req.session_id as u64; - let dapp = req.origin.as_ref().map(|origin| (&**origin).into()).unwrap_or_default(); let origin = match self.authcodes_path { Some(ref path) => { let authorization = req.protocols.get(0).and_then(|p| auth_token_hash(&path, p, true)); match authorization { - Some(id) => Origin::Signer { session: id.into(), dapp: dapp }, - None => Origin::Ws { session: id.into(), dapp: dapp }, + Some(id) => Origin::Signer { session: id.into() }, + None => Origin::Ws { session: id.into() }, } }, - None => Origin::Ws { session: id.into(), dapp: dapp }, + None => Origin::Ws { session: id.into() }, }; let session = Some(Arc::new(Session::new(req.sender()))); Metadata { @@ -262,17 +259,4 @@ mod tests { assert_eq!(meta2.origin, Origin::Rpc("http://parity.io".into())); assert_eq!(meta3.origin, Origin::Rpc("http://parity.io".into())); } - - #[test] - fn should_dapps_origin() { - // given - let extractor = RpcExtractor; - let dapp = "https://wallet.ethereum.org".to_owned(); - - // when - let meta = extractor.read_metadata(Some("null".into()), None, Some(dapp.clone())); - - // then - assert_eq!(meta.origin, Origin::Dapps(dapp.into())); - } } diff --git a/rpc/src/v1/helpers/signing_queue.rs b/rpc/src/v1/helpers/signing_queue.rs index 17b26b01ebb..9f31628a319 100644 --- a/rpc/src/v1/helpers/signing_queue.rs +++ b/rpc/src/v1/helpers/signing_queue.rs @@ -17,9 +17,8 @@ use std::collections::BTreeMap; use ethereum_types::{U256, Address}; use parking_lot::{Mutex, RwLock}; -use ethcore::account_provider::DappId; use v1::helpers::{ConfirmationRequest, ConfirmationPayload, oneshot, errors}; -use v1::types::{ConfirmationResponse, H160 as RpcH160, Origin, DappId as RpcDappId}; +use v1::types::{ConfirmationResponse, H160 as RpcH160, Origin}; use jsonrpc_core::Error; @@ -30,14 +29,6 @@ pub type ConfirmationResult = Result; pub enum DefaultAccount { /// Default account is known Provided(Address), - /// Should use default account for dapp - ForDapp(DappId), -} - -impl From for DefaultAccount { - fn from(dapp_id: RpcDappId) -> Self { - DefaultAccount::ForDapp(dapp_id.into()) - } } impl From for DefaultAccount { diff --git a/rpc/src/v1/impls/eth.rs b/rpc/src/v1/impls/eth.rs index d20b2feb267..589c9a70972 100644 --- a/rpc/src/v1/impls/eth.rs +++ b/rpc/src/v1/impls/eth.rs @@ -21,11 +21,11 @@ use std::time::{Instant, Duration, SystemTime, UNIX_EPOCH}; use std::sync::Arc; use rlp::{self, Rlp}; -use ethereum_types::{U256, H64, H160, H256, Address}; +use ethereum_types::{U256, H64, H256, Address}; use parking_lot::Mutex; use ethash::SeedHashCompute; -use ethcore::account_provider::{AccountProvider, DappId}; +use ethcore::account_provider::AccountProvider; use ethcore::client::{BlockChainClient, BlockId, TransactionId, UncleId, StateOrBlock, StateClient, StateInfo, Call, EngineInfo}; use ethcore::ethereum::Ethash; use ethcore::filter::Filter as EthcoreFilter; @@ -400,13 +400,6 @@ impl EthClient Result> { - self.accounts - .note_dapp_used(dapp.clone()) - .and_then(|_| self.accounts.dapp_addresses(dapp)) - .map_err(|e| errors::account("Could not fetch accounts.", e)) - } - fn get_state(&self, number: BlockNumber) -> StateOrBlock { match number { BlockNumber::Num(num) => BlockId::Number(num).into(), @@ -509,12 +502,10 @@ impl Eth for EthClient< } } - fn author(&self, meta: Metadata) -> Result { - let dapp = meta.dapp_id(); - + fn author(&self, _meta: Metadata) -> Result { let mut miner = self.miner.authoring_params().author; if miner == 0.into() { - miner = self.dapp_accounts(dapp.into())?.get(0).cloned().unwrap_or_default(); + miner = self.accounts.accounts().ok().and_then(|a| a.get(0).cloned()).unwrap_or_default(); } Ok(RpcH160::from(miner)) @@ -532,10 +523,9 @@ impl Eth for EthClient< Ok(RpcU256::from(default_gas_price(&*self.client, &*self.miner, self.options.gas_price_percentile))) } - fn accounts(&self, meta: Metadata) -> Result> { - let dapp = meta.dapp_id(); - - let accounts = self.dapp_accounts(dapp.into())?; + fn accounts(&self, _meta: Metadata) -> Result> { + let accounts = self.accounts.accounts() + .map_err(|e| errors::account("Could not fetch accounts.", e))?; Ok(accounts.into_iter().map(Into::into).collect()) } diff --git a/rpc/src/v1/impls/light/eth.rs b/rpc/src/v1/impls/light/eth.rs index e88ac2dab35..e9528ac6331 100644 --- a/rpc/src/v1/impls/light/eth.rs +++ b/rpc/src/v1/impls/light/eth.rs @@ -29,7 +29,7 @@ use light::client::LightChainClient; use light::{cht, TransactionQueue}; use light::on_demand::{request, OnDemand}; -use ethcore::account_provider::{AccountProvider, DappId}; +use ethcore::account_provider::AccountProvider; use ethcore::encoded; use ethcore::filter::Filter as EthcoreFilter; use ethcore::ids::BlockId; @@ -271,12 +271,8 @@ impl Eth for EthClient { .unwrap_or_else(Default::default)) } - fn accounts(&self, meta: Metadata) -> Result> { - let dapp: DappId = meta.dapp_id().into(); - - self.accounts - .note_dapp_used(dapp.clone()) - .and_then(|_| self.accounts.dapp_addresses(dapp)) + fn accounts(&self, _meta: Metadata) -> Result> { + self.accounts.accounts() .map_err(|e| errors::account("Could not fetch accounts.", e)) .map(|accs| accs.into_iter().map(Into::::into).collect()) } diff --git a/rpc/src/v1/impls/light/parity.rs b/rpc/src/v1/impls/light/parity.rs index f9ec03cd378..a23613c8877 100644 --- a/rpc/src/v1/impls/light/parity.rs +++ b/rpc/src/v1/impls/light/parity.rs @@ -44,7 +44,7 @@ use v1::types::{ Peers, Transaction, RpcSettings, Histogram, TransactionStats, LocalTransactionStatus, BlockNumber, ConsensusCapability, VersionInfo, - OperationsInfo, DappId, ChainStatus, + OperationsInfo, ChainStatus, AccountInfo, HwAccountInfo, Header, RichHeader, }; use Host; @@ -105,13 +105,10 @@ impl ParityClient { impl Parity for ParityClient { type Metadata = Metadata; - fn accounts_info(&self, dapp: Trailing) -> Result> { - let dapp = dapp.unwrap_or_default(); - + fn accounts_info(&self) -> Result> { let store = &self.accounts; let dapp_accounts = store - .note_dapp_used(dapp.clone().into()) - .and_then(|_| store.dapp_addresses(dapp.into())) + .accounts() .map_err(|e| errors::account("Could not fetch accounts.", e))? .into_iter().collect::>(); @@ -142,10 +139,9 @@ impl Parity for ParityClient { Ok(store.locked_hardware_accounts().map_err(|e| errors::account("Error communicating with hardware wallet.", e))?) } - fn default_account(&self, meta: Self::Metadata) -> Result { - let dapp_id = meta.dapp_id(); + fn default_account(&self, _meta: Self::Metadata) -> Result { Ok(self.accounts - .dapp_addresses(dapp_id.into()) + .accounts() .ok() .and_then(|accounts| accounts.get(0).cloned()) .map(|acc| acc.into()) diff --git a/rpc/src/v1/impls/parity.rs b/rpc/src/v1/impls/parity.rs index 93560836f9c..fe2db73936d 100644 --- a/rpc/src/v1/impls/parity.rs +++ b/rpc/src/v1/impls/parity.rs @@ -45,7 +45,7 @@ use v1::types::{ Peers, Transaction, RpcSettings, Histogram, TransactionStats, LocalTransactionStatus, BlockNumber, ConsensusCapability, VersionInfo, - OperationsInfo, DappId, ChainStatus, + OperationsInfo, ChainStatus, AccountInfo, HwAccountInfo, RichHeader, block_number_to_id }; @@ -110,12 +110,8 @@ impl Parity for ParityClient where { type Metadata = Metadata; - fn accounts_info(&self, dapp: Trailing) -> Result> { - let dapp = dapp.unwrap_or_default(); - - let dapp_accounts = self.accounts - .note_dapp_used(dapp.clone().into()) - .and_then(|_| self.accounts.dapp_addresses(dapp.into())) + fn accounts_info(&self) -> Result> { + let dapp_accounts = self.accounts.accounts() .map_err(|e| errors::account("Could not fetch accounts.", e))? .into_iter().collect::>(); @@ -144,11 +140,8 @@ impl Parity for ParityClient where self.accounts.locked_hardware_accounts().map_err(|e| errors::account("Error communicating with hardware wallet.", e)) } - fn default_account(&self, meta: Self::Metadata) -> Result { - let dapp_id = meta.dapp_id(); - - Ok(self.accounts - .dapp_default_address(dapp_id.into()) + fn default_account(&self, _meta: Self::Metadata) -> Result { + Ok(self.accounts.default_account() .map(Into::into) .ok() .unwrap_or_default()) diff --git a/rpc/src/v1/impls/parity_accounts.rs b/rpc/src/v1/impls/parity_accounts.rs index f9be594ad8b..941a77796b9 100644 --- a/rpc/src/v1/impls/parity_accounts.rs +++ b/rpc/src/v1/impls/parity_accounts.rs @@ -25,7 +25,7 @@ use ethcore::account_provider::AccountProvider; use jsonrpc_core::Result; use v1::helpers::errors; use v1::traits::ParityAccounts; -use v1::types::{H160 as RpcH160, H256 as RpcH256, H520 as RpcH520, DappId, Derive, DeriveHierarchical, DeriveHash, ExtAccountInfo}; +use v1::types::{H160 as RpcH160, H256 as RpcH256, H520 as RpcH520, Derive, DeriveHierarchical, DeriveHash, ExtAccountInfo}; use ethkey::Password; /// Account management (personal) rpc implementation. @@ -143,61 +143,6 @@ impl ParityAccounts for ParityAccountsClient { Ok(true) } - fn set_dapp_addresses(&self, dapp: DappId, addresses: Option>) -> Result { - self.accounts.set_dapp_addresses(dapp.into(), addresses.map(into_vec)) - .map_err(|e| errors::account("Couldn't set dapp addresses.", e)) - .map(|_| true) - } - - fn dapp_addresses(&self, dapp: DappId) -> Result> { - self.accounts.dapp_addresses(dapp.into()) - .map_err(|e| errors::account("Couldn't get dapp addresses.", e)) - .map(into_vec) - } - - fn set_dapp_default_address(&self, dapp: DappId, address: RpcH160) -> Result { - self.accounts.set_dapp_default_address(dapp.into(), address.into()) - .map_err(|e| errors::account("Couldn't set dapp default address.", e)) - .map(|_| true) - } - - fn dapp_default_address(&self, dapp: DappId) -> Result { - self.accounts.dapp_default_address(dapp.into()) - .map_err(|e| errors::account("Couldn't get dapp default address.", e)) - .map(Into::into) - } - - fn set_new_dapps_addresses(&self, addresses: Option>) -> Result { - self.accounts - .set_new_dapps_addresses(addresses.map(into_vec)) - .map_err(|e| errors::account("Couldn't set dapps addresses.", e)) - .map(|_| true) - } - - fn new_dapps_addresses(&self) -> Result>> { - self.accounts.new_dapps_addresses() - .map_err(|e| errors::account("Couldn't get dapps addresses.", e)) - .map(|accounts| accounts.map(into_vec)) - } - - fn set_new_dapps_default_address(&self, address: RpcH160) -> Result { - self.accounts.set_new_dapps_default_address(address.into()) - .map_err(|e| errors::account("Couldn't set new dapps default address.", e)) - .map(|_| true) - } - - fn new_dapps_default_address(&self) -> Result { - self.accounts.new_dapps_default_address() - .map_err(|e| errors::account("Couldn't get new dapps default address.", e)) - .map(Into::into) - } - - fn recent_dapps(&self) -> Result> { - self.accounts.recent_dapps() - .map_err(|e| errors::account("Couldn't get recent dapps.", e)) - .map(|map| map.into_iter().map(|(k, v)| (k.into(), v)).collect()) - } - fn import_geth_accounts(&self, addresses: Vec) -> Result> { self.accounts .import_geth_accounts(into_vec(addresses), false) diff --git a/rpc/src/v1/impls/personal.rs b/rpc/src/v1/impls/personal.rs index 8cb98a66b1e..9def0244767 100644 --- a/rpc/src/v1/impls/personal.rs +++ b/rpc/src/v1/impls/personal.rs @@ -58,14 +58,14 @@ impl PersonalClient { } impl PersonalClient { - fn do_sign_transaction(&self, meta: Metadata, request: TransactionRequest, password: String) -> BoxFuture<(PendingTransaction, D)> { + fn do_sign_transaction(&self, _meta: Metadata, request: TransactionRequest, password: String) -> BoxFuture<(PendingTransaction, D)> { let dispatcher = self.dispatcher.clone(); let accounts = self.accounts.clone(); let default = match request.from.as_ref() { Some(account) => Ok(account.clone().into()), None => accounts - .dapp_default_address(meta.dapp_id().into()) + .default_account() .map_err(|e| errors::account("Cannot find default account.", e)), }; diff --git a/rpc/src/v1/impls/signing.rs b/rpc/src/v1/impls/signing.rs index b22bbc80dd8..d167153530a 100644 --- a/rpc/src/v1/impls/signing.rs +++ b/rpc/src/v1/impls/signing.rs @@ -112,7 +112,6 @@ impl SigningQueueClient { let accounts = self.accounts.clone(); let default_account = match default_account { DefaultAccount::Provided(acc) => acc, - DefaultAccount::ForDapp(dapp) => accounts.dapp_default_address(dapp).ok().unwrap_or_default(), }; let dispatcher = self.dispatcher.clone(); @@ -138,8 +137,8 @@ impl SigningQueueClient { impl ParitySigning for SigningQueueClient { type Metadata = Metadata; - fn compose_transaction(&self, meta: Metadata, transaction: RpcTransactionRequest) -> BoxFuture { - let default_account = self.accounts.dapp_default_address(meta.dapp_id().into()).ok().unwrap_or_default(); + fn compose_transaction(&self, _meta: Metadata, transaction: RpcTransactionRequest) -> BoxFuture { + let default_account = self.accounts.default_account().ok().unwrap_or_default(); Box::new(self.dispatcher.fill_optional_fields(transaction.into(), default_account, true).map(Into::into)) } @@ -164,7 +163,7 @@ impl ParitySigning for SigningQueueClient { let remote = self.remote.clone(); let confirmations = self.confirmations.clone(); - Box::new(self.dispatch(RpcConfirmationPayload::SendTransaction(request), meta.dapp_id().into(), meta.origin) + Box::new(self.dispatch(RpcConfirmationPayload::SendTransaction(request), DefaultAccount::Provided(self.accounts.default_account().ok().unwrap_or_default()), meta.origin) .map(|result| match result { DispatchResult::Value(v) => RpcEither::Or(v), DispatchResult::Future(id, future) => { @@ -221,7 +220,7 @@ impl EthSigning for SigningQueueClient { fn send_transaction(&self, meta: Metadata, request: RpcTransactionRequest) -> BoxFuture { let res = self.dispatch( RpcConfirmationPayload::SendTransaction(request), - meta.dapp_id().into(), + DefaultAccount::Provided(self.accounts.default_account().ok().unwrap_or_default()), meta.origin, ); @@ -236,7 +235,7 @@ impl EthSigning for SigningQueueClient { fn sign_transaction(&self, meta: Metadata, request: RpcTransactionRequest) -> BoxFuture { let res = self.dispatch( RpcConfirmationPayload::SignTransaction(request), - meta.dapp_id().into(), + DefaultAccount::Provided(self.accounts.default_account().ok().unwrap_or_default()), meta.origin, ); diff --git a/rpc/src/v1/impls/signing_unsafe.rs b/rpc/src/v1/impls/signing_unsafe.rs index 6016cbbfc0b..c4f2117a5e1 100644 --- a/rpc/src/v1/impls/signing_unsafe.rs +++ b/rpc/src/v1/impls/signing_unsafe.rs @@ -55,7 +55,6 @@ impl SigningUnsafeClient { let accounts = self.accounts.clone(); let default = match account { DefaultAccount::Provided(acc) => acc, - DefaultAccount::ForDapp(dapp) => accounts.dapp_default_address(dapp).ok().unwrap_or_default(), }; let dis = self.dispatcher.clone(); @@ -80,8 +79,8 @@ impl EthSigning for SigningUnsafeClient })) } - fn send_transaction(&self, meta: Metadata, request: RpcTransactionRequest) -> BoxFuture { - Box::new(self.handle(RpcConfirmationPayload::SendTransaction(request), meta.dapp_id().into()) + fn send_transaction(&self, _meta: Metadata, request: RpcTransactionRequest) -> BoxFuture { + Box::new(self.handle(RpcConfirmationPayload::SendTransaction(request), DefaultAccount::Provided(self.accounts.default_account().ok().unwrap_or_default())) .then(|res| match res { Ok(RpcConfirmationResponse::SendTransaction(hash)) => Ok(hash), Err(e) => Err(e), @@ -89,8 +88,8 @@ impl EthSigning for SigningUnsafeClient })) } - fn sign_transaction(&self, meta: Metadata, request: RpcTransactionRequest) -> BoxFuture { - Box::new(self.handle(RpcConfirmationPayload::SignTransaction(request), meta.dapp_id().into()) + fn sign_transaction(&self, _meta: Metadata, request: RpcTransactionRequest) -> BoxFuture { + Box::new(self.handle(RpcConfirmationPayload::SignTransaction(request), DefaultAccount::Provided(self.accounts.default_account().ok().unwrap_or_default())) .then(|res| match res { Ok(RpcConfirmationResponse::SignTransaction(tx)) => Ok(tx), Err(e) => Err(e), @@ -102,9 +101,9 @@ impl EthSigning for SigningUnsafeClient impl ParitySigning for SigningUnsafeClient { type Metadata = Metadata; - fn compose_transaction(&self, meta: Metadata, transaction: RpcTransactionRequest) -> BoxFuture { + fn compose_transaction(&self, _meta: Metadata, transaction: RpcTransactionRequest) -> BoxFuture { let accounts = self.accounts.clone(); - let default_account = accounts.dapp_default_address(meta.dapp_id().into()).ok().unwrap_or_default(); + let default_account = accounts.default_account().ok().unwrap_or_default(); Box::new(self.dispatcher.fill_optional_fields(transaction.into(), default_account, true).map(Into::into)) } diff --git a/rpc/src/v1/metadata.rs b/rpc/src/v1/metadata.rs index 970ec60e486..2dc4c557d46 100644 --- a/rpc/src/v1/metadata.rs +++ b/rpc/src/v1/metadata.rs @@ -20,7 +20,7 @@ use std::sync::Arc; use jsonrpc_core; use jsonrpc_pubsub::{Session, PubSubMetadata}; -use v1::types::{DappId, Origin}; +use v1::types::Origin; /// RPC methods metadata. #[derive(Clone, Default, Debug)] @@ -32,24 +32,9 @@ pub struct Metadata { } impl Metadata { - /// Returns dapp id if this request is coming from a Dapp or default `DappId` otherwise. - pub fn dapp_id(&self) -> DappId { - // TODO [ToDr] Extract dapp info from Ws connections. - match self.origin { - Origin::Dapps(ref dapp) => dapp.clone(), - Origin::Ws { ref dapp, .. } => dapp.clone(), - Origin::Signer { ref dapp, .. } => dapp.clone(), - _ => DappId::default(), - } - } - /// Returns true if the request originates from a Dapp. pub fn is_dapp(&self) -> bool { - if let Origin::Dapps(_) = self.origin { - true - } else { - false - } + false } } diff --git a/rpc/src/v1/tests/mocked/eth.rs b/rpc/src/v1/tests/mocked/eth.rs index 7213ad63da4..17cad411369 100644 --- a/rpc/src/v1/tests/mocked/eth.rs +++ b/rpc/src/v1/tests/mocked/eth.rs @@ -39,7 +39,6 @@ use v1::helpers::nonce; use v1::helpers::dispatch::FullDispatcher; use v1::tests::helpers::{TestSyncProvider, Config, TestMinerService, TestSnapshotService}; use v1::metadata::Metadata; -use v1::types::Origin; fn blockchain_client() -> Arc { let client = TestBlockChainClient::new(); @@ -395,7 +394,6 @@ fn rpc_eth_gas_price() { fn rpc_eth_accounts() { let tester = EthTester::default(); let address = tester.accounts_provider.new_account(&"".into()).unwrap(); - tester.accounts_provider.set_new_dapps_addresses(None).unwrap(); tester.accounts_provider.set_address_name(1.into(), "1".into()); tester.accounts_provider.set_address_name(10.into(), "10".into()); @@ -404,18 +402,15 @@ fn rpc_eth_accounts() { let response = r#"{"jsonrpc":"2.0","result":[""#.to_owned() + &format!("0x{:x}", address) + r#""],"id":1}"#; assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned())); - tester.accounts_provider.set_new_dapps_addresses(Some(vec![1.into()])).unwrap(); // even with some account it should return empty list (no dapp detected) let request = r#"{"jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1}"#; let response = r#"{"jsonrpc":"2.0","result":["0x0000000000000000000000000000000000000001"],"id":1}"#; assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned())); // when we add visible address it should return that. - tester.accounts_provider.set_dapp_addresses("app1".into(), Some(vec![10.into()])).unwrap(); let request = r#"{"jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1}"#; let response = r#"{"jsonrpc":"2.0","result":["0x000000000000000000000000000000000000000a"],"id":1}"#; - let mut meta = Metadata::default(); - meta.origin = Origin::Dapps("app1".into()); + let meta = Metadata::default(); assert_eq!((*tester.io).handle_request_sync(request, meta), Some(response.to_owned())); } diff --git a/rpc/src/v1/tests/mocked/parity.rs b/rpc/src/v1/tests/mocked/parity.rs index ca241140640..3f8dfd80102 100644 --- a/rpc/src/v1/tests/mocked/parity.rs +++ b/rpc/src/v1/tests/mocked/parity.rs @@ -134,7 +134,6 @@ fn rpc_parity_accounts_info() { // Change the whitelist let address = Address::from(1); - deps.accounts.set_new_dapps_addresses(Some(vec![address.clone()])).unwrap(); let request = r#"{"jsonrpc": "2.0", "method": "parity_accountsInfo", "params": [], "id": 1}"#; let response = format!("{{\"jsonrpc\":\"2.0\",\"result\":{{\"0x{:x}\":{{\"name\":\"XX\"}}}},\"id\":1}}", address); assert_eq!(io.handle_request_sync(request), Some(response)); diff --git a/rpc/src/v1/tests/mocked/parity_accounts.rs b/rpc/src/v1/tests/mocked/parity_accounts.rs index 699ba01f8ed..4a1f72173bd 100644 --- a/rpc/src/v1/tests/mocked/parity_accounts.rs +++ b/rpc/src/v1/tests/mocked/parity_accounts.rs @@ -121,106 +121,6 @@ fn should_be_able_to_set_meta() { assert_eq!(res, Some(response)); } -#[test] -fn rpc_parity_set_and_get_dapps_accounts() { - // given - let tester = setup(); - tester.accounts.set_address_name(10.into(), "10".into()); - assert_eq!(tester.accounts.dapp_addresses("app1".into()).unwrap(), vec![]); - - // when - let request = r#"{"jsonrpc": "2.0", "method": "parity_setDappAddresses","params":["app1",["0x000000000000000000000000000000000000000a","0x0000000000000000000000000000000000000001"]], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#; - assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned())); - - // then - assert_eq!(tester.accounts.dapp_addresses("app1".into()).unwrap(), vec![10.into()]); - let request = r#"{"jsonrpc": "2.0", "method": "parity_getDappAddresses","params":["app1"], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","result":["0x000000000000000000000000000000000000000a"],"id":1}"#; - assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned())); -} - -#[test] -fn rpc_parity_set_and_get_dapp_default_address() { - // given - let tester = setup(); - tester.accounts.set_address_name(10.into(), "10".into()); - assert_eq!(tester.accounts.dapp_addresses("app1".into()).unwrap(), vec![]); - - // when - let request = r#"{"jsonrpc": "2.0", "method": "parity_setDappDefaultAddress","params":["app1", "0x000000000000000000000000000000000000000a"], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#; - assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned())); - - // then - assert_eq!(tester.accounts.dapp_addresses("app1".into()).unwrap(), vec![10.into()]); - let request = r#"{"jsonrpc": "2.0", "method": "parity_getDappDefaultAddress","params":["app1"], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","result":"0x000000000000000000000000000000000000000a","id":1}"#; - assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned())); -} - -#[test] -fn rpc_parity_set_and_get_new_dapps_whitelist() { - // given - let tester = setup(); - - // when set to whitelist - let request = r#"{"jsonrpc": "2.0", "method": "parity_setNewDappsAddresses","params":[["0x000000000000000000000000000000000000000a"]], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#; - assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned())); - - // then - assert_eq!(tester.accounts.new_dapps_addresses().unwrap(), Some(vec![10.into()])); - let request = r#"{"jsonrpc": "2.0", "method": "parity_getNewDappsAddresses","params":[], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","result":["0x000000000000000000000000000000000000000a"],"id":1}"#; - assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned())); - - // when set to empty - let request = r#"{"jsonrpc": "2.0", "method": "parity_setNewDappsAddresses","params":[null], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#; - assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned())); - - // then - assert_eq!(tester.accounts.new_dapps_addresses().unwrap(), None); - let request = r#"{"jsonrpc": "2.0", "method": "parity_getNewDappsAddresses","params":[], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","result":null,"id":1}"#; - assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned())); -} - -#[test] -fn rpc_parity_set_and_get_new_dapps_default_address() { - // given - let tester = setup(); - tester.accounts.set_address_name(10.into(), "10".into()); - assert_eq!(tester.accounts.new_dapps_default_address().unwrap(), 0.into()); - - // when - let request = r#"{"jsonrpc": "2.0", "method": "parity_setNewDappsDefaultAddress","params":["0x000000000000000000000000000000000000000a"], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#; - assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned())); - - // then - assert_eq!(tester.accounts.new_dapps_default_address().unwrap(), 10.into()); - let request = r#"{"jsonrpc": "2.0", "method": "parity_getNewDappsDefaultAddress","params":[], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","result":"0x000000000000000000000000000000000000000a","id":1}"#; - assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned())); -} - -#[test] -fn rpc_parity_recent_dapps() { - // given - let tester = setup(); - - // when - // trigger dapp usage - tester.accounts.note_dapp_used("dapp1".into()).unwrap(); - - // then - let request = r#"{"jsonrpc": "2.0", "method": "parity_listRecentDapps","params":[], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","result":{"dapp1":1},"id":1}"#; - assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned())); -} - #[test] fn should_be_able_to_kill_account() { let tester = setup(); diff --git a/rpc/src/v1/tests/mocked/signer.rs b/rpc/src/v1/tests/mocked/signer.rs index 52d5f7d8d35..c6674dc0b7c 100644 --- a/rpc/src/v1/tests/mocked/signer.rs +++ b/rpc/src/v1/tests/mocked/signer.rs @@ -89,7 +89,7 @@ fn should_return_list_of_items_to_confirm() { data: vec![], nonce: None, condition: None, - }), Origin::Dapps("http://parity.io".into())).unwrap(); + }), Origin::Unknown).unwrap(); let _sign_future = tester.signer.add_request(ConfirmationPayload::EthSignMessage(1.into(), vec![5].into()), Origin::Unknown).unwrap(); // when diff --git a/rpc/src/v1/traits/parity.rs b/rpc/src/v1/traits/parity.rs index 2f2eef90741..d1d3bd4ea16 100644 --- a/rpc/src/v1/traits/parity.rs +++ b/rpc/src/v1/traits/parity.rs @@ -27,7 +27,7 @@ use v1::types::{ Peers, Transaction, RpcSettings, Histogram, TransactionStats, LocalTransactionStatus, BlockNumber, ConsensusCapability, VersionInfo, - OperationsInfo, DappId, ChainStatus, + OperationsInfo, ChainStatus, AccountInfo, HwAccountInfo, RichHeader, }; @@ -38,7 +38,7 @@ build_rpc_trait! { /// Returns accounts information. #[rpc(name = "parity_accountsInfo")] - fn accounts_info(&self, Trailing) -> Result>; + fn accounts_info(&self) -> Result>; /// Returns hardware accounts information. #[rpc(name = "parity_hardwareAccountsInfo")] diff --git a/rpc/src/v1/traits/parity_accounts.rs b/rpc/src/v1/traits/parity_accounts.rs index c7bc21771b8..029f06bf2ff 100644 --- a/rpc/src/v1/traits/parity_accounts.rs +++ b/rpc/src/v1/traits/parity_accounts.rs @@ -20,7 +20,7 @@ use std::collections::BTreeMap; use jsonrpc_core::Result; use ethkey::Password; use ethstore::KeyFile; -use v1::types::{H160, H256, H520, DappId, DeriveHash, DeriveHierarchical, ExtAccountInfo}; +use v1::types::{H160, H256, H520, DeriveHash, DeriveHierarchical, ExtAccountInfo}; build_rpc_trait! { /// Personal Parity rpc interface. @@ -72,57 +72,6 @@ build_rpc_trait! { #[rpc(name = "parity_setAccountMeta")] fn set_account_meta(&self, H160, String) -> Result; - /// Sets addresses exposed for particular dapp. - /// Setting a non-empty list will also override default account. - /// Setting `None` will resets visible account to what's visible for new dapps - /// (does not affect default account though) - #[rpc(name = "parity_setDappAddresses")] - fn set_dapp_addresses(&self, DappId, Option>) -> Result; - - /// Gets accounts exposed for particular dapp. - #[rpc(name = "parity_getDappAddresses")] - fn dapp_addresses(&self, DappId) -> Result>; - - /// Changes dapp default address. - /// Does not affect other accounts exposed for this dapp, but - /// default account will always be retured as the first one. - #[rpc(name = "parity_setDappDefaultAddress")] - fn set_dapp_default_address(&self, DappId, H160) -> Result; - - /// Returns current dapp default address. - /// If not set explicite for the dapp will return global default. - #[rpc(name = "parity_getDappDefaultAddress")] - fn dapp_default_address(&self, DappId) -> Result; - - /// Sets accounts exposed for new dapps. - /// Setting a non-empty list will also override default account. - /// Setting `None` exposes all internal-managed accounts. - /// (does not affect default account though) - #[rpc(name = "parity_setNewDappsAddresses")] - fn set_new_dapps_addresses(&self, Option>) -> Result; - - /// Gets accounts exposed for new dapps. - /// `None` means that all accounts are exposes. - #[rpc(name = "parity_getNewDappsAddresses")] - fn new_dapps_addresses(&self) -> Result>>; - - /// Changes default address for new dapps (global default address) - /// Does not affect other accounts exposed for new dapps, but - /// default account will always be retured as the first one. - #[rpc(name = "parity_setNewDappsDefaultAddress")] - fn set_new_dapps_default_address(&self, H160) -> Result; - - /// Returns current default address for new dapps (global default address) - /// In case it's not set explicite will return first available account. - /// If no accounts are available will return `0x0` - #[rpc(name = "parity_getNewDappsDefaultAddress")] - fn new_dapps_default_address(&self) -> Result; - - /// Returns identified dapps that recently used RPC - /// Includes last usage timestamp. - #[rpc(name = "parity_listRecentDapps")] - fn recent_dapps(&self) -> Result>; - /// Imports a number of Geth accounts, with the list provided as the argument. #[rpc(name = "parity_importGethAccounts")] fn import_geth_accounts(&self, Vec) -> Result>; diff --git a/rpc/src/v1/types/confirmations.rs b/rpc/src/v1/types/confirmations.rs index 477546aa4f9..72851a554e4 100644 --- a/rpc/src/v1/types/confirmations.rs +++ b/rpc/src/v1/types/confirmations.rs @@ -285,7 +285,6 @@ mod tests { condition: None, }), origin: Origin::Signer { - dapp: "http://parity.io".into(), session: 5.into(), } }; @@ -314,7 +313,7 @@ mod tests { nonce: Some(1.into()), condition: None, }), - origin: Origin::Dapps("http://parity.io".into()), + origin: Origin::Unknown, }; // when diff --git a/rpc/src/v1/types/mod.rs b/rpc/src/v1/types/mod.rs index 0f21e2f7b5b..fe35dd50a09 100644 --- a/rpc/src/v1/types/mod.rs +++ b/rpc/src/v1/types/mod.rs @@ -63,7 +63,7 @@ pub use self::histogram::Histogram; pub use self::index::Index; pub use self::log::Log; pub use self::node_kind::{NodeKind, Availability, Capability}; -pub use self::provenance::{Origin, DappId}; +pub use self::provenance::Origin; pub use self::receipt::Receipt; pub use self::rpc_settings::RpcSettings; pub use self::secretstore::EncryptedDocumentKey; diff --git a/rpc/src/v1/types/provenance.rs b/rpc/src/v1/types/provenance.rs index 328f2ded3e6..b2112129f03 100644 --- a/rpc/src/v1/types/provenance.rs +++ b/rpc/src/v1/types/provenance.rs @@ -17,7 +17,6 @@ //! Request Provenance use std::fmt; -use ethcore::account_provider::DappId as EthDappId; use v1::types::H256; /// RPC request origin @@ -27,25 +26,18 @@ pub enum Origin { /// RPC server (includes request origin) #[serde(rename="rpc")] Rpc(String), - /// Dapps server (includes DappId) - #[serde(rename="dapp")] - Dapps(DappId), /// IPC server (includes session hash) #[serde(rename="ipc")] Ipc(H256), /// WS server #[serde(rename="ws")] Ws { - /// Dapp id - dapp: DappId, /// Session id session: H256, }, /// Signer (authorized WS server) #[serde(rename="signer")] Signer { - /// Dapp id - dapp: DappId, /// Session id session: H256 }, @@ -67,80 +59,35 @@ impl fmt::Display for Origin { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Origin::Rpc(ref origin) => write!(f, "{} via RPC", origin), - Origin::Dapps(ref origin) => write!(f, "Dapp {}", origin), Origin::Ipc(ref session) => write!(f, "IPC (session: {})", session), - Origin::Ws { ref session, ref dapp } => write!(f, "{} via WebSocket (session: {})", dapp, session), - Origin::Signer { ref session, ref dapp } => write!(f, "{} via UI (session: {})", dapp, session), + Origin::Ws { ref session } => write!(f, "WebSocket (session: {})", session), + Origin::Signer { ref session } => write!(f, "Signer (session: {})", session), Origin::CApi => write!(f, "C API"), Origin::Unknown => write!(f, "unknown origin"), } } } -/// Dapplication Internal Id -#[derive(Debug, Default, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Serialize, Deserialize)] -pub struct DappId(pub String); - -impl fmt::Display for DappId { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.0) - } -} - -impl Into for DappId { - fn into(self) -> String { - self.0 - } -} - -impl From for DappId { - fn from(s: String) -> Self { - DappId(s) - } -} - -impl<'a> From<&'a str> for DappId { - fn from(s: &'a str) -> Self { - DappId(s.to_owned()) - } -} - -impl From for DappId { - fn from(id: EthDappId) -> Self { - DappId(id.into()) - } -} - -impl Into for DappId { - fn into(self) -> EthDappId { - Into::::into(self).into() - } -} - #[cfg(test)] mod tests { use serde_json; - use super::{DappId, Origin}; + use super::Origin; #[test] fn should_serialize_origin() { // given let o1 = Origin::Rpc("test service".into()); - let o2 = Origin::Dapps("http://parity.io".into()); let o3 = Origin::Ipc(5.into()); let o4 = Origin::Signer { - dapp: "http://parity.io".into(), session: 10.into(), }; let o5 = Origin::Unknown; let o6 = Origin::Ws { - dapp: "http://parity.io".into(), session: 5.into(), }; // when let res1 = serde_json::to_string(&o1).unwrap(); - let res2 = serde_json::to_string(&o2).unwrap(); let res3 = serde_json::to_string(&o3).unwrap(); let res4 = serde_json::to_string(&o4).unwrap(); let res5 = serde_json::to_string(&o5).unwrap(); @@ -148,34 +95,9 @@ mod tests { // then assert_eq!(res1, r#"{"rpc":"test service"}"#); - assert_eq!(res2, r#"{"dapp":"http://parity.io"}"#); assert_eq!(res3, r#"{"ipc":"0x0000000000000000000000000000000000000000000000000000000000000005"}"#); assert_eq!(res4, r#"{"signer":{"dapp":"http://parity.io","session":"0x000000000000000000000000000000000000000000000000000000000000000a"}}"#); assert_eq!(res5, r#""unknown""#); assert_eq!(res6, r#"{"ws":{"dapp":"http://parity.io","session":"0x0000000000000000000000000000000000000000000000000000000000000005"}}"#); } - - #[test] - fn should_serialize_dapp_id() { - // given - let id = DappId("testapp".into()); - - // when - let res = serde_json::to_string(&id).unwrap(); - - // then - assert_eq!(res, r#""testapp""#); - } - - #[test] - fn should_deserialize_dapp_id() { - // given - let id = r#""testapp""#; - - // when - let res: DappId = serde_json::from_str(id).unwrap(); - - // then - assert_eq!(res, DappId("testapp".into())); - } } From f21b14baf11c66b7f0f2e2b8b15f603e3e680452 Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Sat, 14 Jul 2018 00:05:12 +0800 Subject: [PATCH 5/9] Fix rpc tests --- rpc/src/tests/rpc.rs | 55 ------------------------------- rpc/src/v1/tests/mocked/eth.rs | 11 ------- rpc/src/v1/tests/mocked/parity.rs | 6 ---- rpc/src/v1/tests/mocked/signer.rs | 2 +- rpc/src/v1/types/confirmations.rs | 4 +-- rpc/src/v1/types/provenance.rs | 4 +-- 6 files changed, 5 insertions(+), 77 deletions(-) diff --git a/rpc/src/tests/rpc.rs b/rpc/src/tests/rpc.rs index d15aeca6cb0..f1a2499597b 100644 --- a/rpc/src/tests/rpc.rs +++ b/rpc/src/tests/rpc.rs @@ -116,59 +116,4 @@ mod testsing { res.assert_status("HTTP/1.1 200 OK"); assert_eq!(res.body, expected); } - - #[test] - fn should_extract_dapp_origin() { - // given - let (server, address) = serve(); - - // when - let req = r#"{"method":"hello","params":[],"jsonrpc":"2.0","id":1}"#; - let expected = "3A\n{\"jsonrpc\":\"2.0\",\"result\":\"Dapp http://parity.io\",\"id\":1}\n\n0\n\n"; - let res = request(server, - &format!("\ - POST / HTTP/1.1\r\n\ - Host: {}\r\n\ - Content-Type: application/json\r\n\ - Content-Length: {}\r\n\ - Origin: http://parity.io\r\n\ - Connection: close\r\n\ - User-Agent: curl/7.16.3\r\n\ - \r\n\ - {} - ", address, req.len(), req) - ); - - // then - res.assert_status("HTTP/1.1 200 OK"); - assert_eq!(res.body, expected); - } - - #[test] - fn should_extract_dapp_origin_from_extension() { - // given - let (server, address) = serve(); - - // when - let req = r#"{"method":"hello","params":[],"jsonrpc":"2.0","id":1}"#; - let expected = "44\n{\"jsonrpc\":\"2.0\",\"result\":\"Dapp http://wallet.ethereum.org\",\"id\":1}\n\n0\n\n"; - let res = request(server, - &format!("\ - POST / HTTP/1.1\r\n\ - Host: {}\r\n\ - Content-Type: application/json\r\n\ - Content-Length: {}\r\n\ - Origin: null\r\n\ - X-Parity-Origin: http://wallet.ethereum.org\r\n\ - Connection: close\r\n\ - User-Agent: curl/7.16.3\r\n\ - \r\n\ - {} - ", address, req.len(), req) - ); - - // then - res.assert_status("HTTP/1.1 200 OK"); - assert_eq!(res.body, expected); - } } diff --git a/rpc/src/v1/tests/mocked/eth.rs b/rpc/src/v1/tests/mocked/eth.rs index 17cad411369..60262119430 100644 --- a/rpc/src/v1/tests/mocked/eth.rs +++ b/rpc/src/v1/tests/mocked/eth.rs @@ -401,17 +401,6 @@ fn rpc_eth_accounts() { let request = r#"{"jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1}"#; let response = r#"{"jsonrpc":"2.0","result":[""#.to_owned() + &format!("0x{:x}", address) + r#""],"id":1}"#; assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned())); - - // even with some account it should return empty list (no dapp detected) - let request = r#"{"jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","result":["0x0000000000000000000000000000000000000001"],"id":1}"#; - assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned())); - - // when we add visible address it should return that. - let request = r#"{"jsonrpc": "2.0", "method": "eth_accounts", "params": [], "id": 1}"#; - let response = r#"{"jsonrpc":"2.0","result":["0x000000000000000000000000000000000000000a"],"id":1}"#; - let meta = Metadata::default(); - assert_eq!((*tester.io).handle_request_sync(request, meta), Some(response.to_owned())); } #[test] diff --git a/rpc/src/v1/tests/mocked/parity.rs b/rpc/src/v1/tests/mocked/parity.rs index 3f8dfd80102..46af6bf01d5 100644 --- a/rpc/src/v1/tests/mocked/parity.rs +++ b/rpc/src/v1/tests/mocked/parity.rs @@ -131,12 +131,6 @@ fn rpc_parity_accounts_info() { let request = r#"{"jsonrpc": "2.0", "method": "parity_accountsInfo", "params": [], "id": 1}"#; let response = format!("{{\"jsonrpc\":\"2.0\",\"result\":{{\"0x{:x}\":{{\"name\":\"Test\"}}}},\"id\":1}}", address); assert_eq!(io.handle_request_sync(request), Some(response)); - - // Change the whitelist - let address = Address::from(1); - let request = r#"{"jsonrpc": "2.0", "method": "parity_accountsInfo", "params": [], "id": 1}"#; - let response = format!("{{\"jsonrpc\":\"2.0\",\"result\":{{\"0x{:x}\":{{\"name\":\"XX\"}}}},\"id\":1}}", address); - assert_eq!(io.handle_request_sync(request), Some(response)); } #[test] diff --git a/rpc/src/v1/tests/mocked/signer.rs b/rpc/src/v1/tests/mocked/signer.rs index c6674dc0b7c..430fb4fc211 100644 --- a/rpc/src/v1/tests/mocked/signer.rs +++ b/rpc/src/v1/tests/mocked/signer.rs @@ -96,7 +96,7 @@ fn should_return_list_of_items_to_confirm() { let request = r#"{"jsonrpc":"2.0","method":"signer_requestsToConfirm","params":[],"id":1}"#; let response = concat!( r#"{"jsonrpc":"2.0","result":["#, - r#"{"id":"0x1","origin":{"dapp":"http://parity.io"},"payload":{"sendTransaction":{"condition":null,"data":"0x","from":"0x0000000000000000000000000000000000000001","gas":"0x989680","gasPrice":"0x2710","nonce":null,"to":"0xd46e8dd67c5d32be8058bb8eb970870f07244567","value":"0x1"}}},"#, + r#"{"id":"0x1","origin":"unknown","payload":{"sendTransaction":{"condition":null,"data":"0x","from":"0x0000000000000000000000000000000000000001","gas":"0x989680","gasPrice":"0x2710","nonce":null,"to":"0xd46e8dd67c5d32be8058bb8eb970870f07244567","value":"0x1"}}},"#, r#"{"id":"0x2","origin":"unknown","payload":{"sign":{"address":"0x0000000000000000000000000000000000000001","data":"0x05"}}}"#, r#"],"id":1}"# ); diff --git a/rpc/src/v1/types/confirmations.rs b/rpc/src/v1/types/confirmations.rs index 72851a554e4..e5da13298ea 100644 --- a/rpc/src/v1/types/confirmations.rs +++ b/rpc/src/v1/types/confirmations.rs @@ -291,7 +291,7 @@ mod tests { // when let res = serde_json::to_string(&ConfirmationRequest::from(request)); - let expected = r#"{"id":"0xf","payload":{"sendTransaction":{"from":"0x0000000000000000000000000000000000000000","to":null,"gasPrice":"0x2710","gas":"0x3a98","value":"0x186a0","data":"0x010203","nonce":"0x1","condition":null}},"origin":{"signer":{"dapp":"http://parity.io","session":"0x0000000000000000000000000000000000000000000000000000000000000005"}}}"#; + let expected = r#"{"id":"0xf","payload":{"sendTransaction":{"from":"0x0000000000000000000000000000000000000000","to":null,"gasPrice":"0x2710","gas":"0x3a98","value":"0x186a0","data":"0x010203","nonce":"0x1","condition":null}},"origin":{"signer":{"session":"0x0000000000000000000000000000000000000000000000000000000000000005"}}}"#; // then assert_eq!(res.unwrap(), expected.to_owned()); @@ -318,7 +318,7 @@ mod tests { // when let res = serde_json::to_string(&ConfirmationRequest::from(request)); - let expected = r#"{"id":"0xf","payload":{"signTransaction":{"from":"0x0000000000000000000000000000000000000000","to":null,"gasPrice":"0x2710","gas":"0x3a98","value":"0x186a0","data":"0x010203","nonce":"0x1","condition":null}},"origin":{"dapp":"http://parity.io"}}"#; + let expected = r#"{"id":"0xf","payload":{"signTransaction":{"from":"0x0000000000000000000000000000000000000000","to":null,"gasPrice":"0x2710","gas":"0x3a98","value":"0x186a0","data":"0x010203","nonce":"0x1","condition":null}},"origin":"unknown"}"#; // then assert_eq!(res.unwrap(), expected.to_owned()); diff --git a/rpc/src/v1/types/provenance.rs b/rpc/src/v1/types/provenance.rs index b2112129f03..b86173545bc 100644 --- a/rpc/src/v1/types/provenance.rs +++ b/rpc/src/v1/types/provenance.rs @@ -96,8 +96,8 @@ mod tests { // then assert_eq!(res1, r#"{"rpc":"test service"}"#); assert_eq!(res3, r#"{"ipc":"0x0000000000000000000000000000000000000000000000000000000000000005"}"#); - assert_eq!(res4, r#"{"signer":{"dapp":"http://parity.io","session":"0x000000000000000000000000000000000000000000000000000000000000000a"}}"#); + assert_eq!(res4, r#"{"signer":{"session":"0x000000000000000000000000000000000000000000000000000000000000000a"}}"#); assert_eq!(res5, r#""unknown""#); - assert_eq!(res6, r#"{"ws":{"dapp":"http://parity.io","session":"0x0000000000000000000000000000000000000000000000000000000000000005"}}"#); + assert_eq!(res6, r#"{"ws":{"session":"0x0000000000000000000000000000000000000000000000000000000000000005"}}"#); } } From aedde18eabc18307e4718706c56ab910e89310d8 Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Tue, 24 Jul 2018 14:49:22 +0800 Subject: [PATCH 6/9] Use both origin and user_agent --- rpc/src/v1/extractors.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rpc/src/v1/extractors.rs b/rpc/src/v1/extractors.rs index 67a1c9fdfa8..2bdc107242d 100644 --- a/rpc/src/v1/extractors.rs +++ b/rpc/src/v1/extractors.rs @@ -36,9 +36,9 @@ pub struct RpcExtractor; impl HttpMetaExtractor for RpcExtractor { type Metadata = Metadata; - fn read_metadata(&self, _origin: Option, user_agent: Option, _dapps_origin: Option) -> Metadata { + fn read_metadata(&self, origin: Option, user_agent: Option, _dapps_origin: Option) -> Metadata { Metadata { - origin: match user_agent { + origin: match user_agent.or(origin) { Some(service) => Origin::Rpc(service.into()), None => Origin::Rpc("unknown".into()), }, From 6a087d9014f7a36f86c17a09213abdf5fae0555e Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Tue, 24 Jul 2018 15:09:18 +0800 Subject: [PATCH 7/9] Address grumbles --- rpc/src/http_common.rs | 5 ++--- rpc/src/v1/extractors.rs | 8 ++++---- rpc/src/v1/helpers/fake_sign.rs | 10 +++------- rpc/src/v1/impls/eth.rs | 12 ++++++------ rpc/src/v1/impls/light/eth.rs | 8 ++++---- rpc/src/v1/impls/light/parity.rs | 4 ++-- rpc/src/v1/impls/light/trace.rs | 4 ++-- rpc/src/v1/impls/parity.rs | 6 +++--- rpc/src/v1/impls/private.rs | 4 ++-- rpc/src/v1/impls/traces.rs | 8 ++++---- rpc/src/v1/metadata.rs | 7 ------- rpc/src/v1/traits/eth.rs | 16 ++++++++-------- rpc/src/v1/traits/parity.rs | 8 ++++---- rpc/src/v1/traits/private.rs | 4 ++-- rpc/src/v1/traits/traces.rs | 8 ++++---- rpc/src/v1/types/provenance.rs | 2 +- 16 files changed, 51 insertions(+), 63 deletions(-) diff --git a/rpc/src/http_common.rs b/rpc/src/http_common.rs index 8296720b20f..47717f3135c 100644 --- a/rpc/src/http_common.rs +++ b/rpc/src/http_common.rs @@ -25,7 +25,7 @@ pub trait HttpMetaExtractor: Send + Sync + 'static { /// Type of Metadata type Metadata: jsonrpc_core::Metadata; /// Extracts metadata from given params. - fn read_metadata(&self, origin: Option, user_agent: Option, dapps_origin: Option) -> Self::Metadata; + fn read_metadata(&self, origin: Option, user_agent: Option) -> Self::Metadata; } pub struct MetaExtractor { @@ -49,7 +49,6 @@ impl http::MetaExtractor for MetaExtractor where let origin = as_string(req.headers().get_raw("origin")); let user_agent = as_string(req.headers().get_raw("user-agent")); - let dapps_origin = as_string(req.headers().get_raw("x-parity-origin")); - self.extractor.read_metadata(origin, user_agent, dapps_origin) + self.extractor.read_metadata(origin, user_agent) } } diff --git a/rpc/src/v1/extractors.rs b/rpc/src/v1/extractors.rs index 2bdc107242d..009a72df6ac 100644 --- a/rpc/src/v1/extractors.rs +++ b/rpc/src/v1/extractors.rs @@ -36,7 +36,7 @@ pub struct RpcExtractor; impl HttpMetaExtractor for RpcExtractor { type Metadata = Metadata; - fn read_metadata(&self, origin: Option, user_agent: Option, _dapps_origin: Option) -> Metadata { + fn read_metadata(&self, origin: Option, user_agent: Option) -> Metadata { Metadata { origin: match user_agent.or(origin) { Some(service) => Origin::Rpc(service.into()), @@ -250,9 +250,9 @@ mod tests { let extractor = RpcExtractor; // when - let meta1 = extractor.read_metadata(None, None, None); - let meta2 = extractor.read_metadata(None, Some("http://parity.io".to_owned()), None); - let meta3 = extractor.read_metadata(None, Some("http://parity.io".to_owned()), Some("ignored".into())); + let meta1 = extractor.read_metadata(None, None); + let meta2 = extractor.read_metadata(None, Some("http://parity.io".to_owned())); + let meta3 = extractor.read_metadata(None, Some("http://parity.io".to_owned())); // then assert_eq!(meta1.origin, Origin::Rpc("unknown".into())); diff --git a/rpc/src/v1/helpers/fake_sign.rs b/rpc/src/v1/helpers/fake_sign.rs index fc6aaccdd5f..2ff54e481cc 100644 --- a/rpc/src/v1/helpers/fake_sign.rs +++ b/rpc/src/v1/helpers/fake_sign.rs @@ -16,18 +16,14 @@ use transaction::{Transaction, SignedTransaction, Action}; +use ethereum_types::U256; use jsonrpc_core::Error; use v1::helpers::CallRequest; -pub fn sign_call(request: CallRequest, gas_cap: bool) -> Result { - let max_gas = 50_000_000.into(); +pub fn sign_call(request: CallRequest) -> Result { + let max_gas = U256::from(50_000_000); let gas = match request.gas { - Some(gas) if gas_cap && gas > max_gas => { - warn!("Gas limit capped to {} (from {})", max_gas, gas); - max_gas - } Some(gas) => gas, - None if gas_cap => max_gas, None => max_gas * 10, }; let from = request.from.unwrap_or(0.into()); diff --git a/rpc/src/v1/impls/eth.rs b/rpc/src/v1/impls/eth.rs index 589c9a70972..261c22eb270 100644 --- a/rpc/src/v1/impls/eth.rs +++ b/rpc/src/v1/impls/eth.rs @@ -502,7 +502,7 @@ impl Eth for EthClient< } } - fn author(&self, _meta: Metadata) -> Result { + fn author(&self) -> Result { let mut miner = self.miner.authoring_params().author; if miner == 0.into() { miner = self.accounts.accounts().ok().and_then(|a| a.get(0).cloned()).unwrap_or_default(); @@ -523,7 +523,7 @@ impl Eth for EthClient< Ok(RpcU256::from(default_gas_price(&*self.client, &*self.miner, self.options.gas_price_percentile))) } - fn accounts(&self, _meta: Metadata) -> Result> { + fn accounts(&self) -> Result> { let accounts = self.accounts.accounts() .map_err(|e| errors::account("Could not fetch accounts.", e))?; Ok(accounts.into_iter().map(Into::into).collect()) @@ -826,9 +826,9 @@ impl Eth for EthClient< self.send_raw_transaction(raw) } - fn call(&self, meta: Self::Metadata, request: CallRequest, num: Trailing) -> BoxFuture { + fn call(&self, request: CallRequest, num: Trailing) -> BoxFuture { let request = CallRequest::into(request); - let signed = try_bf!(fake_sign::sign_call(request, meta.is_dapp())); + let signed = try_bf!(fake_sign::sign_call(request)); let num = num.unwrap_or_default(); @@ -866,9 +866,9 @@ impl Eth for EthClient< )) } - fn estimate_gas(&self, meta: Self::Metadata, request: CallRequest, num: Trailing) -> BoxFuture { + fn estimate_gas(&self, request: CallRequest, num: Trailing) -> BoxFuture { let request = CallRequest::into(request); - let signed = try_bf!(fake_sign::sign_call(request, meta.is_dapp())); + let signed = try_bf!(fake_sign::sign_call(request)); let num = num.unwrap_or_default(); let (state, header) = if num == BlockNumber::Pending { diff --git a/rpc/src/v1/impls/light/eth.rs b/rpc/src/v1/impls/light/eth.rs index e9528ac6331..74e5e296ebf 100644 --- a/rpc/src/v1/impls/light/eth.rs +++ b/rpc/src/v1/impls/light/eth.rs @@ -252,7 +252,7 @@ impl Eth for EthClient { } } - fn author(&self, _meta: Self::Metadata) -> Result { + fn author(&self) -> Result { Ok(Default::default()) } @@ -271,7 +271,7 @@ impl Eth for EthClient { .unwrap_or_else(Default::default)) } - fn accounts(&self, _meta: Metadata) -> Result> { + fn accounts(&self) -> Result> { self.accounts.accounts() .map_err(|e| errors::account("Could not fetch accounts.", e)) .map(|accs| accs.into_iter().map(Into::::into).collect()) @@ -394,7 +394,7 @@ impl Eth for EthClient { self.send_raw_transaction(raw) } - fn call(&self, _meta: Self::Metadata, req: CallRequest, num: Trailing) -> BoxFuture { + fn call(&self, req: CallRequest, num: Trailing) -> BoxFuture { Box::new(self.fetcher().proved_execution(req, num).and_then(|res| { match res { Ok(exec) => Ok(exec.output.into()), @@ -403,7 +403,7 @@ impl Eth for EthClient { })) } - fn estimate_gas(&self, _meta: Self::Metadata, req: CallRequest, num: Trailing) -> BoxFuture { + fn estimate_gas(&self, req: CallRequest, num: Trailing) -> BoxFuture { // TODO: binary chop for more accurate estimates. Box::new(self.fetcher().proved_execution(req, num).and_then(|res| { match res { diff --git a/rpc/src/v1/impls/light/parity.rs b/rpc/src/v1/impls/light/parity.rs index a23613c8877..e9b03e51f98 100644 --- a/rpc/src/v1/impls/light/parity.rs +++ b/rpc/src/v1/impls/light/parity.rs @@ -139,7 +139,7 @@ impl Parity for ParityClient { Ok(store.locked_hardware_accounts().map_err(|e| errors::account("Error communicating with hardware wallet.", e))?) } - fn default_account(&self, _meta: Self::Metadata) -> Result { + fn default_account(&self) -> Result { Ok(self.accounts .accounts() .ok() @@ -425,7 +425,7 @@ impl Parity for ParityClient { ipfs::cid(content) } - fn call(&self, _meta: Self::Metadata, _requests: Vec, _block: Trailing) -> Result> { + fn call(&self, _requests: Vec, _block: Trailing) -> Result> { Err(errors::light_unimplemented(None)) } diff --git a/rpc/src/v1/impls/light/trace.rs b/rpc/src/v1/impls/light/trace.rs index 80cc63a4083..483b193653c 100644 --- a/rpc/src/v1/impls/light/trace.rs +++ b/rpc/src/v1/impls/light/trace.rs @@ -46,11 +46,11 @@ impl Traces for TracesClient { Err(errors::light_unimplemented(None)) } - fn call(&self, _meta: Self::Metadata, _request: CallRequest, _flags: TraceOptions, _block: Trailing) -> Result { + fn call(&self, _request: CallRequest, _flags: TraceOptions, _block: Trailing) -> Result { Err(errors::light_unimplemented(None)) } - fn call_many(&self, _meta: Self::Metadata, _request: Vec<(CallRequest, TraceOptions)>, _block: Trailing) -> Result> { + fn call_many(&self, _request: Vec<(CallRequest, TraceOptions)>, _block: Trailing) -> Result> { Err(errors::light_unimplemented(None)) } diff --git a/rpc/src/v1/impls/parity.rs b/rpc/src/v1/impls/parity.rs index fe2db73936d..525e3347acb 100644 --- a/rpc/src/v1/impls/parity.rs +++ b/rpc/src/v1/impls/parity.rs @@ -140,7 +140,7 @@ impl Parity for ParityClient where self.accounts.locked_hardware_accounts().map_err(|e| errors::account("Error communicating with hardware wallet.", e)) } - fn default_account(&self, _meta: Self::Metadata) -> Result { + fn default_account(&self) -> Result { Ok(self.accounts.default_account() .map(Into::into) .ok() @@ -424,11 +424,11 @@ impl Parity for ParityClient where ipfs::cid(content) } - fn call(&self, meta: Self::Metadata, requests: Vec, num: Trailing) -> Result> { + fn call(&self, requests: Vec, num: Trailing) -> Result> { let requests = requests .into_iter() .map(|request| Ok(( - fake_sign::sign_call(request.into(), meta.is_dapp())?, + fake_sign::sign_call(request.into())?, Default::default() ))) .collect::>>()?; diff --git a/rpc/src/v1/impls/private.rs b/rpc/src/v1/impls/private.rs index a1110eed113..247fb1aa1c7 100644 --- a/rpc/src/v1/impls/private.rs +++ b/rpc/src/v1/impls/private.rs @@ -100,14 +100,14 @@ impl Private for PrivateClient { }) } - fn private_call(&self, meta: Self::Metadata, block_number: BlockNumber, request: CallRequest) -> Result { + fn private_call(&self, block_number: BlockNumber, request: CallRequest) -> Result { let id = match block_number { BlockNumber::Pending => return Err(errors::private_message_block_id_not_supported()), num => block_number_to_id(num) }; let request = CallRequest::into(request); - let signed = fake_sign::sign_call(request, meta.is_dapp())?; + let signed = fake_sign::sign_call(request)?; let client = self.unwrap_manager()?; let executed_result = client.private_call(id, &signed).map_err(|e| errors::private_message(e))?; Ok(executed_result.output.into()) diff --git a/rpc/src/v1/impls/traces.rs b/rpc/src/v1/impls/traces.rs index ee7d7154cb5..3abddd2f97d 100644 --- a/rpc/src/v1/impls/traces.rs +++ b/rpc/src/v1/impls/traces.rs @@ -87,11 +87,11 @@ impl Traces for TracesClient where .map(LocalizedTrace::from)) } - fn call(&self, meta: Self::Metadata, request: CallRequest, flags: TraceOptions, block: Trailing) -> Result { + fn call(&self, request: CallRequest, flags: TraceOptions, block: Trailing) -> Result { let block = block.unwrap_or_default(); let request = CallRequest::into(request); - let signed = fake_sign::sign_call(request, meta.is_dapp())?; + let signed = fake_sign::sign_call(request)?; let id = match block { BlockNumber::Num(num) => BlockId::Number(num), @@ -109,13 +109,13 @@ impl Traces for TracesClient where .map_err(errors::call) } - fn call_many(&self, meta: Self::Metadata, requests: Vec<(CallRequest, TraceOptions)>, block: Trailing) -> Result> { + fn call_many(&self, requests: Vec<(CallRequest, TraceOptions)>, block: Trailing) -> Result> { let block = block.unwrap_or_default(); let requests = requests.into_iter() .map(|(request, flags)| { let request = CallRequest::into(request); - let signed = fake_sign::sign_call(request, meta.is_dapp())?; + let signed = fake_sign::sign_call(request)?; Ok((signed, to_call_analytics(flags))) }) .collect::>>()?; diff --git a/rpc/src/v1/metadata.rs b/rpc/src/v1/metadata.rs index 2dc4c557d46..10486f496c8 100644 --- a/rpc/src/v1/metadata.rs +++ b/rpc/src/v1/metadata.rs @@ -31,13 +31,6 @@ pub struct Metadata { pub session: Option>, } -impl Metadata { - /// Returns true if the request originates from a Dapp. - pub fn is_dapp(&self) -> bool { - false - } -} - impl jsonrpc_core::Metadata for Metadata {} impl PubSubMetadata for Metadata { fn session(&self) -> Option> { diff --git a/rpc/src/v1/traits/eth.rs b/rpc/src/v1/traits/eth.rs index 48e315ce7e9..a11b8680635 100644 --- a/rpc/src/v1/traits/eth.rs +++ b/rpc/src/v1/traits/eth.rs @@ -40,8 +40,8 @@ build_rpc_trait! { fn hashrate(&self) -> Result; /// Returns block author. - #[rpc(meta, name = "eth_coinbase")] - fn author(&self, Self::Metadata) -> Result; + #[rpc(name = "eth_coinbase")] + fn author(&self) -> Result; /// Returns true if client is actively mining new blocks. #[rpc(name = "eth_mining")] @@ -52,8 +52,8 @@ build_rpc_trait! { fn gas_price(&self) -> Result; /// Returns accounts list. - #[rpc(meta, name = "eth_accounts")] - fn accounts(&self, Self::Metadata) -> Result>; + #[rpc(name = "eth_accounts")] + fn accounts(&self) -> Result>; /// Returns highest block number. #[rpc(name = "eth_blockNumber")] @@ -108,12 +108,12 @@ build_rpc_trait! { fn submit_transaction(&self, Bytes) -> Result; /// Call contract, returning the output data. - #[rpc(meta, name = "eth_call")] - fn call(&self, Self::Metadata, CallRequest, Trailing) -> BoxFuture; + #[rpc(name = "eth_call")] + fn call(&self, CallRequest, Trailing) -> BoxFuture; /// Estimate gas needed for execution of given contract. - #[rpc(meta, name = "eth_estimateGas")] - fn estimate_gas(&self, Self::Metadata, CallRequest, Trailing) -> BoxFuture; + #[rpc(name = "eth_estimateGas")] + fn estimate_gas(&self, CallRequest, Trailing) -> BoxFuture; /// Get transaction by its hash. #[rpc(name = "eth_getTransactionByHash")] diff --git a/rpc/src/v1/traits/parity.rs b/rpc/src/v1/traits/parity.rs index d1d3bd4ea16..cd61290830a 100644 --- a/rpc/src/v1/traits/parity.rs +++ b/rpc/src/v1/traits/parity.rs @@ -49,8 +49,8 @@ build_rpc_trait! { fn locked_hardware_accounts_info(&self) -> Result>; /// Returns default account for dapp. - #[rpc(meta, name = "parity_defaultAccount")] - fn default_account(&self, Self::Metadata) -> Result; + #[rpc(name = "parity_defaultAccount")] + fn default_account(&self) -> Result; /// Returns current transactions limit. #[rpc(name = "parity_transactionsLimit")] @@ -217,8 +217,8 @@ build_rpc_trait! { fn ipfs_cid(&self, Bytes) -> Result; /// Call contract, returning the output data. - #[rpc(meta, name = "parity_call")] - fn call(&self, Self::Metadata, Vec, Trailing) -> Result>; + #[rpc(name = "parity_call")] + fn call(&self, Vec, Trailing) -> Result>; /// Returns node's health report. #[rpc(name = "parity_nodeHealth")] diff --git a/rpc/src/v1/traits/private.rs b/rpc/src/v1/traits/private.rs index b7b1aa20a78..fdc28a817b4 100644 --- a/rpc/src/v1/traits/private.rs +++ b/rpc/src/v1/traits/private.rs @@ -35,8 +35,8 @@ build_rpc_trait! { fn compose_deployment_transaction(&self, BlockNumber, Bytes, Vec, U256) -> Result; /// Make a call to the private contract - #[rpc(meta, name = "private_call")] - fn private_call(&self, Self::Metadata, BlockNumber, CallRequest) -> Result; + #[rpc(name = "private_call")] + fn private_call(&self, BlockNumber, CallRequest) -> Result; /// Retrieve the id of the key associated with the contract #[rpc(name = "private_contractKey")] diff --git a/rpc/src/v1/traits/traces.rs b/rpc/src/v1/traits/traces.rs index 91d46086497..00572ce38db 100644 --- a/rpc/src/v1/traits/traces.rs +++ b/rpc/src/v1/traits/traces.rs @@ -42,12 +42,12 @@ build_rpc_trait! { fn block_traces(&self, BlockNumber) -> Result>>; /// Executes the given call and returns a number of possible traces for it. - #[rpc(meta, name = "trace_call")] - fn call(&self, Self::Metadata, CallRequest, TraceOptions, Trailing) -> Result; + #[rpc(name = "trace_call")] + fn call(&self, CallRequest, TraceOptions, Trailing) -> Result; /// Executes all given calls and returns a number of possible traces for each of it. - #[rpc(meta, name = "trace_callMany")] - fn call_many(&self, Self::Metadata, Vec<(CallRequest, TraceOptions)>, Trailing) -> Result>; + #[rpc(name = "trace_callMany")] + fn call_many(&self, Vec<(CallRequest, TraceOptions)>, Trailing) -> Result>; /// Executes the given raw transaction and returns a number of possible traces for it. #[rpc(name = "trace_rawTransaction")] diff --git a/rpc/src/v1/types/provenance.rs b/rpc/src/v1/types/provenance.rs index b86173545bc..55e25f0da6f 100644 --- a/rpc/src/v1/types/provenance.rs +++ b/rpc/src/v1/types/provenance.rs @@ -61,7 +61,7 @@ impl fmt::Display for Origin { Origin::Rpc(ref origin) => write!(f, "{} via RPC", origin), Origin::Ipc(ref session) => write!(f, "IPC (session: {})", session), Origin::Ws { ref session } => write!(f, "WebSocket (session: {})", session), - Origin::Signer { ref session } => write!(f, "Signer (session: {})", session), + Origin::Signer { ref session } => write!(f, "Secure Session (session: {})", session), Origin::CApi => write!(f, "C API"), Origin::Unknown => write!(f, "unknown origin"), } From 212ec7ee237634fc326c872e525a2f9d5b93c269 Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Tue, 7 Aug 2018 18:54:36 +0800 Subject: [PATCH 8/9] Address grumbles --- rpc/src/v1/extractors.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/rpc/src/v1/extractors.rs b/rpc/src/v1/extractors.rs index 009a72df6ac..258f1796d39 100644 --- a/rpc/src/v1/extractors.rs +++ b/rpc/src/v1/extractors.rs @@ -38,10 +38,11 @@ impl HttpMetaExtractor for RpcExtractor { fn read_metadata(&self, origin: Option, user_agent: Option) -> Metadata { Metadata { - origin: match user_agent.or(origin) { - Some(service) => Origin::Rpc(service.into()), - None => Origin::Rpc("unknown".into()), - }, + origin: Origin::Rpc( + format!("{} / {}", + origin.unwrap_or("unknown origin".to_string()), + user_agent.unwrap_or("unknown agent".to_string())) + ), session: None, } } From 1d936704dfb300d17a8c381ce09236dffe820c23 Mon Sep 17 00:00:00 2001 From: Wei Tang Date: Tue, 7 Aug 2018 19:53:37 +0800 Subject: [PATCH 9/9] Fix tests --- rpc/src/tests/rpc.rs | 4 ++-- rpc/src/v1/extractors.rs | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/rpc/src/tests/rpc.rs b/rpc/src/tests/rpc.rs index f1a2499597b..fd515ea3a7b 100644 --- a/rpc/src/tests/rpc.rs +++ b/rpc/src/tests/rpc.rs @@ -73,7 +73,7 @@ mod testsing { // when let req = r#"{"method":"hello","params":[],"jsonrpc":"2.0","id":1}"#; - let expected = "34\n{\"jsonrpc\":\"2.0\",\"result\":\"unknown via RPC\",\"id\":1}\n\n0\n\n"; + let expected = "4B\n{\"jsonrpc\":\"2.0\",\"result\":\"unknown origin / unknown agent via RPC\",\"id\":1}\n\n0\n\n"; let res = request(server, &format!("\ POST / HTTP/1.1\r\n\ @@ -98,7 +98,7 @@ mod testsing { // when let req = r#"{"method":"hello","params":[],"jsonrpc":"2.0","id":1}"#; - let expected = "38\n{\"jsonrpc\":\"2.0\",\"result\":\"curl/7.16.3 via RPC\",\"id\":1}\n\n0\n\n"; + let expected = "49\n{\"jsonrpc\":\"2.0\",\"result\":\"unknown origin / curl/7.16.3 via RPC\",\"id\":1}\n\n0\n\n"; let res = request(server, &format!("\ POST / HTTP/1.1\r\n\ diff --git a/rpc/src/v1/extractors.rs b/rpc/src/v1/extractors.rs index 258f1796d39..3406bb031ea 100644 --- a/rpc/src/v1/extractors.rs +++ b/rpc/src/v1/extractors.rs @@ -256,8 +256,8 @@ mod tests { let meta3 = extractor.read_metadata(None, Some("http://parity.io".to_owned())); // then - assert_eq!(meta1.origin, Origin::Rpc("unknown".into())); - assert_eq!(meta2.origin, Origin::Rpc("http://parity.io".into())); - assert_eq!(meta3.origin, Origin::Rpc("http://parity.io".into())); + assert_eq!(meta1.origin, Origin::Rpc("unknown origin / unknown agent".into())); + assert_eq!(meta2.origin, Origin::Rpc("unknown origin / http://parity.io".into())); + assert_eq!(meta3.origin, Origin::Rpc("unknown origin / http://parity.io".into())); } }