Deprecate account management (#10213)
* Extract accounts from ethcore. * Fix ethcore. * Get rid of AccountProvider in test_helpers * Fix rest of the code. * Re-use EngineSigner, fix tests. * Simplify EngineSigner to always have an Address. * Fix RPC tests. * Add deprecation notice to RPCs. * Feature to disable accounts. * extract accounts in RPC * Run with accounts in tests. * Fix RPC compilation and tests. * Fix compilation of the binary. * Fix compilation of the binary. * Fix compilation with accounts enabled. * Fix tests. * Update submodule. * Remove android. * Use derive for Default * Don't build secretstore by default. * Add link to issue. * Refresh Cargo.lock. * Fix miner tests. * Update rpc/Cargo.toml Co-Authored-By: tomusdrw <tomusdrw@users.noreply.github.com> * Fix private tests.
This commit is contained in:
parent
8fa56add47
commit
d5c19f8719
27
Cargo.lock
generated
27
Cargo.lock
generated
@ -693,6 +693,7 @@ dependencies = [
|
|||||||
"ethabi-contract 6.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
"ethabi-contract 6.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
"ethabi-derive 6.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
"ethabi-derive 6.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
"ethash 1.12.0",
|
"ethash 1.12.0",
|
||||||
|
"ethcore-accounts 0.1.0",
|
||||||
"ethcore-blockchain 0.1.0",
|
"ethcore-blockchain 0.1.0",
|
||||||
"ethcore-bloom-journal 0.1.0",
|
"ethcore-bloom-journal 0.1.0",
|
||||||
"ethcore-call-contract 0.1.0",
|
"ethcore-call-contract 0.1.0",
|
||||||
@ -703,10 +704,7 @@ dependencies = [
|
|||||||
"ethereum-types 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
"ethereum-types 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
"ethjson 0.1.0",
|
"ethjson 0.1.0",
|
||||||
"ethkey 0.3.0",
|
"ethkey 0.3.0",
|
||||||
"ethstore 0.2.1",
|
|
||||||
"evm 0.1.0",
|
"evm 0.1.0",
|
||||||
"fake-hardware-wallet 0.0.1",
|
|
||||||
"hardware-wallet 1.12.0",
|
|
||||||
"hashdb 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
"hashdb 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
"heapsize 0.4.2 (git+https://github.com/cheme/heapsize.git?branch=ec-macfix)",
|
"heapsize 0.4.2 (git+https://github.com/cheme/heapsize.git?branch=ec-macfix)",
|
||||||
"itertools 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)",
|
"itertools 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
@ -751,6 +749,24 @@ dependencies = [
|
|||||||
"wasm 0.1.0",
|
"wasm 0.1.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ethcore-accounts"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"common-types 0.1.0",
|
||||||
|
"ethereum-types 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
|
"ethkey 0.3.0",
|
||||||
|
"ethstore 0.2.1",
|
||||||
|
"fake-hardware-wallet 0.0.1",
|
||||||
|
"hardware-wallet 1.12.0",
|
||||||
|
"log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
|
"parking_lot 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
|
"serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
|
"serde_derive 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
|
"serde_json 1.0.32 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
|
"tempdir 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ethcore-blockchain"
|
name = "ethcore-blockchain"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
@ -1015,6 +1031,7 @@ dependencies = [
|
|||||||
"ethabi-contract 6.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
"ethabi-contract 6.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
"ethabi-derive 6.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
"ethabi-derive 6.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
"ethcore 1.12.0",
|
"ethcore 1.12.0",
|
||||||
|
"ethcore-accounts 0.1.0",
|
||||||
"ethcore-call-contract 0.1.0",
|
"ethcore-call-contract 0.1.0",
|
||||||
"ethcore-sync 1.12.0",
|
"ethcore-sync 1.12.0",
|
||||||
"ethereum-types 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
"ethereum-types 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
@ -2447,6 +2464,7 @@ dependencies = [
|
|||||||
"dir 0.1.2",
|
"dir 0.1.2",
|
||||||
"docopt 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
"docopt 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
"ethcore 1.12.0",
|
"ethcore 1.12.0",
|
||||||
|
"ethcore-accounts 0.1.0",
|
||||||
"ethcore-blockchain 0.1.0",
|
"ethcore-blockchain 0.1.0",
|
||||||
"ethcore-call-contract 0.1.0",
|
"ethcore-call-contract 0.1.0",
|
||||||
"ethcore-db 0.1.0",
|
"ethcore-db 0.1.0",
|
||||||
@ -2605,6 +2623,7 @@ dependencies = [
|
|||||||
"eip-712 0.1.0",
|
"eip-712 0.1.0",
|
||||||
"ethash 1.12.0",
|
"ethash 1.12.0",
|
||||||
"ethcore 1.12.0",
|
"ethcore 1.12.0",
|
||||||
|
"ethcore-accounts 0.1.0",
|
||||||
"ethcore-io 1.12.0",
|
"ethcore-io 1.12.0",
|
||||||
"ethcore-light 1.12.0",
|
"ethcore-light 1.12.0",
|
||||||
"ethcore-logger 1.12.0",
|
"ethcore-logger 1.12.0",
|
||||||
@ -2617,11 +2636,9 @@ dependencies = [
|
|||||||
"ethkey 0.3.0",
|
"ethkey 0.3.0",
|
||||||
"ethstore 0.2.1",
|
"ethstore 0.2.1",
|
||||||
"fake-fetch 0.0.1",
|
"fake-fetch 0.0.1",
|
||||||
"fake-hardware-wallet 0.0.1",
|
|
||||||
"fastmap 0.1.0",
|
"fastmap 0.1.0",
|
||||||
"fetch 0.1.0",
|
"fetch 0.1.0",
|
||||||
"futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
|
"futures 0.1.25 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
"hardware-wallet 1.12.0",
|
|
||||||
"itertools 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)",
|
"itertools 0.5.10 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
"jsonrpc-core 10.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
|
"jsonrpc-core 10.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
"jsonrpc-derive 10.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
"jsonrpc-derive 10.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||||
|
11
Cargo.toml
11
Cargo.toml
@ -30,9 +30,10 @@ futures = "0.1"
|
|||||||
fdlimit = "0.1"
|
fdlimit = "0.1"
|
||||||
ctrlc = { git = "https://github.com/paritytech/rust-ctrlc.git" }
|
ctrlc = { git = "https://github.com/paritytech/rust-ctrlc.git" }
|
||||||
jsonrpc-core = "10.0.1"
|
jsonrpc-core = "10.0.1"
|
||||||
ethcore = { path = "ethcore", features = ["parity"] }
|
|
||||||
parity-bytes = "0.1"
|
parity-bytes = "0.1"
|
||||||
common-types = { path = "ethcore/types" }
|
common-types = { path = "ethcore/types" }
|
||||||
|
ethcore = { path = "ethcore", features = ["parity"] }
|
||||||
|
ethcore-accounts = { path = "accounts", optional = true }
|
||||||
ethcore-blockchain = { path = "ethcore/blockchain" }
|
ethcore-blockchain = { path = "ethcore/blockchain" }
|
||||||
ethcore-call-contract = { path = "ethcore/call-contract"}
|
ethcore-call-contract = { path = "ethcore/call-contract"}
|
||||||
ethcore-db = { path = "ethcore/db" }
|
ethcore-db = { path = "ethcore/db" }
|
||||||
@ -44,10 +45,10 @@ ethcore-network = { path = "util/network" }
|
|||||||
ethcore-private-tx = { path = "ethcore/private-tx" }
|
ethcore-private-tx = { path = "ethcore/private-tx" }
|
||||||
ethcore-service = { path = "ethcore/service" }
|
ethcore-service = { path = "ethcore/service" }
|
||||||
ethcore-sync = { path = "ethcore/sync" }
|
ethcore-sync = { path = "ethcore/sync" }
|
||||||
ethstore = { path = "accounts/ethstore" }
|
|
||||||
ethereum-types = "0.4"
|
ethereum-types = "0.4"
|
||||||
node-filter = { path = "ethcore/node-filter" }
|
|
||||||
ethkey = { path = "accounts/ethkey" }
|
ethkey = { path = "accounts/ethkey" }
|
||||||
|
ethstore = { path = "accounts/ethstore" }
|
||||||
|
node-filter = { path = "ethcore/node-filter" }
|
||||||
rlp = { version = "0.3.0", features = ["ethereum"] }
|
rlp = { version = "0.3.0", features = ["ethereum"] }
|
||||||
cli-signer= { path = "cli-signer" }
|
cli-signer= { path = "cli-signer" }
|
||||||
parity-daemonize = "0.2"
|
parity-daemonize = "0.2"
|
||||||
@ -86,6 +87,8 @@ lazy_static = "1.2.0"
|
|||||||
winapi = { version = "0.3.4", features = ["winsock2", "winuser", "shellapi"] }
|
winapi = { version = "0.3.4", features = ["winsock2", "winuser", "shellapi"] }
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
|
default = ["accounts"]
|
||||||
|
accounts = ["ethcore-accounts", "parity-rpc/accounts"]
|
||||||
miner-debug = ["ethcore/miner-debug"]
|
miner-debug = ["ethcore/miner-debug"]
|
||||||
json-tests = ["ethcore/json-tests"]
|
json-tests = ["ethcore/json-tests"]
|
||||||
ci-skip-issue = ["ethcore/ci-skip-issue"]
|
ci-skip-issue = ["ethcore/ci-skip-issue"]
|
||||||
@ -93,7 +96,7 @@ test-heavy = ["ethcore/test-heavy"]
|
|||||||
evm-debug = ["ethcore/evm-debug"]
|
evm-debug = ["ethcore/evm-debug"]
|
||||||
evm-debug-tests = ["ethcore/evm-debug-tests"]
|
evm-debug-tests = ["ethcore/evm-debug-tests"]
|
||||||
slow-blocks = ["ethcore/slow-blocks"]
|
slow-blocks = ["ethcore/slow-blocks"]
|
||||||
secretstore = ["ethcore-secretstore"]
|
secretstore = ["ethcore-secretstore", "ethcore-secretstore/accounts"]
|
||||||
final = ["parity-version/final"]
|
final = ["parity-version/final"]
|
||||||
deadlock_detection = ["parking_lot/deadlock_detection"]
|
deadlock_detection = ["parking_lot/deadlock_detection"]
|
||||||
# to create a memory profile (requires nightly rust), use e.g.
|
# to create a memory profile (requires nightly rust), use e.g.
|
||||||
|
28
accounts/Cargo.toml
Normal file
28
accounts/Cargo.toml
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
[package]
|
||||||
|
description = "Account management for Parity Ethereum"
|
||||||
|
homepage = "http://parity.io"
|
||||||
|
license = "GPL-3.0"
|
||||||
|
name = "ethcore-accounts"
|
||||||
|
version = "0.1.0"
|
||||||
|
authors = ["Parity Technologies <admin@parity.io>"]
|
||||||
|
edition = "2018"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
common-types = { path = "../ethcore/types" }
|
||||||
|
ethkey = { path = "ethkey" }
|
||||||
|
ethstore = { path = "ethstore" }
|
||||||
|
log = "0.4"
|
||||||
|
parking_lot = "0.7"
|
||||||
|
serde = "1.0"
|
||||||
|
serde_derive = "1.0"
|
||||||
|
serde_json = "1.0"
|
||||||
|
|
||||||
|
[target.'cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))'.dependencies]
|
||||||
|
hardware-wallet = { path = "hw" }
|
||||||
|
|
||||||
|
[target.'cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))'.dependencies]
|
||||||
|
fake-hardware-wallet = { path = "fake-hardware-wallet" }
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
ethereum-types = "0.4"
|
||||||
|
tempdir = "0.3"
|
@ -14,9 +14,35 @@
|
|||||||
// You should have received a copy of the GNU General Public License
|
// You should have received a copy of the GNU General Public License
|
||||||
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
//! Misc deserialization.
|
//! Account Metadata
|
||||||
|
|
||||||
use hash;
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
time::Instant,
|
||||||
|
};
|
||||||
|
|
||||||
|
use ethkey::{Address, Password};
|
||||||
|
use serde_derive::{Serialize, Deserialize};
|
||||||
|
use serde_json;
|
||||||
|
|
||||||
|
/// Type of unlock.
|
||||||
|
#[derive(Clone, PartialEq)]
|
||||||
|
pub enum Unlock {
|
||||||
|
/// If account is unlocked temporarily, it should be locked after first usage.
|
||||||
|
OneTime,
|
||||||
|
/// Account unlocked permanently can always sign message.
|
||||||
|
/// Use with caution.
|
||||||
|
Perm,
|
||||||
|
/// Account unlocked with a timeout
|
||||||
|
Timed(Instant),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Data associated with account.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct AccountData {
|
||||||
|
pub unlock: Unlock,
|
||||||
|
pub password: Password,
|
||||||
|
}
|
||||||
|
|
||||||
/// Collected account metadata
|
/// Collected account metadata
|
||||||
#[derive(Default, Clone, Debug, PartialEq, Serialize, Deserialize)]
|
#[derive(Default, Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
@ -29,4 +55,19 @@ pub struct AccountMeta {
|
|||||||
pub uuid: Option<String>,
|
pub uuid: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl_serialization!(hash::Address => AccountMeta);
|
impl AccountMeta {
|
||||||
|
/// Read a hash map of Address -> AccountMeta
|
||||||
|
pub fn read<R>(reader: R) -> Result<HashMap<Address, Self>, serde_json::Error> where
|
||||||
|
R: ::std::io::Read,
|
||||||
|
{
|
||||||
|
serde_json::from_reader(reader)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write a hash map of Address -> AccountMeta
|
||||||
|
pub fn write<W>(m: &HashMap<Address, Self>, writer: &mut W) -> Result<(), serde_json::Error> where
|
||||||
|
W: ::std::io::Write,
|
||||||
|
{
|
||||||
|
serde_json::to_writer(writer, m)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
56
accounts/src/error.rs
Normal file
56
accounts/src/error.rs
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
// 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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
use std::fmt;
|
||||||
|
|
||||||
|
use ethstore::{Error as SSError};
|
||||||
|
use hardware_wallet::{Error as HardwareError};
|
||||||
|
|
||||||
|
/// Signing error
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum SignError {
|
||||||
|
/// Account is not unlocked
|
||||||
|
NotUnlocked,
|
||||||
|
/// Account does not exist.
|
||||||
|
NotFound,
|
||||||
|
/// Low-level hardware device error.
|
||||||
|
Hardware(HardwareError),
|
||||||
|
/// Low-level error from store
|
||||||
|
SStore(SSError),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for SignError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
||||||
|
match *self {
|
||||||
|
SignError::NotUnlocked => write!(f, "Account is locked"),
|
||||||
|
SignError::NotFound => write!(f, "Account does not exist"),
|
||||||
|
SignError::Hardware(ref e) => write!(f, "{}", e),
|
||||||
|
SignError::SStore(ref e) => write!(f, "{}", e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<HardwareError> for SignError {
|
||||||
|
fn from(e: HardwareError) -> Self {
|
||||||
|
SignError::Hardware(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<SSError> for SignError {
|
||||||
|
fn from(e: SSError) -> Self {
|
||||||
|
SignError::SStore(e)
|
||||||
|
}
|
||||||
|
}
|
@ -14,94 +14,55 @@
|
|||||||
// You should have received a copy of the GNU General Public License
|
// You should have received a copy of the GNU General Public License
|
||||||
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
#![warn(missing_docs)]
|
||||||
|
|
||||||
//! Account management.
|
//! Account management.
|
||||||
|
|
||||||
|
mod account_data;
|
||||||
|
mod error;
|
||||||
mod stores;
|
mod stores;
|
||||||
|
|
||||||
|
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
|
||||||
|
extern crate fake_hardware_wallet as hardware_wallet;
|
||||||
|
|
||||||
|
use self::account_data::{Unlock, AccountData};
|
||||||
use self::stores::AddressBook;
|
use self::stores::AddressBook;
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::fmt;
|
|
||||||
use std::time::{Instant, Duration};
|
use std::time::{Instant, Duration};
|
||||||
|
|
||||||
|
use common_types::transaction::{Action, Transaction};
|
||||||
|
use ethkey::{Address, Message, Public, Secret, Password, Random, Generator};
|
||||||
use ethstore::accounts_dir::MemoryDirectory;
|
use ethstore::accounts_dir::MemoryDirectory;
|
||||||
use ethstore::ethkey::{Address, Message, Public, Secret, Password, Random, Generator};
|
|
||||||
use ethjson::misc::AccountMeta;
|
|
||||||
use ethstore::{
|
use ethstore::{
|
||||||
SimpleSecretStore, SecretStore, Error as SSError, EthStore, EthMultiStore,
|
SimpleSecretStore, SecretStore, EthStore, EthMultiStore,
|
||||||
random_string, SecretVaultRef, StoreAccountRef, OpaqueSecret,
|
random_string, SecretVaultRef, StoreAccountRef, OpaqueSecret,
|
||||||
};
|
};
|
||||||
|
use log::{warn, debug};
|
||||||
use parking_lot::RwLock;
|
use parking_lot::RwLock;
|
||||||
use types::transaction::{Action, Transaction};
|
|
||||||
|
|
||||||
pub use ethstore::ethkey::Signature;
|
pub use ethkey::Signature;
|
||||||
pub use ethstore::{Derivation, IndexDerivation, KeyFile};
|
pub use ethstore::{Derivation, IndexDerivation, KeyFile, Error};
|
||||||
pub use hardware_wallet::{Error as HardwareError, HardwareWalletManager, KeyPath, TransactionInfo};
|
pub use hardware_wallet::{Error as HardwareError, HardwareWalletManager, KeyPath, TransactionInfo};
|
||||||
|
|
||||||
/// Type of unlock.
|
pub use self::account_data::AccountMeta;
|
||||||
#[derive(Clone, PartialEq)]
|
pub use self::error::SignError;
|
||||||
enum Unlock {
|
|
||||||
/// If account is unlocked temporarily, it should be locked after first usage.
|
|
||||||
OneTime,
|
|
||||||
/// Account unlocked permanently can always sign message.
|
|
||||||
/// Use with caution.
|
|
||||||
Perm,
|
|
||||||
/// Account unlocked with a timeout
|
|
||||||
Timed(Instant),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Data associated with account.
|
|
||||||
#[derive(Clone)]
|
|
||||||
struct AccountData {
|
|
||||||
unlock: Unlock,
|
|
||||||
password: Password,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Signing error
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub enum SignError {
|
|
||||||
/// Account is not unlocked
|
|
||||||
NotUnlocked,
|
|
||||||
/// Account does not exist.
|
|
||||||
NotFound,
|
|
||||||
/// Low-level hardware device error.
|
|
||||||
Hardware(HardwareError),
|
|
||||||
/// Low-level error from store
|
|
||||||
SStore(SSError),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for SignError {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
|
|
||||||
match *self {
|
|
||||||
SignError::NotUnlocked => write!(f, "Account is locked"),
|
|
||||||
SignError::NotFound => write!(f, "Account does not exist"),
|
|
||||||
SignError::Hardware(ref e) => write!(f, "{}", e),
|
|
||||||
SignError::SStore(ref e) => write!(f, "{}", e),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<HardwareError> for SignError {
|
|
||||||
fn from(e: HardwareError) -> Self {
|
|
||||||
SignError::Hardware(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<SSError> for SignError {
|
|
||||||
fn from(e: SSError) -> Self {
|
|
||||||
SignError::SStore(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `AccountProvider` errors.
|
|
||||||
pub type Error = SSError;
|
|
||||||
|
|
||||||
fn transient_sstore() -> EthMultiStore {
|
|
||||||
EthMultiStore::open(Box::new(MemoryDirectory::default())).expect("MemoryDirectory load always succeeds; qed")
|
|
||||||
}
|
|
||||||
|
|
||||||
type AccountToken = Password;
|
type AccountToken = Password;
|
||||||
|
|
||||||
|
/// Account management settings.
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct AccountProviderSettings {
|
||||||
|
/// Enable hardware wallet support.
|
||||||
|
pub enable_hardware_wallets: bool,
|
||||||
|
/// Use the classic chain key on the hardware wallet.
|
||||||
|
pub hardware_wallet_classic_key: bool,
|
||||||
|
/// Store raw account secret when unlocking the account permanently.
|
||||||
|
pub unlock_keep_secret: bool,
|
||||||
|
/// Disallowed accounts.
|
||||||
|
pub blacklisted_accounts: Vec<Address>,
|
||||||
|
}
|
||||||
|
|
||||||
/// Account management.
|
/// Account management.
|
||||||
/// Responsible for unlocking accounts.
|
/// Responsible for unlocking accounts.
|
||||||
pub struct AccountProvider {
|
pub struct AccountProvider {
|
||||||
@ -124,27 +85,8 @@ pub struct AccountProvider {
|
|||||||
blacklisted_accounts: Vec<Address>,
|
blacklisted_accounts: Vec<Address>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Account management settings.
|
fn transient_sstore() -> EthMultiStore {
|
||||||
pub struct AccountProviderSettings {
|
EthMultiStore::open(Box::new(MemoryDirectory::default())).expect("MemoryDirectory load always succeeds; qed")
|
||||||
/// Enable hardware wallet support.
|
|
||||||
pub enable_hardware_wallets: bool,
|
|
||||||
/// Use the classic chain key on the hardware wallet.
|
|
||||||
pub hardware_wallet_classic_key: bool,
|
|
||||||
/// Store raw account secret when unlocking the account permanently.
|
|
||||||
pub unlock_keep_secret: bool,
|
|
||||||
/// Disallowed accounts.
|
|
||||||
pub blacklisted_accounts: Vec<Address>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for AccountProviderSettings {
|
|
||||||
fn default() -> Self {
|
|
||||||
AccountProviderSettings {
|
|
||||||
enable_hardware_wallets: false,
|
|
||||||
hardware_wallet_classic_key: false,
|
|
||||||
unlock_keep_secret: false,
|
|
||||||
blacklisted_accounts: vec![],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AccountProvider {
|
impl AccountProvider {
|
||||||
@ -221,7 +163,7 @@ impl AccountProvider {
|
|||||||
let account = self.sstore.insert_account(SecretVaultRef::Root, secret, password)?;
|
let account = self.sstore.insert_account(SecretVaultRef::Root, secret, password)?;
|
||||||
if self.blacklisted_accounts.contains(&account.address) {
|
if self.blacklisted_accounts.contains(&account.address) {
|
||||||
self.sstore.remove_account(&account, password)?;
|
self.sstore.remove_account(&account, password)?;
|
||||||
return Err(SSError::InvalidAccount.into());
|
return Err(Error::InvalidAccount.into());
|
||||||
}
|
}
|
||||||
Ok(account.address)
|
Ok(account.address)
|
||||||
}
|
}
|
||||||
@ -251,7 +193,7 @@ impl AccountProvider {
|
|||||||
let account = self.sstore.import_wallet(SecretVaultRef::Root, json, password, gen_id)?;
|
let account = self.sstore.import_wallet(SecretVaultRef::Root, json, password, gen_id)?;
|
||||||
if self.blacklisted_accounts.contains(&account.address) {
|
if self.blacklisted_accounts.contains(&account.address) {
|
||||||
self.sstore.remove_account(&account, password)?;
|
self.sstore.remove_account(&account, password)?;
|
||||||
return Err(SSError::InvalidAccount.into());
|
return Err(Error::InvalidAccount.into());
|
||||||
}
|
}
|
||||||
Ok(Address::from(account.address).into())
|
Ok(Address::from(account.address).into())
|
||||||
}
|
}
|
||||||
@ -284,7 +226,7 @@ impl AccountProvider {
|
|||||||
return Ok(accounts.into_iter().map(|a| a.address).collect());
|
return Ok(accounts.into_iter().map(|a| a.address).collect());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(SSError::Custom("No hardware wallet accounts were found".into()))
|
Err(Error::Custom("No hardware wallet accounts were found".into()))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get a list of paths to locked hardware wallets
|
/// Get a list of paths to locked hardware wallets
|
||||||
@ -669,7 +611,7 @@ impl AccountProvider {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::{AccountProvider, Unlock};
|
use super::{AccountProvider, Unlock};
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
use ethstore::ethkey::{Generator, Random, Address};
|
use ethkey::{Generator, Random, Address};
|
||||||
use ethstore::{StoreAccountRef, Derivation};
|
use ethstore::{StoreAccountRef, Derivation};
|
||||||
use ethereum_types::H256;
|
use ethereum_types::H256;
|
||||||
|
|
@ -20,8 +20,10 @@ use std::{fs, fmt, hash, ops};
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
use ethstore::ethkey::Address;
|
use ethkey::Address;
|
||||||
use ethjson::misc::AccountMeta;
|
use log::{trace, warn};
|
||||||
|
|
||||||
|
use crate::AccountMeta;
|
||||||
|
|
||||||
/// Disk-backed map from Address to String. Uses JSON.
|
/// Disk-backed map from Address to String. Uses JSON.
|
||||||
pub struct AddressBook {
|
pub struct AddressBook {
|
||||||
@ -153,8 +155,8 @@ impl<K: hash::Hash + Eq, V> DiskMap<K, V> {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::AddressBook;
|
use super::AddressBook;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use ethjson::misc::AccountMeta;
|
|
||||||
use tempdir::TempDir;
|
use tempdir::TempDir;
|
||||||
|
use crate::account_data::AccountMeta;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn should_save_and_reload_address_book() {
|
fn should_save_and_reload_address_book() {
|
||||||
@ -163,7 +165,9 @@ mod tests {
|
|||||||
b.set_name(1.into(), "One".to_owned());
|
b.set_name(1.into(), "One".to_owned());
|
||||||
b.set_meta(1.into(), "{1:1}".to_owned());
|
b.set_meta(1.into(), "{1:1}".to_owned());
|
||||||
let b = AddressBook::new(tempdir.path());
|
let b = AddressBook::new(tempdir.path());
|
||||||
assert_eq!(b.get(), hash_map![1.into() => AccountMeta{name: "One".to_owned(), meta: "{1:1}".to_owned(), uuid: None}]);
|
assert_eq!(b.get(), vec![
|
||||||
|
(1, AccountMeta {name: "One".to_owned(), meta: "{1:1}".to_owned(), uuid: None})
|
||||||
|
].into_iter().map(|(a, b)| (a.into(), b)).collect::<HashMap<_, _>>());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@ -177,9 +181,9 @@ mod tests {
|
|||||||
b.remove(2.into());
|
b.remove(2.into());
|
||||||
|
|
||||||
let b = AddressBook::new(tempdir.path());
|
let b = AddressBook::new(tempdir.path());
|
||||||
assert_eq!(b.get(), hash_map![
|
assert_eq!(b.get(), vec![
|
||||||
1.into() => AccountMeta{name: "One".to_owned(), meta: "{}".to_owned(), uuid: None},
|
(1, AccountMeta{name: "One".to_owned(), meta: "{}".to_owned(), uuid: None}),
|
||||||
3.into() => AccountMeta{name: "Three".to_owned(), meta: "{}".to_owned(), uuid: None}
|
(3, AccountMeta{name: "Three".to_owned(), meta: "{}".to_owned(), uuid: None}),
|
||||||
]);
|
].into_iter().map(|(a, b)| (a.into(), b)).collect::<HashMap<_, _>>());
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -29,7 +29,6 @@ ethcore-stratum = { path = "../miner/stratum", optional = true }
|
|||||||
ethereum-types = "0.4"
|
ethereum-types = "0.4"
|
||||||
ethjson = { path = "../json" }
|
ethjson = { path = "../json" }
|
||||||
ethkey = { path = "../accounts/ethkey" }
|
ethkey = { path = "../accounts/ethkey" }
|
||||||
ethstore = { path = "../accounts/ethstore" }
|
|
||||||
evm = { path = "evm" }
|
evm = { path = "evm" }
|
||||||
hashdb = "0.3.0"
|
hashdb = "0.3.0"
|
||||||
heapsize = "0.4"
|
heapsize = "0.4"
|
||||||
@ -72,16 +71,11 @@ using_queue = { path = "../miner/using-queue" }
|
|||||||
vm = { path = "vm" }
|
vm = { path = "vm" }
|
||||||
wasm = { path = "wasm" }
|
wasm = { path = "wasm" }
|
||||||
|
|
||||||
[target.'cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))'.dependencies]
|
|
||||||
hardware-wallet = { path = "../accounts/hw" }
|
|
||||||
|
|
||||||
[target.'cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))'.dependencies]
|
|
||||||
fake-hardware-wallet = { path = "../accounts/fake-hardware-wallet" }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
blooms-db = { path = "../util/blooms-db" }
|
blooms-db = { path = "../util/blooms-db" }
|
||||||
criterion = "0.2"
|
criterion = "0.2"
|
||||||
env_logger = "0.5"
|
env_logger = "0.5"
|
||||||
|
ethcore-accounts = { path = "../accounts" }
|
||||||
kvdb-rocksdb = "0.1.3"
|
kvdb-rocksdb = "0.1.3"
|
||||||
rlp_compress = { path = "../util/rlp-compress" }
|
rlp_compress = { path = "../util/rlp-compress" }
|
||||||
tempdir = "0.3"
|
tempdir = "0.3"
|
||||||
|
@ -18,22 +18,22 @@
|
|||||||
|
|
||||||
use std::io::Read;
|
use std::io::Read;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
use std::sync::Arc;
|
||||||
use std::iter::repeat;
|
use std::iter::repeat;
|
||||||
use std::time::{Instant, Duration};
|
use std::time::{Instant, Duration};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::collections::hash_map::Entry;
|
use std::collections::hash_map::Entry;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use ethcore::account_provider::AccountProvider;
|
|
||||||
use ethereum_types::{H128, H256, Address};
|
use ethereum_types::{H128, H256, Address};
|
||||||
use ethjson;
|
use ethjson;
|
||||||
use ethkey::{Signature, Password, Public};
|
use ethkey::{Signature, Public};
|
||||||
use crypto;
|
use crypto;
|
||||||
use futures::Future;
|
use futures::Future;
|
||||||
use fetch::{Fetch, Client as FetchClient, Method, BodyReader, Request};
|
use fetch::{Fetch, Client as FetchClient, Method, BodyReader, Request};
|
||||||
use bytes::{Bytes, ToPretty};
|
use bytes::{Bytes, ToPretty};
|
||||||
use error::{Error, ErrorKind};
|
use error::{Error, ErrorKind};
|
||||||
use url::Url;
|
use url::Url;
|
||||||
use super::find_account_password;
|
use super::Signer;
|
||||||
use super::key_server_keys::address_to_key;
|
use super::key_server_keys::address_to_key;
|
||||||
|
|
||||||
/// Initialization vector length.
|
/// Initialization vector length.
|
||||||
@ -48,7 +48,6 @@ pub trait Encryptor: Send + Sync + 'static {
|
|||||||
fn encrypt(
|
fn encrypt(
|
||||||
&self,
|
&self,
|
||||||
contract_address: &Address,
|
contract_address: &Address,
|
||||||
accounts: &AccountProvider,
|
|
||||||
initialisation_vector: &H128,
|
initialisation_vector: &H128,
|
||||||
plain_data: &[u8],
|
plain_data: &[u8],
|
||||||
) -> Result<Bytes, Error>;
|
) -> Result<Bytes, Error>;
|
||||||
@ -57,7 +56,6 @@ pub trait Encryptor: Send + Sync + 'static {
|
|||||||
fn decrypt(
|
fn decrypt(
|
||||||
&self,
|
&self,
|
||||||
contract_address: &Address,
|
contract_address: &Address,
|
||||||
accounts: &AccountProvider,
|
|
||||||
cypher: &[u8],
|
cypher: &[u8],
|
||||||
) -> Result<Bytes, Error>;
|
) -> Result<Bytes, Error>;
|
||||||
}
|
}
|
||||||
@ -71,8 +69,6 @@ pub struct EncryptorConfig {
|
|||||||
pub threshold: u32,
|
pub threshold: u32,
|
||||||
/// Account used for signing requests to key server
|
/// Account used for signing requests to key server
|
||||||
pub key_server_account: Option<Address>,
|
pub key_server_account: Option<Address>,
|
||||||
/// Passwords used to unlock accounts
|
|
||||||
pub passwords: Vec<Password>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
struct EncryptionSession {
|
struct EncryptionSession {
|
||||||
@ -85,14 +81,20 @@ pub struct SecretStoreEncryptor {
|
|||||||
config: EncryptorConfig,
|
config: EncryptorConfig,
|
||||||
client: FetchClient,
|
client: FetchClient,
|
||||||
sessions: Mutex<HashMap<Address, EncryptionSession>>,
|
sessions: Mutex<HashMap<Address, EncryptionSession>>,
|
||||||
|
signer: Arc<Signer>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SecretStoreEncryptor {
|
impl SecretStoreEncryptor {
|
||||||
/// Create new encryptor
|
/// Create new encryptor
|
||||||
pub fn new(config: EncryptorConfig, client: FetchClient) -> Result<Self, Error> {
|
pub fn new(
|
||||||
|
config: EncryptorConfig,
|
||||||
|
client: FetchClient,
|
||||||
|
signer: Arc<Signer>,
|
||||||
|
) -> Result<Self, Error> {
|
||||||
Ok(SecretStoreEncryptor {
|
Ok(SecretStoreEncryptor {
|
||||||
config,
|
config,
|
||||||
client,
|
client,
|
||||||
|
signer,
|
||||||
sessions: Mutex::default(),
|
sessions: Mutex::default(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -103,13 +105,12 @@ impl SecretStoreEncryptor {
|
|||||||
url_suffix: &str,
|
url_suffix: &str,
|
||||||
use_post: bool,
|
use_post: bool,
|
||||||
contract_address: &Address,
|
contract_address: &Address,
|
||||||
accounts: &AccountProvider,
|
|
||||||
) -> Result<Bytes, Error> {
|
) -> Result<Bytes, Error> {
|
||||||
// check if the key was already cached
|
// check if the key was already cached
|
||||||
if let Some(key) = self.obtained_key(contract_address) {
|
if let Some(key) = self.obtained_key(contract_address) {
|
||||||
return Ok(key);
|
return Ok(key);
|
||||||
}
|
}
|
||||||
let contract_address_signature = self.sign_contract_address(contract_address, accounts)?;
|
let contract_address_signature = self.sign_contract_address(contract_address)?;
|
||||||
let requester = self.config.key_server_account.ok_or_else(|| ErrorKind::KeyServerAccountNotSet)?;
|
let requester = self.config.key_server_account.ok_or_else(|| ErrorKind::KeyServerAccountNotSet)?;
|
||||||
|
|
||||||
// key id in SS is H256 && we have H160 here => expand with assitional zeros
|
// key id in SS is H256 && we have H160 here => expand with assitional zeros
|
||||||
@ -149,10 +150,9 @@ impl SecretStoreEncryptor {
|
|||||||
|
|
||||||
// response is JSON string (which is, in turn, hex-encoded, encrypted Public)
|
// response is JSON string (which is, in turn, hex-encoded, encrypted Public)
|
||||||
let encrypted_bytes: ethjson::bytes::Bytes = result.trim_matches('\"').parse().map_err(|e| ErrorKind::Encrypt(e))?;
|
let encrypted_bytes: ethjson::bytes::Bytes = result.trim_matches('\"').parse().map_err(|e| ErrorKind::Encrypt(e))?;
|
||||||
let password = find_account_password(&self.config.passwords, &*accounts, &requester);
|
|
||||||
|
|
||||||
// decrypt Public
|
// decrypt Public
|
||||||
let decrypted_bytes = accounts.decrypt(requester, password, &crypto::DEFAULT_MAC, &encrypted_bytes)?;
|
let decrypted_bytes = self.signer.decrypt(requester, &crypto::DEFAULT_MAC, &encrypted_bytes)?;
|
||||||
let decrypted_key = Public::from_slice(&decrypted_bytes);
|
let decrypted_key = Public::from_slice(&decrypted_bytes);
|
||||||
|
|
||||||
// and now take x coordinate of Public as a key
|
// and now take x coordinate of Public as a key
|
||||||
@ -188,10 +188,9 @@ impl SecretStoreEncryptor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sign_contract_address(&self, contract_address: &Address, accounts: &AccountProvider) -> Result<Signature, Error> {
|
fn sign_contract_address(&self, contract_address: &Address) -> Result<Signature, Error> {
|
||||||
let key_server_account = self.config.key_server_account.ok_or_else(|| ErrorKind::KeyServerAccountNotSet)?;
|
let key_server_account = self.config.key_server_account.ok_or_else(|| ErrorKind::KeyServerAccountNotSet)?;
|
||||||
let password = find_account_password(&self.config.passwords, accounts, &key_server_account);
|
Ok(self.signer.sign(key_server_account, address_to_key(contract_address))?)
|
||||||
Ok(accounts.sign(key_server_account, password, address_to_key(contract_address))?)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -199,16 +198,15 @@ impl Encryptor for SecretStoreEncryptor {
|
|||||||
fn encrypt(
|
fn encrypt(
|
||||||
&self,
|
&self,
|
||||||
contract_address: &Address,
|
contract_address: &Address,
|
||||||
accounts: &AccountProvider,
|
|
||||||
initialisation_vector: &H128,
|
initialisation_vector: &H128,
|
||||||
plain_data: &[u8],
|
plain_data: &[u8],
|
||||||
) -> Result<Bytes, Error> {
|
) -> Result<Bytes, Error> {
|
||||||
// retrieve the key, try to generate it if it doesn't exist yet
|
// retrieve the key, try to generate it if it doesn't exist yet
|
||||||
let key = match self.retrieve_key("", false, contract_address, &*accounts) {
|
let key = match self.retrieve_key("", false, contract_address) {
|
||||||
Ok(key) => Ok(key),
|
Ok(key) => Ok(key),
|
||||||
Err(Error(ErrorKind::EncryptionKeyNotFound(_), _)) => {
|
Err(Error(ErrorKind::EncryptionKeyNotFound(_), _)) => {
|
||||||
trace!(target: "privatetx", "Key for account wasnt found in sstore. Creating. Address: {:?}", contract_address);
|
trace!(target: "privatetx", "Key for account wasnt found in sstore. Creating. Address: {:?}", contract_address);
|
||||||
self.retrieve_key(&format!("/{}", self.config.threshold), true, contract_address, &*accounts)
|
self.retrieve_key(&format!("/{}", self.config.threshold), true, contract_address)
|
||||||
}
|
}
|
||||||
Err(err) => Err(err),
|
Err(err) => Err(err),
|
||||||
}?;
|
}?;
|
||||||
@ -227,7 +225,6 @@ impl Encryptor for SecretStoreEncryptor {
|
|||||||
fn decrypt(
|
fn decrypt(
|
||||||
&self,
|
&self,
|
||||||
contract_address: &Address,
|
contract_address: &Address,
|
||||||
accounts: &AccountProvider,
|
|
||||||
cypher: &[u8],
|
cypher: &[u8],
|
||||||
) -> Result<Bytes, Error> {
|
) -> Result<Bytes, Error> {
|
||||||
// initialization vector takes INIT_VEC_LEN bytes
|
// initialization vector takes INIT_VEC_LEN bytes
|
||||||
@ -237,7 +234,7 @@ impl Encryptor for SecretStoreEncryptor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// retrieve existing key
|
// retrieve existing key
|
||||||
let key = self.retrieve_key("", false, contract_address, accounts)?;
|
let key = self.retrieve_key("", false, contract_address)?;
|
||||||
|
|
||||||
// use symmetric decryption to decrypt document
|
// use symmetric decryption to decrypt document
|
||||||
let (cypher, iv) = cypher.split_at(cypher_len - INIT_VEC_LEN);
|
let (cypher, iv) = cypher.split_at(cypher_len - INIT_VEC_LEN);
|
||||||
@ -257,7 +254,6 @@ impl Encryptor for NoopEncryptor {
|
|||||||
fn encrypt(
|
fn encrypt(
|
||||||
&self,
|
&self,
|
||||||
_contract_address: &Address,
|
_contract_address: &Address,
|
||||||
_accounts: &AccountProvider,
|
|
||||||
_initialisation_vector: &H128,
|
_initialisation_vector: &H128,
|
||||||
data: &[u8],
|
data: &[u8],
|
||||||
) -> Result<Bytes, Error> {
|
) -> Result<Bytes, Error> {
|
||||||
@ -267,7 +263,6 @@ impl Encryptor for NoopEncryptor {
|
|||||||
fn decrypt(
|
fn decrypt(
|
||||||
&self,
|
&self,
|
||||||
_contract_address: &Address,
|
_contract_address: &Address,
|
||||||
_accounts: &AccountProvider,
|
|
||||||
data: &[u8],
|
data: &[u8],
|
||||||
) -> Result<Bytes, Error> {
|
) -> Result<Bytes, Error> {
|
||||||
Ok(data.to_vec())
|
Ok(data.to_vec())
|
||||||
|
@ -17,10 +17,10 @@
|
|||||||
use ethereum_types::Address;
|
use ethereum_types::Address;
|
||||||
use rlp::DecoderError;
|
use rlp::DecoderError;
|
||||||
use ethtrie::TrieError;
|
use ethtrie::TrieError;
|
||||||
use ethcore::account_provider::SignError;
|
|
||||||
use ethcore::error::{Error as EthcoreError, ExecutionError};
|
use ethcore::error::{Error as EthcoreError, ExecutionError};
|
||||||
use types::transaction::Error as TransactionError;
|
use types::transaction::Error as TransactionError;
|
||||||
use ethkey::Error as KeyError;
|
use ethkey::Error as KeyError;
|
||||||
|
use ethkey::crypto::Error as CryptoError;
|
||||||
use txpool::Error as TxPoolError;
|
use txpool::Error as TxPoolError;
|
||||||
|
|
||||||
error_chain! {
|
error_chain! {
|
||||||
@ -29,6 +29,7 @@ error_chain! {
|
|||||||
Decoder(DecoderError) #[doc = "RLP decoding error."];
|
Decoder(DecoderError) #[doc = "RLP decoding error."];
|
||||||
Trie(TrieError) #[doc = "Error concerning TrieDBs."];
|
Trie(TrieError) #[doc = "Error concerning TrieDBs."];
|
||||||
Txpool(TxPoolError) #[doc = "Tx pool error."];
|
Txpool(TxPoolError) #[doc = "Tx pool error."];
|
||||||
|
Crypto(CryptoError) #[doc = "Crypto error."];
|
||||||
}
|
}
|
||||||
|
|
||||||
errors {
|
errors {
|
||||||
@ -152,12 +153,6 @@ error_chain! {
|
|||||||
display("General signing error {}", err),
|
display("General signing error {}", err),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[doc = "Account provider signing error."]
|
|
||||||
Sign(err: SignError) {
|
|
||||||
description("Account provider signing error."),
|
|
||||||
display("Account provider signing error {}", err),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[doc = "Error of transactions processing."]
|
#[doc = "Error of transactions processing."]
|
||||||
Transaction(err: TransactionError) {
|
Transaction(err: TransactionError) {
|
||||||
description("Error of transactions processing."),
|
description("Error of transactions processing."),
|
||||||
@ -172,12 +167,6 @@ error_chain! {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<SignError> for Error {
|
|
||||||
fn from(err: SignError) -> Self {
|
|
||||||
ErrorKind::Sign(err).into()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<KeyError> for Error {
|
impl From<KeyError> for Error {
|
||||||
fn from(err: KeyError) -> Self {
|
fn from(err: KeyError) -> Self {
|
||||||
ErrorKind::Key(err).into()
|
ErrorKind::Key(err).into()
|
||||||
|
@ -87,13 +87,11 @@ use ethcore::client::{
|
|||||||
Client, ChainNotify, NewBlocks, ChainMessageType, ClientIoMessage, BlockId,
|
Client, ChainNotify, NewBlocks, ChainMessageType, ClientIoMessage, BlockId,
|
||||||
Call, BlockInfo
|
Call, BlockInfo
|
||||||
};
|
};
|
||||||
use ethcore::account_provider::AccountProvider;
|
|
||||||
use ethcore::miner::{self, Miner, MinerService, pool_client::NonceCache};
|
use ethcore::miner::{self, Miner, MinerService, pool_client::NonceCache};
|
||||||
use ethcore::{state, state_db};
|
use ethcore::{state, state_db};
|
||||||
use ethcore::trace::{Tracer, VMTracer};
|
use ethcore::trace::{Tracer, VMTracer};
|
||||||
use call_contract::CallContract;
|
use call_contract::CallContract;
|
||||||
use rustc_hex::FromHex;
|
use rustc_hex::FromHex;
|
||||||
use ethkey::Password;
|
|
||||||
use ethabi::FunctionOutputDecoder;
|
use ethabi::FunctionOutputDecoder;
|
||||||
|
|
||||||
// Source avaiable at https://github.com/parity-contracts/private-tx/blob/master/contracts/PrivateContract.sol
|
// Source avaiable at https://github.com/parity-contracts/private-tx/blob/master/contracts/PrivateContract.sol
|
||||||
@ -120,8 +118,6 @@ pub struct ProviderConfig {
|
|||||||
pub validator_accounts: Vec<Address>,
|
pub validator_accounts: Vec<Address>,
|
||||||
/// Account used for signing public transactions created from private transactions
|
/// Account used for signing public transactions created from private transactions
|
||||||
pub signer_account: Option<Address>,
|
pub signer_account: Option<Address>,
|
||||||
/// Passwords used to unlock accounts
|
|
||||||
pub passwords: Vec<Password>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@ -135,18 +131,51 @@ pub struct Receipt {
|
|||||||
pub status_code: u8,
|
pub status_code: u8,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Payload signing and decrypting capabilities.
|
||||||
|
pub trait Signer: Send + Sync {
|
||||||
|
/// Decrypt payload using private key of given address.
|
||||||
|
fn decrypt(&self, account: Address, shared_mac: &[u8], payload: &[u8]) -> Result<Vec<u8>, Error>;
|
||||||
|
/// Sign given hash using provided account.
|
||||||
|
fn sign(&self, account: Address, hash: ethkey::Message) -> Result<Signature, Error>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Signer implementation that errors on any request.
|
||||||
|
pub struct DummySigner;
|
||||||
|
impl Signer for DummySigner {
|
||||||
|
fn decrypt(&self, _account: Address, _shared_mac: &[u8], _payload: &[u8]) -> Result<Vec<u8>, Error> {
|
||||||
|
Err("Decrypting is not supported.".to_owned())?
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sign(&self, _account: Address, _hash: ethkey::Message) -> Result<Signature, Error> {
|
||||||
|
Err("Signing is not supported.".to_owned())?
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Signer implementation using multiple keypairs
|
||||||
|
pub struct KeyPairSigner(pub Vec<ethkey::KeyPair>);
|
||||||
|
impl Signer for KeyPairSigner {
|
||||||
|
fn decrypt(&self, account: Address, shared_mac: &[u8], payload: &[u8]) -> Result<Vec<u8>, Error> {
|
||||||
|
let kp = self.0.iter().find(|k| k.address() == account).ok_or(ethkey::Error::InvalidAddress)?;
|
||||||
|
Ok(ethkey::crypto::ecies::decrypt(kp.secret(), shared_mac, payload)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sign(&self, account: Address, hash: ethkey::Message) -> Result<Signature, Error> {
|
||||||
|
let kp = self.0.iter().find(|k| k.address() == account).ok_or(ethkey::Error::InvalidAddress)?;
|
||||||
|
Ok(ethkey::sign(kp.secret(), &hash)?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Manager of private transactions
|
/// Manager of private transactions
|
||||||
pub struct Provider {
|
pub struct Provider {
|
||||||
encryptor: Box<Encryptor>,
|
encryptor: Box<Encryptor>,
|
||||||
validator_accounts: HashSet<Address>,
|
validator_accounts: HashSet<Address>,
|
||||||
signer_account: Option<Address>,
|
signer_account: Option<Address>,
|
||||||
passwords: Vec<Password>,
|
|
||||||
notify: RwLock<Vec<Weak<ChainNotify>>>,
|
notify: RwLock<Vec<Weak<ChainNotify>>>,
|
||||||
transactions_for_signing: RwLock<SigningStore>,
|
transactions_for_signing: RwLock<SigningStore>,
|
||||||
transactions_for_verification: VerificationStore,
|
transactions_for_verification: VerificationStore,
|
||||||
client: Arc<Client>,
|
client: Arc<Client>,
|
||||||
miner: Arc<Miner>,
|
miner: Arc<Miner>,
|
||||||
accounts: Arc<AccountProvider>,
|
accounts: Arc<Signer>,
|
||||||
channel: IoChannel<ClientIoMessage>,
|
channel: IoChannel<ClientIoMessage>,
|
||||||
keys_provider: Arc<KeyProvider>,
|
keys_provider: Arc<KeyProvider>,
|
||||||
}
|
}
|
||||||
@ -159,12 +188,12 @@ pub struct PrivateExecutionResult<T, V> where T: Tracer, V: VMTracer {
|
|||||||
result: Executed<T::Output, V::Output>,
|
result: Executed<T::Output, V::Output>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Provider where {
|
impl Provider {
|
||||||
/// Create a new provider.
|
/// Create a new provider.
|
||||||
pub fn new(
|
pub fn new(
|
||||||
client: Arc<Client>,
|
client: Arc<Client>,
|
||||||
miner: Arc<Miner>,
|
miner: Arc<Miner>,
|
||||||
accounts: Arc<AccountProvider>,
|
accounts: Arc<Signer>,
|
||||||
encryptor: Box<Encryptor>,
|
encryptor: Box<Encryptor>,
|
||||||
config: ProviderConfig,
|
config: ProviderConfig,
|
||||||
channel: IoChannel<ClientIoMessage>,
|
channel: IoChannel<ClientIoMessage>,
|
||||||
@ -175,7 +204,6 @@ impl Provider where {
|
|||||||
encryptor,
|
encryptor,
|
||||||
validator_accounts: config.validator_accounts.into_iter().collect(),
|
validator_accounts: config.validator_accounts.into_iter().collect(),
|
||||||
signer_account: config.signer_account,
|
signer_account: config.signer_account,
|
||||||
passwords: config.passwords,
|
|
||||||
notify: RwLock::default(),
|
notify: RwLock::default(),
|
||||||
transactions_for_signing: RwLock::default(),
|
transactions_for_signing: RwLock::default(),
|
||||||
transactions_for_verification: VerificationStore::default(),
|
transactions_for_verification: VerificationStore::default(),
|
||||||
@ -248,21 +276,20 @@ impl Provider where {
|
|||||||
keccak(&state_buf.as_ref())
|
keccak(&state_buf.as_ref())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn pool_client<'a>(&'a self, nonce_cache: &'a NonceCache) -> miner::pool_client::PoolClient<'a, Client> {
|
fn pool_client<'a>(&'a self, nonce_cache: &'a NonceCache, local_accounts: &'a HashSet<Address>) -> miner::pool_client::PoolClient<'a, Client> {
|
||||||
let engine = self.client.engine();
|
let engine = self.client.engine();
|
||||||
let refuse_service_transactions = true;
|
let refuse_service_transactions = true;
|
||||||
miner::pool_client::PoolClient::new(
|
miner::pool_client::PoolClient::new(
|
||||||
&*self.client,
|
&*self.client,
|
||||||
nonce_cache,
|
nonce_cache,
|
||||||
engine,
|
engine,
|
||||||
Some(&*self.accounts),
|
local_accounts,
|
||||||
refuse_service_transactions,
|
refuse_service_transactions,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Retrieve and verify the first available private transaction for every sender
|
/// Retrieve and verify the first available private transaction for every sender
|
||||||
fn process_verification_queue(&self) -> Result<(), Error> {
|
fn process_verification_queue(&self) -> Result<(), Error> {
|
||||||
let nonce_cache = NonceCache::new(NONCE_CACHE_SIZE);
|
|
||||||
let process_transaction = |transaction: &VerifiedPrivateTransaction| -> Result<_, String> {
|
let process_transaction = |transaction: &VerifiedPrivateTransaction| -> Result<_, String> {
|
||||||
let private_hash = transaction.private_transaction.hash();
|
let private_hash = transaction.private_transaction.hash();
|
||||||
match transaction.validator_account {
|
match transaction.validator_account {
|
||||||
@ -292,8 +319,7 @@ impl Provider where {
|
|||||||
let private_state = private_state.expect("Error was checked before");
|
let private_state = private_state.expect("Error was checked before");
|
||||||
let private_state_hash = self.calculate_state_hash(&private_state, contract_nonce);
|
let private_state_hash = self.calculate_state_hash(&private_state, contract_nonce);
|
||||||
trace!(target: "privatetx", "Hashed effective private state for validator: {:?}", private_state_hash);
|
trace!(target: "privatetx", "Hashed effective private state for validator: {:?}", private_state_hash);
|
||||||
let password = find_account_password(&self.passwords, &*self.accounts, &validator_account);
|
let signed_state = self.accounts.sign(validator_account, private_state_hash);
|
||||||
let signed_state = self.accounts.sign(validator_account, password, private_state_hash);
|
|
||||||
if let Err(e) = signed_state {
|
if let Err(e) = signed_state {
|
||||||
bail!("Cannot sign the state: {:?}", e);
|
bail!("Cannot sign the state: {:?}", e);
|
||||||
}
|
}
|
||||||
@ -305,7 +331,9 @@ impl Provider where {
|
|||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
};
|
};
|
||||||
let ready_transactions = self.transactions_for_verification.drain(self.pool_client(&nonce_cache));
|
let nonce_cache = NonceCache::new(NONCE_CACHE_SIZE);
|
||||||
|
let local_accounts = HashSet::new();
|
||||||
|
let ready_transactions = self.transactions_for_verification.drain(self.pool_client(&nonce_cache, &local_accounts));
|
||||||
for transaction in ready_transactions {
|
for transaction in ready_transactions {
|
||||||
if let Err(e) = process_transaction(&transaction) {
|
if let Err(e) = process_transaction(&transaction) {
|
||||||
warn!(target: "privatetx", "Error: {:?}", e);
|
warn!(target: "privatetx", "Error: {:?}", e);
|
||||||
@ -346,8 +374,7 @@ impl Provider where {
|
|||||||
let chain_id = desc.original_transaction.chain_id();
|
let chain_id = desc.original_transaction.chain_id();
|
||||||
let hash = public_tx.hash(chain_id);
|
let hash = public_tx.hash(chain_id);
|
||||||
let signer_account = self.signer_account.ok_or_else(|| ErrorKind::SignerAccountNotSet)?;
|
let signer_account = self.signer_account.ok_or_else(|| ErrorKind::SignerAccountNotSet)?;
|
||||||
let password = find_account_password(&self.passwords, &*self.accounts, &signer_account);
|
let signature = self.accounts.sign(signer_account, hash)?;
|
||||||
let signature = self.accounts.sign(signer_account, password, hash)?;
|
|
||||||
let signed = SignedTransaction::new(public_tx.with_signature(signature, chain_id))?;
|
let signed = SignedTransaction::new(public_tx.with_signature(signature, chain_id))?;
|
||||||
match self.miner.import_own_transaction(&*self.client, signed.into()) {
|
match self.miner.import_own_transaction(&*self.client, signed.into()) {
|
||||||
Ok(_) => trace!(target: "privatetx", "Public transaction added to queue"),
|
Ok(_) => trace!(target: "privatetx", "Public transaction added to queue"),
|
||||||
@ -442,12 +469,12 @@ impl Provider where {
|
|||||||
|
|
||||||
fn encrypt(&self, contract_address: &Address, initialisation_vector: &H128, data: &[u8]) -> Result<Bytes, Error> {
|
fn encrypt(&self, contract_address: &Address, initialisation_vector: &H128, data: &[u8]) -> Result<Bytes, Error> {
|
||||||
trace!(target: "privatetx", "Encrypt data using key(address): {:?}", contract_address);
|
trace!(target: "privatetx", "Encrypt data using key(address): {:?}", contract_address);
|
||||||
Ok(self.encryptor.encrypt(contract_address, &*self.accounts, initialisation_vector, data)?)
|
Ok(self.encryptor.encrypt(contract_address, initialisation_vector, data)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn decrypt(&self, contract_address: &Address, data: &[u8]) -> Result<Bytes, Error> {
|
fn decrypt(&self, contract_address: &Address, data: &[u8]) -> Result<Bytes, Error> {
|
||||||
trace!(target: "privatetx", "Decrypt data using key(address): {:?}", contract_address);
|
trace!(target: "privatetx", "Decrypt data using key(address): {:?}", contract_address);
|
||||||
Ok(self.encryptor.decrypt(contract_address, &*self.accounts, data)?)
|
Ok(self.encryptor.decrypt(contract_address, data)?)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_decrypted_state(&self, address: &Address, block: BlockId) -> Result<Bytes, Error> {
|
fn get_decrypted_state(&self, address: &Address, block: BlockId) -> Result<Bytes, Error> {
|
||||||
@ -702,12 +729,13 @@ impl Importer for Arc<Provider> {
|
|||||||
let transaction_bytes = self.decrypt(&contract, &encrypted_data)?;
|
let transaction_bytes = self.decrypt(&contract, &encrypted_data)?;
|
||||||
let original_tx: UnverifiedTransaction = Rlp::new(&transaction_bytes).as_val()?;
|
let original_tx: UnverifiedTransaction = Rlp::new(&transaction_bytes).as_val()?;
|
||||||
let nonce_cache = NonceCache::new(NONCE_CACHE_SIZE);
|
let nonce_cache = NonceCache::new(NONCE_CACHE_SIZE);
|
||||||
|
let local_accounts = HashSet::new();
|
||||||
// Add to the queue for further verification
|
// Add to the queue for further verification
|
||||||
self.transactions_for_verification.add_transaction(
|
self.transactions_for_verification.add_transaction(
|
||||||
original_tx,
|
original_tx,
|
||||||
validation_account.map(|&account| account),
|
validation_account.map(|&account| account),
|
||||||
private_tx,
|
private_tx,
|
||||||
self.pool_client(&nonce_cache),
|
self.pool_client(&nonce_cache, &local_accounts),
|
||||||
)?;
|
)?;
|
||||||
let provider = Arc::downgrade(self);
|
let provider = Arc::downgrade(self);
|
||||||
let result = self.channel.send(ClientIoMessage::execute(move |_| {
|
let result = self.channel.send(ClientIoMessage::execute(move |_| {
|
||||||
@ -742,16 +770,6 @@ impl Importer for Arc<Provider> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Try to unlock account using stored password, return found password if any
|
|
||||||
fn find_account_password(passwords: &Vec<Password>, account_provider: &AccountProvider, account: &Address) -> Option<Password> {
|
|
||||||
for password in passwords {
|
|
||||||
if let Ok(true) = account_provider.test_password(account, password) {
|
|
||||||
return Some(password.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ChainNotify for Provider {
|
impl ChainNotify for Provider {
|
||||||
fn new_blocks(&self, new_blocks: NewBlocks) {
|
fn new_blocks(&self, new_blocks: NewBlocks) {
|
||||||
if new_blocks.imported.is_empty() || new_blocks.has_more_blocks_to_import { return }
|
if new_blocks.imported.is_empty() || new_blocks.has_more_blocks_to_import { return }
|
||||||
|
@ -34,7 +34,6 @@ use rustc_hex::{FromHex, ToHex};
|
|||||||
use types::ids::BlockId;
|
use types::ids::BlockId;
|
||||||
use types::transaction::{Transaction, Action};
|
use types::transaction::{Transaction, Action};
|
||||||
use ethcore::CreateContractAddress;
|
use ethcore::CreateContractAddress;
|
||||||
use ethcore::account_provider::AccountProvider;
|
|
||||||
use ethcore::client::BlockChainClient;
|
use ethcore::client::BlockChainClient;
|
||||||
use ethcore::executive::{contract_address};
|
use ethcore::executive::{contract_address};
|
||||||
use ethcore::miner::Miner;
|
use ethcore::miner::Miner;
|
||||||
@ -54,15 +53,12 @@ fn private_contract() {
|
|||||||
let _key2 = KeyPair::from_secret(Secret::from("0000000000000000000000000000000000000000000000000000000000000012")).unwrap();
|
let _key2 = KeyPair::from_secret(Secret::from("0000000000000000000000000000000000000000000000000000000000000012")).unwrap();
|
||||||
let key3 = KeyPair::from_secret(Secret::from("0000000000000000000000000000000000000000000000000000000000000013")).unwrap();
|
let key3 = KeyPair::from_secret(Secret::from("0000000000000000000000000000000000000000000000000000000000000013")).unwrap();
|
||||||
let key4 = KeyPair::from_secret(Secret::from("0000000000000000000000000000000000000000000000000000000000000014")).unwrap();
|
let key4 = KeyPair::from_secret(Secret::from("0000000000000000000000000000000000000000000000000000000000000014")).unwrap();
|
||||||
let ap = Arc::new(AccountProvider::transient_provider());
|
|
||||||
ap.insert_account(key1.secret().clone(), &"".into()).unwrap();
|
let signer = Arc::new(ethcore_private_tx::KeyPairSigner(vec![key1.clone(), key3.clone(), key4.clone()]));
|
||||||
ap.insert_account(key3.secret().clone(), &"".into()).unwrap();
|
|
||||||
ap.insert_account(key4.secret().clone(), &"".into()).unwrap();
|
|
||||||
|
|
||||||
let config = ProviderConfig{
|
let config = ProviderConfig{
|
||||||
validator_accounts: vec![key3.address(), key4.address()],
|
validator_accounts: vec![key3.address(), key4.address()],
|
||||||
signer_account: None,
|
signer_account: None,
|
||||||
passwords: vec!["".into()],
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let io = ethcore_io::IoChannel::disconnected();
|
let io = ethcore_io::IoChannel::disconnected();
|
||||||
@ -71,7 +67,7 @@ fn private_contract() {
|
|||||||
let pm = Arc::new(Provider::new(
|
let pm = Arc::new(Provider::new(
|
||||||
client.clone(),
|
client.clone(),
|
||||||
miner,
|
miner,
|
||||||
ap.clone(),
|
signer.clone(),
|
||||||
Box::new(NoopEncryptor::default()),
|
Box::new(NoopEncryptor::default()),
|
||||||
config,
|
config,
|
||||||
io,
|
io,
|
||||||
@ -192,15 +188,11 @@ fn call_other_private_contract() {
|
|||||||
let _key2 = KeyPair::from_secret(Secret::from("0000000000000000000000000000000000000000000000000000000000000012")).unwrap();
|
let _key2 = KeyPair::from_secret(Secret::from("0000000000000000000000000000000000000000000000000000000000000012")).unwrap();
|
||||||
let key3 = KeyPair::from_secret(Secret::from("0000000000000000000000000000000000000000000000000000000000000013")).unwrap();
|
let key3 = KeyPair::from_secret(Secret::from("0000000000000000000000000000000000000000000000000000000000000013")).unwrap();
|
||||||
let key4 = KeyPair::from_secret(Secret::from("0000000000000000000000000000000000000000000000000000000000000014")).unwrap();
|
let key4 = KeyPair::from_secret(Secret::from("0000000000000000000000000000000000000000000000000000000000000014")).unwrap();
|
||||||
let ap = Arc::new(AccountProvider::transient_provider());
|
let signer = Arc::new(ethcore_private_tx::KeyPairSigner(vec![key1.clone(), key3.clone(), key4.clone()]));
|
||||||
ap.insert_account(key1.secret().clone(), &"".into()).unwrap();
|
|
||||||
ap.insert_account(key3.secret().clone(), &"".into()).unwrap();
|
|
||||||
ap.insert_account(key4.secret().clone(), &"".into()).unwrap();
|
|
||||||
|
|
||||||
let config = ProviderConfig{
|
let config = ProviderConfig{
|
||||||
validator_accounts: vec![key3.address(), key4.address()],
|
validator_accounts: vec![key3.address(), key4.address()],
|
||||||
signer_account: None,
|
signer_account: None,
|
||||||
passwords: vec!["".into()],
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let io = ethcore_io::IoChannel::disconnected();
|
let io = ethcore_io::IoChannel::disconnected();
|
||||||
@ -209,7 +201,7 @@ fn call_other_private_contract() {
|
|||||||
let pm = Arc::new(Provider::new(
|
let pm = Arc::new(Provider::new(
|
||||||
client.clone(),
|
client.clone(),
|
||||||
miner,
|
miner,
|
||||||
ap.clone(),
|
signer.clone(),
|
||||||
Box::new(NoopEncryptor::default()),
|
Box::new(NoopEncryptor::default()),
|
||||||
config,
|
config,
|
||||||
io,
|
io,
|
||||||
|
@ -32,9 +32,8 @@ use ethcore::miner::Miner;
|
|||||||
use ethcore::snapshot::service::{Service as SnapshotService, ServiceParams as SnapServiceParams};
|
use ethcore::snapshot::service::{Service as SnapshotService, ServiceParams as SnapServiceParams};
|
||||||
use ethcore::snapshot::{SnapshotService as _SnapshotService, RestorationStatus};
|
use ethcore::snapshot::{SnapshotService as _SnapshotService, RestorationStatus};
|
||||||
use ethcore::spec::Spec;
|
use ethcore::spec::Spec;
|
||||||
use ethcore::account_provider::AccountProvider;
|
|
||||||
|
|
||||||
use ethcore_private_tx::{self, Importer};
|
use ethcore_private_tx::{self, Importer, Signer};
|
||||||
use Error;
|
use Error;
|
||||||
|
|
||||||
pub struct PrivateTxService {
|
pub struct PrivateTxService {
|
||||||
@ -96,7 +95,7 @@ impl ClientService {
|
|||||||
restoration_db_handler: Box<BlockChainDBHandler>,
|
restoration_db_handler: Box<BlockChainDBHandler>,
|
||||||
_ipc_path: &Path,
|
_ipc_path: &Path,
|
||||||
miner: Arc<Miner>,
|
miner: Arc<Miner>,
|
||||||
account_provider: Arc<AccountProvider>,
|
signer: Arc<Signer>,
|
||||||
encryptor: Box<ethcore_private_tx::Encryptor>,
|
encryptor: Box<ethcore_private_tx::Encryptor>,
|
||||||
private_tx_conf: ethcore_private_tx::ProviderConfig,
|
private_tx_conf: ethcore_private_tx::ProviderConfig,
|
||||||
private_encryptor_conf: ethcore_private_tx::EncryptorConfig,
|
private_encryptor_conf: ethcore_private_tx::EncryptorConfig,
|
||||||
@ -135,7 +134,7 @@ impl ClientService {
|
|||||||
let provider = Arc::new(ethcore_private_tx::Provider::new(
|
let provider = Arc::new(ethcore_private_tx::Provider::new(
|
||||||
client.clone(),
|
client.clone(),
|
||||||
miner,
|
miner,
|
||||||
account_provider,
|
signer,
|
||||||
encryptor,
|
encryptor,
|
||||||
private_tx_conf,
|
private_tx_conf,
|
||||||
io_service.channel(),
|
io_service.channel(),
|
||||||
@ -282,7 +281,6 @@ mod tests {
|
|||||||
use tempdir::TempDir;
|
use tempdir::TempDir;
|
||||||
|
|
||||||
use ethcore_db::NUM_COLUMNS;
|
use ethcore_db::NUM_COLUMNS;
|
||||||
use ethcore::account_provider::AccountProvider;
|
|
||||||
use ethcore::client::ClientConfig;
|
use ethcore::client::ClientConfig;
|
||||||
use ethcore::miner::Miner;
|
use ethcore::miner::Miner;
|
||||||
use ethcore::spec::Spec;
|
use ethcore::spec::Spec;
|
||||||
@ -317,7 +315,7 @@ mod tests {
|
|||||||
restoration_db_handler,
|
restoration_db_handler,
|
||||||
tempdir.path(),
|
tempdir.path(),
|
||||||
Arc::new(Miner::new_for_tests(&spec, None)),
|
Arc::new(Miner::new_for_tests(&spec, None)),
|
||||||
Arc::new(AccountProvider::transient_provider()),
|
Arc::new(ethcore_private_tx::DummySigner),
|
||||||
Box::new(ethcore_private_tx::NoopEncryptor),
|
Box::new(ethcore_private_tx::NoopEncryptor),
|
||||||
Default::default(),
|
Default::default(),
|
||||||
Default::default(),
|
Default::default(),
|
||||||
|
@ -24,7 +24,6 @@ use std::sync::atomic::{AtomicUsize, AtomicBool, Ordering as AtomicOrdering};
|
|||||||
use std::sync::{Weak, Arc};
|
use std::sync::{Weak, Arc};
|
||||||
use std::time::{UNIX_EPOCH, SystemTime, Duration};
|
use std::time::{UNIX_EPOCH, SystemTime, Duration};
|
||||||
|
|
||||||
use account_provider::AccountProvider;
|
|
||||||
use block::*;
|
use block::*;
|
||||||
use client::EngineClient;
|
use client::EngineClient;
|
||||||
use engines::{Engine, Seal, EngineError, ConstructedVerifier};
|
use engines::{Engine, Seal, EngineError, ConstructedVerifier};
|
||||||
@ -37,7 +36,7 @@ use hash::keccak;
|
|||||||
use super::signer::EngineSigner;
|
use super::signer::EngineSigner;
|
||||||
use super::validator_set::{ValidatorSet, SimpleList, new_validator_set};
|
use super::validator_set::{ValidatorSet, SimpleList, new_validator_set};
|
||||||
use self::finality::RollingFinality;
|
use self::finality::RollingFinality;
|
||||||
use ethkey::{self, Password, Signature};
|
use ethkey::{self, Signature};
|
||||||
use io::{IoContext, IoHandler, TimerToken, IoService};
|
use io::{IoContext, IoHandler, TimerToken, IoService};
|
||||||
use itertools::{self, Itertools};
|
use itertools::{self, Itertools};
|
||||||
use rlp::{encode, Decodable, DecoderError, Encodable, RlpStream, Rlp};
|
use rlp::{encode, Decodable, DecoderError, Encodable, RlpStream, Rlp};
|
||||||
@ -412,7 +411,7 @@ pub struct AuthorityRound {
|
|||||||
transition_service: IoService<()>,
|
transition_service: IoService<()>,
|
||||||
step: Arc<PermissionedStep>,
|
step: Arc<PermissionedStep>,
|
||||||
client: Arc<RwLock<Option<Weak<EngineClient>>>>,
|
client: Arc<RwLock<Option<Weak<EngineClient>>>>,
|
||||||
signer: RwLock<EngineSigner>,
|
signer: RwLock<Option<Box<EngineSigner>>>,
|
||||||
validators: Box<ValidatorSet>,
|
validators: Box<ValidatorSet>,
|
||||||
validate_score_transition: u64,
|
validate_score_transition: u64,
|
||||||
validate_step_transition: u64,
|
validate_step_transition: u64,
|
||||||
@ -665,7 +664,7 @@ impl AuthorityRound {
|
|||||||
can_propose: AtomicBool::new(true),
|
can_propose: AtomicBool::new(true),
|
||||||
}),
|
}),
|
||||||
client: Arc::new(RwLock::new(None)),
|
client: Arc::new(RwLock::new(None)),
|
||||||
signer: Default::default(),
|
signer: RwLock::new(None),
|
||||||
validators: our_params.validators,
|
validators: our_params.validators,
|
||||||
validate_score_transition: our_params.validate_score_transition,
|
validate_score_transition: our_params.validate_score_transition,
|
||||||
validate_step_transition: our_params.validate_step_transition,
|
validate_step_transition: our_params.validate_step_transition,
|
||||||
@ -788,7 +787,7 @@ impl AuthorityRound {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let (true, Some(me)) = (current_step > parent_step + 1, self.signer.read().address()) {
|
if let (true, Some(me)) = (current_step > parent_step + 1, self.signer.read().as_ref().map(|s| s.address())) {
|
||||||
debug!(target: "engine", "Author {} built block with step gap. current step: {}, parent step: {}",
|
debug!(target: "engine", "Author {} built block with step gap. current step: {}, parent step: {}",
|
||||||
header.author(), current_step, parent_step);
|
header.author(), current_step, parent_step);
|
||||||
let mut reported = HashSet::new();
|
let mut reported = HashSet::new();
|
||||||
@ -1492,12 +1491,16 @@ impl Engine<EthereumMachine> for AuthorityRound {
|
|||||||
self.validators.register_client(client);
|
self.validators.register_client(client);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_signer(&self, ap: Arc<AccountProvider>, address: Address, password: Password) {
|
fn set_signer(&self, signer: Box<EngineSigner>) {
|
||||||
self.signer.write().set(ap, address, password);
|
*self.signer.write() = Some(signer);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sign(&self, hash: H256) -> Result<Signature, Error> {
|
fn sign(&self, hash: H256) -> Result<Signature, Error> {
|
||||||
Ok(self.signer.read().sign(hash)?)
|
Ok(self.signer.read()
|
||||||
|
.as_ref()
|
||||||
|
.ok_or(ethkey::Error::InvalidAddress)?
|
||||||
|
.sign(hash)?
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn snapshot_components(&self) -> Option<Box<::snapshot::SnapshotComponents>> {
|
fn snapshot_components(&self) -> Option<Box<::snapshot::SnapshotComponents>> {
|
||||||
@ -1532,16 +1535,16 @@ mod tests {
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
|
use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};
|
||||||
use hash::keccak;
|
use hash::keccak;
|
||||||
|
use accounts::AccountProvider;
|
||||||
use ethereum_types::{Address, H520, H256, U256};
|
use ethereum_types::{Address, H520, H256, U256};
|
||||||
use ethkey::Signature;
|
use ethkey::Signature;
|
||||||
use types::header::Header;
|
use types::header::Header;
|
||||||
use rlp::encode;
|
use rlp::encode;
|
||||||
use block::*;
|
use block::*;
|
||||||
use test_helpers::{
|
use test_helpers::{
|
||||||
generate_dummy_client_with_spec_and_accounts, get_temp_state_db,
|
generate_dummy_client_with_spec, get_temp_state_db,
|
||||||
TestNotify
|
TestNotify
|
||||||
};
|
};
|
||||||
use account_provider::AccountProvider;
|
|
||||||
use spec::Spec;
|
use spec::Spec;
|
||||||
use types::transaction::{Action, Transaction};
|
use types::transaction::{Action, Transaction};
|
||||||
use engines::{Seal, Engine, EngineError, EthEngine};
|
use engines::{Seal, Engine, EngineError, EthEngine};
|
||||||
@ -1620,14 +1623,14 @@ mod tests {
|
|||||||
let b2 = OpenBlock::new(engine, Default::default(), false, db2, &genesis_header, last_hashes, addr2, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap();
|
let b2 = OpenBlock::new(engine, Default::default(), false, db2, &genesis_header, last_hashes, addr2, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap();
|
||||||
let b2 = b2.close_and_lock().unwrap();
|
let b2 = b2.close_and_lock().unwrap();
|
||||||
|
|
||||||
engine.set_signer(tap.clone(), addr1, "1".into());
|
engine.set_signer(Box::new((tap.clone(), addr1, "1".into())));
|
||||||
if let Seal::Regular(seal) = engine.generate_seal(b1.block(), &genesis_header) {
|
if let Seal::Regular(seal) = engine.generate_seal(b1.block(), &genesis_header) {
|
||||||
assert!(b1.clone().try_seal(engine, seal).is_ok());
|
assert!(b1.clone().try_seal(engine, seal).is_ok());
|
||||||
// Second proposal is forbidden.
|
// Second proposal is forbidden.
|
||||||
assert!(engine.generate_seal(b1.block(), &genesis_header) == Seal::None);
|
assert!(engine.generate_seal(b1.block(), &genesis_header) == Seal::None);
|
||||||
}
|
}
|
||||||
|
|
||||||
engine.set_signer(tap, addr2, "2".into());
|
engine.set_signer(Box::new((tap, addr2, "2".into())));
|
||||||
if let Seal::Regular(seal) = engine.generate_seal(b2.block(), &genesis_header) {
|
if let Seal::Regular(seal) = engine.generate_seal(b2.block(), &genesis_header) {
|
||||||
assert!(b2.clone().try_seal(engine, seal).is_ok());
|
assert!(b2.clone().try_seal(engine, seal).is_ok());
|
||||||
// Second proposal is forbidden.
|
// Second proposal is forbidden.
|
||||||
@ -1654,13 +1657,13 @@ mod tests {
|
|||||||
let b2 = OpenBlock::new(engine, Default::default(), false, db2, &genesis_header, last_hashes, addr2, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap();
|
let b2 = OpenBlock::new(engine, Default::default(), false, db2, &genesis_header, last_hashes, addr2, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap();
|
||||||
let b2 = b2.close_and_lock().unwrap();
|
let b2 = b2.close_and_lock().unwrap();
|
||||||
|
|
||||||
engine.set_signer(tap.clone(), addr1, "1".into());
|
engine.set_signer(Box::new((tap.clone(), addr1, "1".into())));
|
||||||
match engine.generate_seal(b1.block(), &genesis_header) {
|
match engine.generate_seal(b1.block(), &genesis_header) {
|
||||||
Seal::None | Seal::Proposal(_) => panic!("wrong seal"),
|
Seal::None | Seal::Proposal(_) => panic!("wrong seal"),
|
||||||
Seal::Regular(_) => {
|
Seal::Regular(_) => {
|
||||||
engine.step();
|
engine.step();
|
||||||
|
|
||||||
engine.set_signer(tap.clone(), addr2, "0".into());
|
engine.set_signer(Box::new((tap.clone(), addr2, "0".into())));
|
||||||
match engine.generate_seal(b2.block(), &genesis_header) {
|
match engine.generate_seal(b2.block(), &genesis_header) {
|
||||||
Seal::Regular(_) | Seal::Proposal(_) => panic!("sealed despite wrong difficulty"),
|
Seal::Regular(_) | Seal::Proposal(_) => panic!("sealed despite wrong difficulty"),
|
||||||
Seal::None => {}
|
Seal::None => {}
|
||||||
@ -1768,7 +1771,7 @@ mod tests {
|
|||||||
assert!(aura.verify_block_family(&header, &parent_header).is_ok());
|
assert!(aura.verify_block_family(&header, &parent_header).is_ok());
|
||||||
assert_eq!(last_benign.load(AtomicOrdering::SeqCst), 0);
|
assert_eq!(last_benign.load(AtomicOrdering::SeqCst), 0);
|
||||||
|
|
||||||
aura.set_signer(Arc::new(AccountProvider::transient_provider()), Default::default(), "".into());
|
aura.set_signer(Box::new((Arc::new(AccountProvider::transient_provider()), Default::default(), "".into())));
|
||||||
|
|
||||||
// Do not report on steps skipped between genesis and first block.
|
// Do not report on steps skipped between genesis and first block.
|
||||||
header.set_number(1);
|
header.set_number(1);
|
||||||
@ -1878,12 +1881,12 @@ mod tests {
|
|||||||
|
|
||||||
let last_hashes = Arc::new(vec![genesis_header.hash()]);
|
let last_hashes = Arc::new(vec![genesis_header.hash()]);
|
||||||
|
|
||||||
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_test_round_empty_steps, None);
|
let client = generate_dummy_client_with_spec(Spec::new_test_round_empty_steps);
|
||||||
let notify = Arc::new(TestNotify::default());
|
let notify = Arc::new(TestNotify::default());
|
||||||
client.add_notify(notify.clone());
|
client.add_notify(notify.clone());
|
||||||
engine.register_client(Arc::downgrade(&client) as _);
|
engine.register_client(Arc::downgrade(&client) as _);
|
||||||
|
|
||||||
engine.set_signer(tap.clone(), addr1, "1".into());
|
engine.set_signer(Box::new((tap.clone(), addr1, "1".into())));
|
||||||
|
|
||||||
let b1 = OpenBlock::new(engine, Default::default(), false, db1, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap();
|
let b1 = OpenBlock::new(engine, Default::default(), false, db1, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap();
|
||||||
let b1 = b1.close_and_lock().unwrap();
|
let b1 = b1.close_and_lock().unwrap();
|
||||||
@ -1917,7 +1920,7 @@ mod tests {
|
|||||||
|
|
||||||
let last_hashes = Arc::new(vec![genesis_header.hash()]);
|
let last_hashes = Arc::new(vec![genesis_header.hash()]);
|
||||||
|
|
||||||
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_test_round_empty_steps, None);
|
let client = generate_dummy_client_with_spec(Spec::new_test_round_empty_steps);
|
||||||
let notify = Arc::new(TestNotify::default());
|
let notify = Arc::new(TestNotify::default());
|
||||||
client.add_notify(notify.clone());
|
client.add_notify(notify.clone());
|
||||||
engine.register_client(Arc::downgrade(&client) as _);
|
engine.register_client(Arc::downgrade(&client) as _);
|
||||||
@ -1927,7 +1930,7 @@ mod tests {
|
|||||||
let b1 = b1.close_and_lock().unwrap();
|
let b1 = b1.close_and_lock().unwrap();
|
||||||
|
|
||||||
// since the block is empty it isn't sealed and we generate empty steps
|
// since the block is empty it isn't sealed and we generate empty steps
|
||||||
engine.set_signer(tap.clone(), addr1, "1".into());
|
engine.set_signer(Box::new((tap.clone(), addr1, "1".into())));
|
||||||
assert_eq!(engine.generate_seal(b1.block(), &genesis_header), Seal::None);
|
assert_eq!(engine.generate_seal(b1.block(), &genesis_header), Seal::None);
|
||||||
engine.step();
|
engine.step();
|
||||||
|
|
||||||
@ -1944,9 +1947,9 @@ mod tests {
|
|||||||
let b2 = b2.close_and_lock().unwrap();
|
let b2 = b2.close_and_lock().unwrap();
|
||||||
|
|
||||||
// we will now seal a block with 1tx and include the accumulated empty step message
|
// we will now seal a block with 1tx and include the accumulated empty step message
|
||||||
engine.set_signer(tap.clone(), addr2, "0".into());
|
engine.set_signer(Box::new((tap.clone(), addr2, "0".into())));
|
||||||
if let Seal::Regular(seal) = engine.generate_seal(b2.block(), &genesis_header) {
|
if let Seal::Regular(seal) = engine.generate_seal(b2.block(), &genesis_header) {
|
||||||
engine.set_signer(tap.clone(), addr1, "1".into());
|
engine.set_signer(Box::new((tap.clone(), addr1, "1".into())));
|
||||||
let empty_step2 = sealed_empty_step(engine, 2, &genesis_header.hash());
|
let empty_step2 = sealed_empty_step(engine, 2, &genesis_header.hash());
|
||||||
let empty_steps = ::rlp::encode_list(&vec![empty_step2]);
|
let empty_steps = ::rlp::encode_list(&vec![empty_step2]);
|
||||||
|
|
||||||
@ -1970,7 +1973,7 @@ mod tests {
|
|||||||
|
|
||||||
let last_hashes = Arc::new(vec![genesis_header.hash()]);
|
let last_hashes = Arc::new(vec![genesis_header.hash()]);
|
||||||
|
|
||||||
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_test_round_empty_steps, None);
|
let client = generate_dummy_client_with_spec(Spec::new_test_round_empty_steps);
|
||||||
let notify = Arc::new(TestNotify::default());
|
let notify = Arc::new(TestNotify::default());
|
||||||
client.add_notify(notify.clone());
|
client.add_notify(notify.clone());
|
||||||
engine.register_client(Arc::downgrade(&client) as _);
|
engine.register_client(Arc::downgrade(&client) as _);
|
||||||
@ -1980,14 +1983,14 @@ mod tests {
|
|||||||
let b1 = b1.close_and_lock().unwrap();
|
let b1 = b1.close_and_lock().unwrap();
|
||||||
|
|
||||||
// since the block is empty it isn't sealed and we generate empty steps
|
// since the block is empty it isn't sealed and we generate empty steps
|
||||||
engine.set_signer(tap.clone(), addr1, "1".into());
|
engine.set_signer(Box::new((tap.clone(), addr1, "1".into())));
|
||||||
assert_eq!(engine.generate_seal(b1.block(), &genesis_header), Seal::None);
|
assert_eq!(engine.generate_seal(b1.block(), &genesis_header), Seal::None);
|
||||||
engine.step();
|
engine.step();
|
||||||
|
|
||||||
// step 3
|
// step 3
|
||||||
let b2 = OpenBlock::new(engine, Default::default(), false, db2, &genesis_header, last_hashes.clone(), addr2, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap();
|
let b2 = OpenBlock::new(engine, Default::default(), false, db2, &genesis_header, last_hashes.clone(), addr2, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap();
|
||||||
let b2 = b2.close_and_lock().unwrap();
|
let b2 = b2.close_and_lock().unwrap();
|
||||||
engine.set_signer(tap.clone(), addr2, "0".into());
|
engine.set_signer(Box::new((tap.clone(), addr2, "0".into())));
|
||||||
assert_eq!(engine.generate_seal(b2.block(), &genesis_header), Seal::None);
|
assert_eq!(engine.generate_seal(b2.block(), &genesis_header), Seal::None);
|
||||||
engine.step();
|
engine.step();
|
||||||
|
|
||||||
@ -1996,10 +1999,10 @@ mod tests {
|
|||||||
let b3 = OpenBlock::new(engine, Default::default(), false, db3, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap();
|
let b3 = OpenBlock::new(engine, Default::default(), false, db3, &genesis_header, last_hashes.clone(), addr1, (3141562.into(), 31415620.into()), vec![], false, &mut Vec::new().into_iter()).unwrap();
|
||||||
let b3 = b3.close_and_lock().unwrap();
|
let b3 = b3.close_and_lock().unwrap();
|
||||||
|
|
||||||
engine.set_signer(tap.clone(), addr1, "1".into());
|
engine.set_signer(Box::new((tap.clone(), addr1, "1".into())));
|
||||||
if let Seal::Regular(seal) = engine.generate_seal(b3.block(), &genesis_header) {
|
if let Seal::Regular(seal) = engine.generate_seal(b3.block(), &genesis_header) {
|
||||||
let empty_step2 = sealed_empty_step(engine, 2, &genesis_header.hash());
|
let empty_step2 = sealed_empty_step(engine, 2, &genesis_header.hash());
|
||||||
engine.set_signer(tap.clone(), addr2, "0".into());
|
engine.set_signer(Box::new((tap.clone(), addr2, "0".into())));
|
||||||
let empty_step3 = sealed_empty_step(engine, 3, &genesis_header.hash());
|
let empty_step3 = sealed_empty_step(engine, 3, &genesis_header.hash());
|
||||||
|
|
||||||
let empty_steps = ::rlp::encode_list(&vec![empty_step2, empty_step3]);
|
let empty_steps = ::rlp::encode_list(&vec![empty_step2, empty_step3]);
|
||||||
@ -2022,7 +2025,7 @@ mod tests {
|
|||||||
|
|
||||||
let last_hashes = Arc::new(vec![genesis_header.hash()]);
|
let last_hashes = Arc::new(vec![genesis_header.hash()]);
|
||||||
|
|
||||||
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_test_round_empty_steps, None);
|
let client = generate_dummy_client_with_spec(Spec::new_test_round_empty_steps);
|
||||||
engine.register_client(Arc::downgrade(&client) as _);
|
engine.register_client(Arc::downgrade(&client) as _);
|
||||||
|
|
||||||
// step 2
|
// step 2
|
||||||
@ -2030,7 +2033,7 @@ mod tests {
|
|||||||
let b1 = b1.close_and_lock().unwrap();
|
let b1 = b1.close_and_lock().unwrap();
|
||||||
|
|
||||||
// since the block is empty it isn't sealed and we generate empty steps
|
// since the block is empty it isn't sealed and we generate empty steps
|
||||||
engine.set_signer(tap.clone(), addr1, "1".into());
|
engine.set_signer(Box::new((tap.clone(), addr1, "1".into())));
|
||||||
assert_eq!(engine.generate_seal(b1.block(), &genesis_header), Seal::None);
|
assert_eq!(engine.generate_seal(b1.block(), &genesis_header), Seal::None);
|
||||||
engine.step();
|
engine.step();
|
||||||
|
|
||||||
@ -2084,7 +2087,7 @@ mod tests {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// empty step with valid signature from incorrect proposer for step
|
// empty step with valid signature from incorrect proposer for step
|
||||||
engine.set_signer(tap.clone(), addr1, "1".into());
|
engine.set_signer(Box::new((tap.clone(), addr1, "1".into())));
|
||||||
let empty_steps = vec![sealed_empty_step(engine, 1, &parent_header.hash())];
|
let empty_steps = vec![sealed_empty_step(engine, 1, &parent_header.hash())];
|
||||||
set_empty_steps_seal(&mut header, 2, &signature, &empty_steps);
|
set_empty_steps_seal(&mut header, 2, &signature, &empty_steps);
|
||||||
|
|
||||||
@ -2094,9 +2097,9 @@ mod tests {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// valid empty steps
|
// valid empty steps
|
||||||
engine.set_signer(tap.clone(), addr1, "1".into());
|
engine.set_signer(Box::new((tap.clone(), addr1, "1".into())));
|
||||||
let empty_step2 = sealed_empty_step(engine, 2, &parent_header.hash());
|
let empty_step2 = sealed_empty_step(engine, 2, &parent_header.hash());
|
||||||
engine.set_signer(tap.clone(), addr2, "0".into());
|
engine.set_signer(Box::new((tap.clone(), addr2, "0".into())));
|
||||||
let empty_step3 = sealed_empty_step(engine, 3, &parent_header.hash());
|
let empty_step3 = sealed_empty_step(engine, 3, &parent_header.hash());
|
||||||
|
|
||||||
let empty_steps = vec![empty_step2, empty_step3];
|
let empty_steps = vec![empty_step2, empty_step3];
|
||||||
@ -2121,10 +2124,7 @@ mod tests {
|
|||||||
|
|
||||||
let last_hashes = Arc::new(vec![genesis_header.hash()]);
|
let last_hashes = Arc::new(vec![genesis_header.hash()]);
|
||||||
|
|
||||||
let client = generate_dummy_client_with_spec_and_accounts(
|
let client = generate_dummy_client_with_spec(Spec::new_test_round_block_reward_contract);
|
||||||
Spec::new_test_round_block_reward_contract,
|
|
||||||
None,
|
|
||||||
);
|
|
||||||
engine.register_client(Arc::downgrade(&client) as _);
|
engine.register_client(Arc::downgrade(&client) as _);
|
||||||
|
|
||||||
// step 2
|
// step 2
|
||||||
@ -2144,7 +2144,7 @@ mod tests {
|
|||||||
let b1 = b1.close_and_lock().unwrap();
|
let b1 = b1.close_and_lock().unwrap();
|
||||||
|
|
||||||
// since the block is empty it isn't sealed and we generate empty steps
|
// since the block is empty it isn't sealed and we generate empty steps
|
||||||
engine.set_signer(tap.clone(), addr1, "1".into());
|
engine.set_signer(Box::new((tap.clone(), addr1, "1".into())));
|
||||||
assert_eq!(engine.generate_seal(b1.block(), &genesis_header), Seal::None);
|
assert_eq!(engine.generate_seal(b1.block(), &genesis_header), Seal::None);
|
||||||
engine.step();
|
engine.step();
|
||||||
|
|
||||||
@ -2182,7 +2182,7 @@ mod tests {
|
|||||||
let engine = &*spec.engine;
|
let engine = &*spec.engine;
|
||||||
|
|
||||||
let addr1 = accounts[0];
|
let addr1 = accounts[0];
|
||||||
engine.set_signer(tap.clone(), addr1, "1".into());
|
engine.set_signer(Box::new((tap.clone(), addr1, "1".into())));
|
||||||
|
|
||||||
let mut header: Header = Header::default();
|
let mut header: Header = Header::default();
|
||||||
let empty_step = empty_step(engine, 1, &header.parent_hash());
|
let empty_step = empty_step(engine, 1, &header.parent_hash());
|
||||||
@ -2263,7 +2263,7 @@ mod tests {
|
|||||||
header.set_author(accounts[0]);
|
header.set_author(accounts[0]);
|
||||||
|
|
||||||
// when
|
// when
|
||||||
engine.set_signer(tap.clone(), accounts[1], "0".into());
|
engine.set_signer(Box::new((tap.clone(), accounts[1], "0".into())));
|
||||||
let empty_steps = vec![
|
let empty_steps = vec![
|
||||||
sealed_empty_step(&*engine, 1, &parent.hash()),
|
sealed_empty_step(&*engine, 1, &parent.hash()),
|
||||||
sealed_empty_step(&*engine, 1, &parent.hash()),
|
sealed_empty_step(&*engine, 1, &parent.hash()),
|
||||||
@ -2300,9 +2300,9 @@ mod tests {
|
|||||||
header.set_author(accounts[0]);
|
header.set_author(accounts[0]);
|
||||||
|
|
||||||
// when
|
// when
|
||||||
engine.set_signer(tap.clone(), accounts[1], "0".into());
|
engine.set_signer(Box::new((tap.clone(), accounts[1], "0".into())));
|
||||||
let es1 = sealed_empty_step(&*engine, 1, &parent.hash());
|
let es1 = sealed_empty_step(&*engine, 1, &parent.hash());
|
||||||
engine.set_signer(tap.clone(), accounts[0], "1".into());
|
engine.set_signer(Box::new((tap.clone(), accounts[0], "1".into())));
|
||||||
let es2 = sealed_empty_step(&*engine, 2, &parent.hash());
|
let es2 = sealed_empty_step(&*engine, 2, &parent.hash());
|
||||||
|
|
||||||
let mut empty_steps = vec![es2, es1];
|
let mut empty_steps = vec![es2, es1];
|
||||||
|
@ -16,19 +16,18 @@
|
|||||||
|
|
||||||
//! A blockchain engine that supports a basic, non-BFT proof-of-authority.
|
//! A blockchain engine that supports a basic, non-BFT proof-of-authority.
|
||||||
|
|
||||||
use std::sync::{Weak, Arc};
|
use std::sync::Weak;
|
||||||
use ethereum_types::{H256, H520, Address};
|
use ethereum_types::{H256, H520};
|
||||||
use parking_lot::RwLock;
|
use parking_lot::RwLock;
|
||||||
use ethkey::{self, Password, Signature};
|
use ethkey::{self, Signature};
|
||||||
use account_provider::AccountProvider;
|
|
||||||
use block::*;
|
use block::*;
|
||||||
use engines::{Engine, Seal, ConstructedVerifier, EngineError};
|
use engines::{Engine, Seal, ConstructedVerifier, EngineError};
|
||||||
|
use engines::signer::EngineSigner;
|
||||||
use error::{BlockError, Error};
|
use error::{BlockError, Error};
|
||||||
use ethjson;
|
use ethjson;
|
||||||
use client::EngineClient;
|
use client::EngineClient;
|
||||||
use machine::{AuxiliaryData, Call, EthereumMachine};
|
use machine::{AuxiliaryData, Call, EthereumMachine};
|
||||||
use types::header::{Header, ExtendedHeader};
|
use types::header::{Header, ExtendedHeader};
|
||||||
use super::signer::EngineSigner;
|
|
||||||
use super::validator_set::{ValidatorSet, SimpleList, new_validator_set};
|
use super::validator_set::{ValidatorSet, SimpleList, new_validator_set};
|
||||||
|
|
||||||
/// `BasicAuthority` params.
|
/// `BasicAuthority` params.
|
||||||
@ -76,7 +75,7 @@ fn verify_external(header: &Header, validators: &ValidatorSet) -> Result<(), Err
|
|||||||
/// Engine using `BasicAuthority`, trivial proof-of-authority consensus.
|
/// Engine using `BasicAuthority`, trivial proof-of-authority consensus.
|
||||||
pub struct BasicAuthority {
|
pub struct BasicAuthority {
|
||||||
machine: EthereumMachine,
|
machine: EthereumMachine,
|
||||||
signer: RwLock<EngineSigner>,
|
signer: RwLock<Option<Box<EngineSigner>>>,
|
||||||
validators: Box<ValidatorSet>,
|
validators: Box<ValidatorSet>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -85,7 +84,7 @@ impl BasicAuthority {
|
|||||||
pub fn new(our_params: BasicAuthorityParams, machine: EthereumMachine) -> Self {
|
pub fn new(our_params: BasicAuthorityParams, machine: EthereumMachine) -> Self {
|
||||||
BasicAuthority {
|
BasicAuthority {
|
||||||
machine: machine,
|
machine: machine,
|
||||||
signer: Default::default(),
|
signer: RwLock::new(None),
|
||||||
validators: new_validator_set(our_params.validators),
|
validators: new_validator_set(our_params.validators),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -190,12 +189,16 @@ impl Engine<EthereumMachine> for BasicAuthority {
|
|||||||
self.validators.register_client(client);
|
self.validators.register_client(client);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_signer(&self, ap: Arc<AccountProvider>, address: Address, password: Password) {
|
fn set_signer(&self, signer: Box<EngineSigner>) {
|
||||||
self.signer.write().set(ap, address, password);
|
*self.signer.write() = Some(signer);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sign(&self, hash: H256) -> Result<Signature, Error> {
|
fn sign(&self, hash: H256) -> Result<Signature, Error> {
|
||||||
Ok(self.signer.read().sign(hash)?)
|
Ok(self.signer.read()
|
||||||
|
.as_ref()
|
||||||
|
.ok_or_else(|| ethkey::Error::InvalidAddress)?
|
||||||
|
.sign(hash)?
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn snapshot_components(&self) -> Option<Box<::snapshot::SnapshotComponents>> {
|
fn snapshot_components(&self) -> Option<Box<::snapshot::SnapshotComponents>> {
|
||||||
@ -214,7 +217,7 @@ mod tests {
|
|||||||
use ethereum_types::H520;
|
use ethereum_types::H520;
|
||||||
use block::*;
|
use block::*;
|
||||||
use test_helpers::get_temp_state_db;
|
use test_helpers::get_temp_state_db;
|
||||||
use account_provider::AccountProvider;
|
use accounts::AccountProvider;
|
||||||
use types::header::Header;
|
use types::header::Header;
|
||||||
use spec::Spec;
|
use spec::Spec;
|
||||||
use engines::Seal;
|
use engines::Seal;
|
||||||
@ -257,7 +260,7 @@ mod tests {
|
|||||||
|
|
||||||
let spec = new_test_authority();
|
let spec = new_test_authority();
|
||||||
let engine = &*spec.engine;
|
let engine = &*spec.engine;
|
||||||
engine.set_signer(Arc::new(tap), addr, "".into());
|
engine.set_signer(Box::new((Arc::new(tap), addr, "".into())));
|
||||||
let genesis_header = spec.genesis_header();
|
let genesis_header = spec.genesis_header();
|
||||||
let db = spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap();
|
let db = spec.ensure_db_good(get_temp_state_db(), &Default::default()).unwrap();
|
||||||
let last_hashes = Arc::new(vec![genesis_header.hash()]);
|
let last_hashes = Arc::new(vec![genesis_header.hash()]);
|
||||||
@ -275,7 +278,7 @@ mod tests {
|
|||||||
|
|
||||||
let engine = new_test_authority().engine;
|
let engine = new_test_authority().engine;
|
||||||
assert!(!engine.seals_internally().unwrap());
|
assert!(!engine.seals_internally().unwrap());
|
||||||
engine.set_signer(Arc::new(tap), authority, "".into());
|
engine.set_signer(Box::new((Arc::new(tap), authority, "".into())));
|
||||||
assert!(engine.seals_internally().unwrap());
|
assert!(engine.seals_internally().unwrap());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -170,17 +170,14 @@ mod test {
|
|||||||
use client::PrepareOpenBlock;
|
use client::PrepareOpenBlock;
|
||||||
use ethereum_types::U256;
|
use ethereum_types::U256;
|
||||||
use spec::Spec;
|
use spec::Spec;
|
||||||
use test_helpers::generate_dummy_client_with_spec_and_accounts;
|
use test_helpers::generate_dummy_client_with_spec;
|
||||||
|
|
||||||
use engines::SystemOrCodeCallKind;
|
use engines::SystemOrCodeCallKind;
|
||||||
use super::{BlockRewardContract, RewardKind};
|
use super::{BlockRewardContract, RewardKind};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn block_reward_contract() {
|
fn block_reward_contract() {
|
||||||
let client = generate_dummy_client_with_spec_and_accounts(
|
let client = generate_dummy_client_with_spec(Spec::new_test_round_block_reward_contract);
|
||||||
Spec::new_test_round_block_reward_contract,
|
|
||||||
None,
|
|
||||||
);
|
|
||||||
|
|
||||||
let machine = Spec::new_test_machine();
|
let machine = Spec::new_test_machine();
|
||||||
|
|
||||||
|
@ -20,16 +20,17 @@ mod authority_round;
|
|||||||
mod basic_authority;
|
mod basic_authority;
|
||||||
mod instant_seal;
|
mod instant_seal;
|
||||||
mod null_engine;
|
mod null_engine;
|
||||||
mod signer;
|
|
||||||
mod validator_set;
|
mod validator_set;
|
||||||
|
|
||||||
pub mod block_reward;
|
pub mod block_reward;
|
||||||
|
pub mod signer;
|
||||||
|
|
||||||
pub use self::authority_round::AuthorityRound;
|
pub use self::authority_round::AuthorityRound;
|
||||||
pub use self::basic_authority::BasicAuthority;
|
pub use self::basic_authority::BasicAuthority;
|
||||||
pub use self::epoch::{EpochVerifier, Transition as EpochTransition};
|
pub use self::epoch::{EpochVerifier, Transition as EpochTransition};
|
||||||
pub use self::instant_seal::{InstantSeal, InstantSealParams};
|
pub use self::instant_seal::{InstantSeal, InstantSealParams};
|
||||||
pub use self::null_engine::NullEngine;
|
pub use self::null_engine::NullEngine;
|
||||||
|
pub use self::signer::EngineSigner;
|
||||||
|
|
||||||
// TODO [ToDr] Remove re-export (#10130)
|
// TODO [ToDr] Remove re-export (#10130)
|
||||||
pub use types::engines::ForkChoice;
|
pub use types::engines::ForkChoice;
|
||||||
@ -39,7 +40,6 @@ use std::sync::{Weak, Arc};
|
|||||||
use std::collections::{BTreeMap, HashMap};
|
use std::collections::{BTreeMap, HashMap};
|
||||||
use std::{fmt, error};
|
use std::{fmt, error};
|
||||||
|
|
||||||
use account_provider::AccountProvider;
|
|
||||||
use builtin::Builtin;
|
use builtin::Builtin;
|
||||||
use vm::{EnvInfo, Schedule, CreateContractAddress, CallType, ActionValue};
|
use vm::{EnvInfo, Schedule, CreateContractAddress, CallType, ActionValue};
|
||||||
use error::Error;
|
use error::Error;
|
||||||
@ -49,7 +49,7 @@ use snapshot::SnapshotComponents;
|
|||||||
use spec::CommonParams;
|
use spec::CommonParams;
|
||||||
use types::transaction::{self, UnverifiedTransaction, SignedTransaction};
|
use types::transaction::{self, UnverifiedTransaction, SignedTransaction};
|
||||||
|
|
||||||
use ethkey::{Password, Signature};
|
use ethkey::{Signature};
|
||||||
use parity_machine::{Machine, LocalizedMachine as Localized, TotalScoredHeader};
|
use parity_machine::{Machine, LocalizedMachine as Localized, TotalScoredHeader};
|
||||||
use ethereum_types::{H256, U256, Address};
|
use ethereum_types::{H256, U256, Address};
|
||||||
use unexpected::{Mismatch, OutOfBounds};
|
use unexpected::{Mismatch, OutOfBounds};
|
||||||
@ -380,8 +380,8 @@ pub trait Engine<M: Machine>: Sync + Send {
|
|||||||
/// Takes a header of a fully verified block.
|
/// Takes a header of a fully verified block.
|
||||||
fn is_proposal(&self, _verified_header: &M::Header) -> bool { false }
|
fn is_proposal(&self, _verified_header: &M::Header) -> bool { false }
|
||||||
|
|
||||||
/// Register an account which signs consensus messages.
|
/// Register a component which signs consensus messages.
|
||||||
fn set_signer(&self, _account_provider: Arc<AccountProvider>, _address: Address, _password: Password) {}
|
fn set_signer(&self, _signer: Box<EngineSigner>) {}
|
||||||
|
|
||||||
/// Sign using the EngineSigner, to be used for consensus tx signing.
|
/// Sign using the EngineSigner, to be used for consensus tx signing.
|
||||||
fn sign(&self, _hash: H256) -> Result<Signature, M::Error> { unimplemented!() }
|
fn sign(&self, _hash: H256) -> Result<Signature, M::Error> { unimplemented!() }
|
||||||
|
@ -16,49 +16,68 @@
|
|||||||
|
|
||||||
//! A signer used by Engines which need to sign messages.
|
//! A signer used by Engines which need to sign messages.
|
||||||
|
|
||||||
use std::sync::Arc;
|
|
||||||
use ethereum_types::{H256, Address};
|
use ethereum_types::{H256, Address};
|
||||||
use ethkey::{Password, Signature};
|
use ethkey::{self, Signature};
|
||||||
use account_provider::{self, AccountProvider};
|
|
||||||
|
|
||||||
/// Everything that an Engine needs to sign messages.
|
/// Everything that an Engine needs to sign messages.
|
||||||
pub struct EngineSigner {
|
pub trait EngineSigner: Send + Sync {
|
||||||
account_provider: Arc<AccountProvider>,
|
|
||||||
address: Option<Address>,
|
|
||||||
password: Option<Password>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for EngineSigner {
|
|
||||||
fn default() -> Self {
|
|
||||||
EngineSigner {
|
|
||||||
account_provider: Arc::new(AccountProvider::transient_provider()),
|
|
||||||
address: Default::default(),
|
|
||||||
password: Default::default(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl EngineSigner {
|
|
||||||
/// Set up the signer to sign with given address and password.
|
|
||||||
pub fn set(&mut self, ap: Arc<AccountProvider>, address: Address, password: Password) {
|
|
||||||
self.account_provider = ap;
|
|
||||||
self.address = Some(address);
|
|
||||||
self.password = Some(password);
|
|
||||||
debug!(target: "poa", "Setting Engine signer to {}", address);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sign a consensus message hash.
|
/// Sign a consensus message hash.
|
||||||
pub fn sign(&self, hash: H256) -> Result<Signature, account_provider::SignError> {
|
fn sign(&self, hash: H256) -> Result<Signature, ethkey::Error>;
|
||||||
self.account_provider.sign(self.address.unwrap_or_else(Default::default), self.password.clone(), hash)
|
|
||||||
|
/// Signing address
|
||||||
|
fn address(&self) -> Address;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a new `EngineSigner` from given key pair.
|
||||||
|
pub fn from_keypair(keypair: ethkey::KeyPair) -> Box<EngineSigner> {
|
||||||
|
Box::new(Signer(keypair))
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Signer(ethkey::KeyPair);
|
||||||
|
|
||||||
|
impl EngineSigner for Signer {
|
||||||
|
fn sign(&self, hash: H256) -> Result<Signature, ethkey::Error> {
|
||||||
|
ethkey::sign(self.0.secret(), &hash)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Signing address.
|
fn address(&self) -> Address {
|
||||||
pub fn address(&self) -> Option<Address> {
|
self.0.address()
|
||||||
self.address.clone()
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Check if the signing address was set.
|
#[cfg(test)]
|
||||||
pub fn is_some(&self) -> bool {
|
mod test_signer {
|
||||||
self.address.is_some()
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use ethkey::Password;
|
||||||
|
use accounts::{self, AccountProvider, SignError};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
impl EngineSigner for (Arc<AccountProvider>, Address, Password) {
|
||||||
|
fn sign(&self, hash: H256) -> Result<Signature, ethkey::Error> {
|
||||||
|
match self.0.sign(self.1, Some(self.2.clone()), hash) {
|
||||||
|
Err(SignError::NotUnlocked) => unreachable!(),
|
||||||
|
Err(SignError::NotFound) => Err(ethkey::Error::InvalidAddress),
|
||||||
|
Err(SignError::Hardware(err)) => {
|
||||||
|
warn!("Error using hardware wallet for engine: {:?}", err);
|
||||||
|
Err(ethkey::Error::InvalidSecret)
|
||||||
|
},
|
||||||
|
Err(SignError::SStore(accounts::Error::EthKey(err))) => Err(err),
|
||||||
|
Err(SignError::SStore(accounts::Error::EthKeyCrypto(err))) => {
|
||||||
|
warn!("Low level crypto error: {:?}", err);
|
||||||
|
Err(ethkey::Error::InvalidSecret)
|
||||||
|
},
|
||||||
|
Err(SignError::SStore(err)) => {
|
||||||
|
warn!("Error signing for engine: {:?}", err);
|
||||||
|
Err(ethkey::Error::InvalidSignature)
|
||||||
|
},
|
||||||
|
Ok(ok) => Ok(ok),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn address(&self) -> Address {
|
||||||
|
self.1
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -141,10 +141,10 @@ mod tests {
|
|||||||
use rlp::encode;
|
use rlp::encode;
|
||||||
use spec::Spec;
|
use spec::Spec;
|
||||||
use types::header::Header;
|
use types::header::Header;
|
||||||
use account_provider::AccountProvider;
|
use accounts::AccountProvider;
|
||||||
use miner::MinerService;
|
use miner::{self, MinerService};
|
||||||
use types::ids::BlockId;
|
use types::ids::BlockId;
|
||||||
use test_helpers::generate_dummy_client_with_spec_and_accounts;
|
use test_helpers::generate_dummy_client_with_spec;
|
||||||
use call_contract::CallContract;
|
use call_contract::CallContract;
|
||||||
use client::{BlockChainClient, ChainInfo, BlockInfo};
|
use client::{BlockChainClient, ChainInfo, BlockInfo};
|
||||||
use super::super::ValidatorSet;
|
use super::super::ValidatorSet;
|
||||||
@ -152,7 +152,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn fetches_validators() {
|
fn fetches_validators() {
|
||||||
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_contract, None);
|
let client = generate_dummy_client_with_spec(Spec::new_validator_contract);
|
||||||
let vc = Arc::new(ValidatorContract::new("0000000000000000000000000000000000000005".parse::<Address>().unwrap()));
|
let vc = Arc::new(ValidatorContract::new("0000000000000000000000000000000000000005".parse::<Address>().unwrap()));
|
||||||
vc.register_client(Arc::downgrade(&client) as _);
|
vc.register_client(Arc::downgrade(&client) as _);
|
||||||
let last_hash = client.best_block_header().hash();
|
let last_hash = client.best_block_header().hash();
|
||||||
@ -164,13 +164,14 @@ mod tests {
|
|||||||
fn reports_validators() {
|
fn reports_validators() {
|
||||||
let tap = Arc::new(AccountProvider::transient_provider());
|
let tap = Arc::new(AccountProvider::transient_provider());
|
||||||
let v1 = tap.insert_account(keccak("1").into(), &"".into()).unwrap();
|
let v1 = tap.insert_account(keccak("1").into(), &"".into()).unwrap();
|
||||||
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_contract, Some(tap.clone()));
|
let client = generate_dummy_client_with_spec(Spec::new_validator_contract);
|
||||||
client.engine().register_client(Arc::downgrade(&client) as _);
|
client.engine().register_client(Arc::downgrade(&client) as _);
|
||||||
let validator_contract = "0000000000000000000000000000000000000005".parse::<Address>().unwrap();
|
let validator_contract = "0000000000000000000000000000000000000005".parse::<Address>().unwrap();
|
||||||
|
|
||||||
// Make sure reporting can be done.
|
// Make sure reporting can be done.
|
||||||
client.miner().set_gas_range_target((1_000_000.into(), 1_000_000.into()));
|
client.miner().set_gas_range_target((1_000_000.into(), 1_000_000.into()));
|
||||||
client.miner().set_author(v1, Some("".into())).unwrap();
|
let signer = Box::new((tap.clone(), v1, "".into()));
|
||||||
|
client.miner().set_author(miner::Author::Sealer(signer));
|
||||||
|
|
||||||
// Check a block that is a bit in future, reject it but don't report the validator.
|
// Check a block that is a bit in future, reject it but don't report the validator.
|
||||||
let mut header = Header::default();
|
let mut header = Header::default();
|
||||||
|
@ -150,15 +150,15 @@ mod tests {
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use hash::keccak;
|
use hash::keccak;
|
||||||
use account_provider::AccountProvider;
|
use accounts::AccountProvider;
|
||||||
use client::{BlockChainClient, ChainInfo, BlockInfo, ImportBlock};
|
use client::{BlockChainClient, ChainInfo, BlockInfo, ImportBlock};
|
||||||
use engines::EpochChange;
|
use engines::EpochChange;
|
||||||
use engines::validator_set::ValidatorSet;
|
use engines::validator_set::ValidatorSet;
|
||||||
use ethkey::Secret;
|
use ethkey::Secret;
|
||||||
use types::header::Header;
|
use types::header::Header;
|
||||||
use miner::MinerService;
|
use miner::{self, MinerService};
|
||||||
use spec::Spec;
|
use spec::Spec;
|
||||||
use test_helpers::{generate_dummy_client_with_spec_and_accounts, generate_dummy_client_with_spec_and_data};
|
use test_helpers::{generate_dummy_client_with_spec, generate_dummy_client_with_spec_and_data};
|
||||||
use types::ids::BlockId;
|
use types::ids::BlockId;
|
||||||
use ethereum_types::Address;
|
use ethereum_types::Address;
|
||||||
use verification::queue::kind::blocks::Unverified;
|
use verification::queue::kind::blocks::Unverified;
|
||||||
@ -171,26 +171,29 @@ mod tests {
|
|||||||
let s0: Secret = keccak("0").into();
|
let s0: Secret = keccak("0").into();
|
||||||
let v0 = tap.insert_account(s0.clone(), &"".into()).unwrap();
|
let v0 = tap.insert_account(s0.clone(), &"".into()).unwrap();
|
||||||
let v1 = tap.insert_account(keccak("1").into(), &"".into()).unwrap();
|
let v1 = tap.insert_account(keccak("1").into(), &"".into()).unwrap();
|
||||||
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_multi, Some(tap));
|
let client = generate_dummy_client_with_spec(Spec::new_validator_multi);
|
||||||
client.engine().register_client(Arc::downgrade(&client) as _);
|
client.engine().register_client(Arc::downgrade(&client) as _);
|
||||||
|
|
||||||
// Make sure txs go through.
|
// Make sure txs go through.
|
||||||
client.miner().set_gas_range_target((1_000_000.into(), 1_000_000.into()));
|
client.miner().set_gas_range_target((1_000_000.into(), 1_000_000.into()));
|
||||||
|
|
||||||
// Wrong signer for the first block.
|
// Wrong signer for the first block.
|
||||||
client.miner().set_author(v1, Some("".into())).unwrap();
|
let signer = Box::new((tap.clone(), v1, "".into()));
|
||||||
|
client.miner().set_author(miner::Author::Sealer(signer));
|
||||||
client.transact_contract(Default::default(), Default::default()).unwrap();
|
client.transact_contract(Default::default(), Default::default()).unwrap();
|
||||||
::client::EngineClient::update_sealing(&*client);
|
::client::EngineClient::update_sealing(&*client);
|
||||||
assert_eq!(client.chain_info().best_block_number, 0);
|
assert_eq!(client.chain_info().best_block_number, 0);
|
||||||
// Right signer for the first block.
|
// Right signer for the first block.
|
||||||
client.miner().set_author(v0, Some("".into())).unwrap();
|
let signer = Box::new((tap.clone(), v0, "".into()));
|
||||||
|
client.miner().set_author(miner::Author::Sealer(signer));
|
||||||
::client::EngineClient::update_sealing(&*client);
|
::client::EngineClient::update_sealing(&*client);
|
||||||
assert_eq!(client.chain_info().best_block_number, 1);
|
assert_eq!(client.chain_info().best_block_number, 1);
|
||||||
// This time v0 is wrong.
|
// This time v0 is wrong.
|
||||||
client.transact_contract(Default::default(), Default::default()).unwrap();
|
client.transact_contract(Default::default(), Default::default()).unwrap();
|
||||||
::client::EngineClient::update_sealing(&*client);
|
::client::EngineClient::update_sealing(&*client);
|
||||||
assert_eq!(client.chain_info().best_block_number, 1);
|
assert_eq!(client.chain_info().best_block_number, 1);
|
||||||
client.miner().set_author(v1, Some("".into())).unwrap();
|
let signer = Box::new((tap.clone(), v1, "".into()));
|
||||||
|
client.miner().set_author(miner::Author::Sealer(signer));
|
||||||
::client::EngineClient::update_sealing(&*client);
|
::client::EngineClient::update_sealing(&*client);
|
||||||
assert_eq!(client.chain_info().best_block_number, 2);
|
assert_eq!(client.chain_info().best_block_number, 2);
|
||||||
// v1 is still good.
|
// v1 is still good.
|
||||||
|
@ -445,19 +445,19 @@ mod tests {
|
|||||||
use ethereum_types::Address;
|
use ethereum_types::Address;
|
||||||
use types::ids::BlockId;
|
use types::ids::BlockId;
|
||||||
use spec::Spec;
|
use spec::Spec;
|
||||||
use account_provider::AccountProvider;
|
use accounts::AccountProvider;
|
||||||
use types::transaction::{Transaction, Action};
|
use types::transaction::{Transaction, Action};
|
||||||
use client::{ChainInfo, BlockInfo, ImportBlock};
|
use client::{ChainInfo, BlockInfo, ImportBlock};
|
||||||
use ethkey::Secret;
|
use ethkey::Secret;
|
||||||
use miner::MinerService;
|
use miner::{self, MinerService};
|
||||||
use test_helpers::{generate_dummy_client_with_spec_and_accounts, generate_dummy_client_with_spec_and_data};
|
use test_helpers::{generate_dummy_client_with_spec, generate_dummy_client_with_spec_and_data};
|
||||||
use super::super::ValidatorSet;
|
use super::super::ValidatorSet;
|
||||||
use super::{ValidatorSafeContract, EVENT_NAME_HASH};
|
use super::{ValidatorSafeContract, EVENT_NAME_HASH};
|
||||||
use verification::queue::kind::blocks::Unverified;
|
use verification::queue::kind::blocks::Unverified;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn fetches_validators() {
|
fn fetches_validators() {
|
||||||
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_safe_contract, None);
|
let client = generate_dummy_client_with_spec(Spec::new_validator_safe_contract);
|
||||||
let vc = Arc::new(ValidatorSafeContract::new("0000000000000000000000000000000000000005".parse::<Address>().unwrap()));
|
let vc = Arc::new(ValidatorSafeContract::new("0000000000000000000000000000000000000005".parse::<Address>().unwrap()));
|
||||||
vc.register_client(Arc::downgrade(&client) as _);
|
vc.register_client(Arc::downgrade(&client) as _);
|
||||||
let last_hash = client.best_block_header().hash();
|
let last_hash = client.best_block_header().hash();
|
||||||
@ -472,11 +472,12 @@ mod tests {
|
|||||||
let v0 = tap.insert_account(s0.clone(), &"".into()).unwrap();
|
let v0 = tap.insert_account(s0.clone(), &"".into()).unwrap();
|
||||||
let v1 = tap.insert_account(keccak("0").into(), &"".into()).unwrap();
|
let v1 = tap.insert_account(keccak("0").into(), &"".into()).unwrap();
|
||||||
let chain_id = Spec::new_validator_safe_contract().chain_id();
|
let chain_id = Spec::new_validator_safe_contract().chain_id();
|
||||||
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_safe_contract, Some(tap));
|
let client = generate_dummy_client_with_spec(Spec::new_validator_safe_contract);
|
||||||
client.engine().register_client(Arc::downgrade(&client) as _);
|
client.engine().register_client(Arc::downgrade(&client) as _);
|
||||||
let validator_contract = "0000000000000000000000000000000000000005".parse::<Address>().unwrap();
|
let validator_contract = "0000000000000000000000000000000000000005".parse::<Address>().unwrap();
|
||||||
|
let signer = Box::new((tap.clone(), v1, "".into()));
|
||||||
|
|
||||||
client.miner().set_author(v1, Some("".into())).unwrap();
|
client.miner().set_author(miner::Author::Sealer(signer));
|
||||||
// Remove "1" validator.
|
// Remove "1" validator.
|
||||||
let tx = Transaction {
|
let tx = Transaction {
|
||||||
nonce: 0.into(),
|
nonce: 0.into(),
|
||||||
@ -504,11 +505,13 @@ mod tests {
|
|||||||
assert_eq!(client.chain_info().best_block_number, 1);
|
assert_eq!(client.chain_info().best_block_number, 1);
|
||||||
|
|
||||||
// Switch to the validator that is still there.
|
// Switch to the validator that is still there.
|
||||||
client.miner().set_author(v0, Some("".into())).unwrap();
|
let signer = Box::new((tap.clone(), v0, "".into()));
|
||||||
|
client.miner().set_author(miner::Author::Sealer(signer));
|
||||||
::client::EngineClient::update_sealing(&*client);
|
::client::EngineClient::update_sealing(&*client);
|
||||||
assert_eq!(client.chain_info().best_block_number, 2);
|
assert_eq!(client.chain_info().best_block_number, 2);
|
||||||
// Switch back to the added validator, since the state is updated.
|
// Switch back to the added validator, since the state is updated.
|
||||||
client.miner().set_author(v1, Some("".into())).unwrap();
|
let signer = Box::new((tap.clone(), v1, "".into()));
|
||||||
|
client.miner().set_author(miner::Author::Sealer(signer));
|
||||||
let tx = Transaction {
|
let tx = Transaction {
|
||||||
nonce: 2.into(),
|
nonce: 2.into(),
|
||||||
gas_price: 0.into(),
|
gas_price: 0.into(),
|
||||||
@ -539,7 +542,7 @@ mod tests {
|
|||||||
use types::header::Header;
|
use types::header::Header;
|
||||||
use types::log_entry::LogEntry;
|
use types::log_entry::LogEntry;
|
||||||
|
|
||||||
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_safe_contract, None);
|
let client = generate_dummy_client_with_spec(Spec::new_validator_safe_contract);
|
||||||
let engine = client.engine().clone();
|
let engine = client.engine().clone();
|
||||||
let validator_contract = "0000000000000000000000000000000000000005".parse::<Address>().unwrap();
|
let validator_contract = "0000000000000000000000000000000000000005".parse::<Address>().unwrap();
|
||||||
|
|
||||||
@ -576,7 +579,7 @@ mod tests {
|
|||||||
use types::header::Header;
|
use types::header::Header;
|
||||||
use engines::{EpochChange, Proof};
|
use engines::{EpochChange, Proof};
|
||||||
|
|
||||||
let client = generate_dummy_client_with_spec_and_accounts(Spec::new_validator_safe_contract, None);
|
let client = generate_dummy_client_with_spec(Spec::new_validator_safe_contract);
|
||||||
let engine = client.engine().clone();
|
let engine = client.engine().clone();
|
||||||
|
|
||||||
let mut new_header = Header::default();
|
let mut new_header = Header::default();
|
||||||
|
@ -25,11 +25,10 @@ use ethtrie::TrieError;
|
|||||||
use rlp;
|
use rlp;
|
||||||
use snappy::InvalidInput;
|
use snappy::InvalidInput;
|
||||||
use snapshot::Error as SnapshotError;
|
use snapshot::Error as SnapshotError;
|
||||||
use types::transaction::Error as TransactionError;
|
|
||||||
use types::BlockNumber;
|
use types::BlockNumber;
|
||||||
|
use types::transaction::Error as TransactionError;
|
||||||
use unexpected::{Mismatch, OutOfBounds};
|
use unexpected::{Mismatch, OutOfBounds};
|
||||||
|
|
||||||
use account_provider::SignError as AccountsError;
|
|
||||||
use engines::EngineError;
|
use engines::EngineError;
|
||||||
|
|
||||||
pub use executed::{ExecutionError, CallError};
|
pub use executed::{ExecutionError, CallError};
|
||||||
@ -244,12 +243,6 @@ error_chain! {
|
|||||||
display("Snapshot error {}", err)
|
display("Snapshot error {}", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[doc = "Account Provider error"]
|
|
||||||
AccountProvider(err: AccountsError) {
|
|
||||||
description("Accounts Provider error")
|
|
||||||
display("Accounts Provider error {}", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[doc = "PoW hash is invalid or out of date."]
|
#[doc = "PoW hash is invalid or out of date."]
|
||||||
PowHashInvalid {
|
PowHashInvalid {
|
||||||
description("PoW hash is invalid or out of date.")
|
description("PoW hash is invalid or out of date.")
|
||||||
@ -270,12 +263,6 @@ error_chain! {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<AccountsError> for Error {
|
|
||||||
fn from(err: AccountsError) -> Error {
|
|
||||||
ErrorKind::AccountProvider(err).into()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<SnapshotError> for Error {
|
impl From<SnapshotError> for Error {
|
||||||
fn from(err: SnapshotError) -> Error {
|
fn from(err: SnapshotError) -> Error {
|
||||||
match err {
|
match err {
|
||||||
|
@ -73,7 +73,6 @@ extern crate ethcore_miner;
|
|||||||
extern crate ethereum_types;
|
extern crate ethereum_types;
|
||||||
extern crate ethjson;
|
extern crate ethjson;
|
||||||
extern crate ethkey;
|
extern crate ethkey;
|
||||||
extern crate ethstore;
|
|
||||||
extern crate hashdb;
|
extern crate hashdb;
|
||||||
extern crate heapsize;
|
extern crate heapsize;
|
||||||
extern crate itertools;
|
extern crate itertools;
|
||||||
@ -107,6 +106,8 @@ extern crate using_queue;
|
|||||||
extern crate vm;
|
extern crate vm;
|
||||||
extern crate wasm;
|
extern crate wasm;
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
extern crate ethcore_accounts as accounts;
|
||||||
#[cfg(feature = "stratum")]
|
#[cfg(feature = "stratum")]
|
||||||
extern crate ethcore_stratum;
|
extern crate ethcore_stratum;
|
||||||
#[cfg(any(test, feature = "tempdir"))]
|
#[cfg(any(test, feature = "tempdir"))]
|
||||||
@ -115,12 +116,10 @@ extern crate tempdir;
|
|||||||
extern crate kvdb_rocksdb;
|
extern crate kvdb_rocksdb;
|
||||||
#[cfg(any(test, feature = "blooms-db"))]
|
#[cfg(any(test, feature = "blooms-db"))]
|
||||||
extern crate blooms_db;
|
extern crate blooms_db;
|
||||||
|
#[cfg(any(test, feature = "env_logger"))]
|
||||||
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
|
extern crate env_logger;
|
||||||
extern crate hardware_wallet;
|
#[cfg(test)]
|
||||||
|
extern crate rlp_compress;
|
||||||
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
|
|
||||||
extern crate fake_hardware_wallet as hardware_wallet;
|
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate ethabi_derive;
|
extern crate ethabi_derive;
|
||||||
@ -144,12 +143,6 @@ extern crate serde_derive;
|
|||||||
#[cfg_attr(test, macro_use)]
|
#[cfg_attr(test, macro_use)]
|
||||||
extern crate evm;
|
extern crate evm;
|
||||||
|
|
||||||
#[cfg(any(test, feature = "env_logger"))]
|
|
||||||
extern crate env_logger;
|
|
||||||
#[cfg(test)]
|
|
||||||
extern crate rlp_compress;
|
|
||||||
|
|
||||||
pub mod account_provider;
|
|
||||||
pub mod block;
|
pub mod block;
|
||||||
pub mod builtin;
|
pub mod builtin;
|
||||||
pub mod client;
|
pub mod client;
|
||||||
|
@ -23,11 +23,11 @@ use ansi_term::Colour;
|
|||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use call_contract::CallContract;
|
use call_contract::CallContract;
|
||||||
use ethcore_miner::gas_pricer::GasPricer;
|
use ethcore_miner::gas_pricer::GasPricer;
|
||||||
|
use ethcore_miner::local_accounts::LocalAccounts;
|
||||||
use ethcore_miner::pool::{self, TransactionQueue, VerifiedTransaction, QueueStatus, PrioritizationStrategy};
|
use ethcore_miner::pool::{self, TransactionQueue, VerifiedTransaction, QueueStatus, PrioritizationStrategy};
|
||||||
#[cfg(feature = "work-notify")]
|
#[cfg(feature = "work-notify")]
|
||||||
use ethcore_miner::work_notify::NotifyWork;
|
use ethcore_miner::work_notify::NotifyWork;
|
||||||
use ethereum_types::{H256, U256, Address};
|
use ethereum_types::{H256, U256, Address};
|
||||||
use ethkey::Password;
|
|
||||||
use io::IoChannel;
|
use io::IoChannel;
|
||||||
use miner::pool_client::{PoolClient, CachedNonceClient, NonceCache};
|
use miner::pool_client::{PoolClient, CachedNonceClient, NonceCache};
|
||||||
use miner;
|
use miner;
|
||||||
@ -46,13 +46,12 @@ use types::header::Header;
|
|||||||
use types::receipt::RichReceipt;
|
use types::receipt::RichReceipt;
|
||||||
use using_queue::{UsingQueue, GetAction};
|
use using_queue::{UsingQueue, GetAction};
|
||||||
|
|
||||||
use account_provider::{AccountProvider, SignError as AccountError};
|
|
||||||
use block::{ClosedBlock, IsBlock, SealedBlock};
|
use block::{ClosedBlock, IsBlock, SealedBlock};
|
||||||
use client::{
|
use client::{
|
||||||
BlockChain, ChainInfo, BlockProducer, SealedBlockImporter, Nonce, TransactionInfo, TransactionId
|
BlockChain, ChainInfo, BlockProducer, SealedBlockImporter, Nonce, TransactionInfo, TransactionId
|
||||||
};
|
};
|
||||||
use client::{BlockId, ClientIoMessage};
|
use client::{BlockId, ClientIoMessage};
|
||||||
use engines::{EthEngine, Seal};
|
use engines::{EthEngine, Seal, EngineSigner};
|
||||||
use error::{Error, ErrorKind};
|
use error::{Error, ErrorKind};
|
||||||
use executed::ExecutionError;
|
use executed::ExecutionError;
|
||||||
use executive::contract_address;
|
use executive::contract_address;
|
||||||
@ -140,8 +139,6 @@ pub struct MinerOptions {
|
|||||||
/// will be invalid if mined.
|
/// will be invalid if mined.
|
||||||
pub infinite_pending_block: bool,
|
pub infinite_pending_block: bool,
|
||||||
|
|
||||||
/// Prioritized Local Addresses
|
|
||||||
pub tx_queue_locals: HashSet<Address>,
|
|
||||||
/// Strategy to use for prioritizing transactions in the queue.
|
/// Strategy to use for prioritizing transactions in the queue.
|
||||||
pub tx_queue_strategy: PrioritizationStrategy,
|
pub tx_queue_strategy: PrioritizationStrategy,
|
||||||
/// Simple senders penalization.
|
/// Simple senders penalization.
|
||||||
@ -169,7 +166,6 @@ impl Default for MinerOptions {
|
|||||||
work_queue_size: 20,
|
work_queue_size: 20,
|
||||||
enable_resubmission: true,
|
enable_resubmission: true,
|
||||||
infinite_pending_block: false,
|
infinite_pending_block: false,
|
||||||
tx_queue_locals: HashSet::new(),
|
|
||||||
tx_queue_strategy: PrioritizationStrategy::GasPriceOnly,
|
tx_queue_strategy: PrioritizationStrategy::GasPriceOnly,
|
||||||
tx_queue_penalization: Penalization::Disabled,
|
tx_queue_penalization: Penalization::Disabled,
|
||||||
tx_queue_no_unfamiliar_locals: false,
|
tx_queue_no_unfamiliar_locals: false,
|
||||||
@ -200,6 +196,25 @@ pub struct AuthoringParams {
|
|||||||
pub extra_data: Bytes,
|
pub extra_data: Bytes,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Block sealing mechanism
|
||||||
|
pub enum Author {
|
||||||
|
/// Sealing block is external and we only need a reward beneficiary (i.e. PoW)
|
||||||
|
External(Address),
|
||||||
|
/// Sealing is done internally, we need a way to create signatures to seal block (i.e. PoA)
|
||||||
|
Sealer(Box<EngineSigner>),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Author {
|
||||||
|
/// Get author's address.
|
||||||
|
pub fn address(&self) -> Address {
|
||||||
|
match *self {
|
||||||
|
Author::External(address) => address,
|
||||||
|
Author::Sealer(ref sealer) => sealer.address(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
struct SealingWork {
|
struct SealingWork {
|
||||||
queue: UsingQueue<ClosedBlock>,
|
queue: UsingQueue<ClosedBlock>,
|
||||||
enabled: bool,
|
enabled: bool,
|
||||||
@ -230,7 +245,7 @@ pub struct Miner {
|
|||||||
// TODO [ToDr] Arc is only required because of price updater
|
// TODO [ToDr] Arc is only required because of price updater
|
||||||
transaction_queue: Arc<TransactionQueue>,
|
transaction_queue: Arc<TransactionQueue>,
|
||||||
engine: Arc<EthEngine>,
|
engine: Arc<EthEngine>,
|
||||||
accounts: Option<Arc<AccountProvider>>,
|
accounts: Arc<LocalAccounts>,
|
||||||
io_channel: RwLock<Option<IoChannel<ClientIoMessage>>>,
|
io_channel: RwLock<Option<IoChannel<ClientIoMessage>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -248,11 +263,11 @@ impl Miner {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Creates new instance of miner Arc.
|
/// Creates new instance of miner Arc.
|
||||||
pub fn new(
|
pub fn new<A: LocalAccounts + 'static>(
|
||||||
options: MinerOptions,
|
options: MinerOptions,
|
||||||
gas_pricer: GasPricer,
|
gas_pricer: GasPricer,
|
||||||
spec: &Spec,
|
spec: &Spec,
|
||||||
accounts: Option<Arc<AccountProvider>>,
|
accounts: A,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let limits = options.pool_limits.clone();
|
let limits = options.pool_limits.clone();
|
||||||
let verifier_options = options.pool_verification_options.clone();
|
let verifier_options = options.pool_verification_options.clone();
|
||||||
@ -275,7 +290,7 @@ impl Miner {
|
|||||||
nonce_cache: NonceCache::new(nonce_cache_size),
|
nonce_cache: NonceCache::new(nonce_cache_size),
|
||||||
options,
|
options,
|
||||||
transaction_queue: Arc::new(TransactionQueue::new(limits, verifier_options, tx_queue_strategy)),
|
transaction_queue: Arc::new(TransactionQueue::new(limits, verifier_options, tx_queue_strategy)),
|
||||||
accounts,
|
accounts: Arc::new(accounts),
|
||||||
engine: spec.engine.clone(),
|
engine: spec.engine.clone(),
|
||||||
io_channel: RwLock::new(None),
|
io_channel: RwLock::new(None),
|
||||||
}
|
}
|
||||||
@ -284,7 +299,7 @@ impl Miner {
|
|||||||
/// Creates new instance of miner with given spec and accounts.
|
/// Creates new instance of miner with given spec and accounts.
|
||||||
///
|
///
|
||||||
/// NOTE This should be only used for tests.
|
/// NOTE This should be only used for tests.
|
||||||
pub fn new_for_tests(spec: &Spec, accounts: Option<Arc<AccountProvider>>) -> Miner {
|
pub fn new_for_tests(spec: &Spec, accounts: Option<HashSet<Address>>) -> Miner {
|
||||||
let minimal_gas_price = 0.into();
|
let minimal_gas_price = 0.into();
|
||||||
Miner::new(MinerOptions {
|
Miner::new(MinerOptions {
|
||||||
pool_verification_options: pool::verifier::Options {
|
pool_verification_options: pool::verifier::Options {
|
||||||
@ -295,7 +310,7 @@ impl Miner {
|
|||||||
},
|
},
|
||||||
reseal_min_period: Duration::from_secs(0),
|
reseal_min_period: Duration::from_secs(0),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
}, GasPricer::new_fixed(minimal_gas_price), spec, accounts)
|
}, GasPricer::new_fixed(minimal_gas_price), spec, accounts.unwrap_or_default())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sets `IoChannel`
|
/// Sets `IoChannel`
|
||||||
@ -362,7 +377,7 @@ impl Miner {
|
|||||||
chain,
|
chain,
|
||||||
&self.nonce_cache,
|
&self.nonce_cache,
|
||||||
&*self.engine,
|
&*self.engine,
|
||||||
self.accounts.as_ref().map(|x| &**x),
|
&*self.accounts,
|
||||||
self.options.refuse_service_transactions,
|
self.options.refuse_service_transactions,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -830,14 +845,11 @@ impl miner::MinerService for Miner {
|
|||||||
self.params.write().extra_data = extra_data;
|
self.params.write().extra_data = extra_data;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_author(&self, address: Address, password: Option<Password>) -> Result<(), AccountError> {
|
fn set_author(&self, author: Author) {
|
||||||
self.params.write().author = address;
|
self.params.write().author = author.address();
|
||||||
|
|
||||||
if self.engine.seals_internally().is_some() && password.is_some() {
|
if let Author::Sealer(signer) = author {
|
||||||
if let Some(ref ap) = self.accounts {
|
if self.engine.seals_internally().is_some() {
|
||||||
let password = password.unwrap_or_else(|| Password::from(String::new()));
|
|
||||||
// Sign test message
|
|
||||||
ap.sign(address.clone(), Some(password.clone()), Default::default())?;
|
|
||||||
// Enable sealing
|
// Enable sealing
|
||||||
self.sealing.lock().enabled = true;
|
self.sealing.lock().enabled = true;
|
||||||
// --------------------------------------------------------------------------
|
// --------------------------------------------------------------------------
|
||||||
@ -845,14 +857,10 @@ impl miner::MinerService for Miner {
|
|||||||
// | (some `Engine`s call `EngineClient.update_sealing()`) |
|
// | (some `Engine`s call `EngineClient.update_sealing()`) |
|
||||||
// | Make sure to release the locks before calling that method. |
|
// | Make sure to release the locks before calling that method. |
|
||||||
// --------------------------------------------------------------------------
|
// --------------------------------------------------------------------------
|
||||||
self.engine.set_signer(ap.clone(), address, password);
|
self.engine.set_signer(signer);
|
||||||
Ok(())
|
|
||||||
} else {
|
} else {
|
||||||
warn!(target: "miner", "No account provider");
|
warn!("Setting an EngineSigner while Engine does not require one.");
|
||||||
Err(AccountError::NotFound)
|
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -925,8 +933,7 @@ impl miner::MinerService for Miner {
|
|||||||
let sender = pending.sender();
|
let sender = pending.sender();
|
||||||
let treat_as_local = trusted
|
let treat_as_local = trusted
|
||||||
|| !self.options.tx_queue_no_unfamiliar_locals
|
|| !self.options.tx_queue_no_unfamiliar_locals
|
||||||
|| self.accounts.as_ref().map(|accts| accts.has_account(sender)).unwrap_or(false)
|
|| self.accounts.is_local(&sender);
|
||||||
|| self.options.tx_queue_locals.contains(&sender);
|
|
||||||
|
|
||||||
if treat_as_local {
|
if treat_as_local {
|
||||||
self.import_own_transaction(chain, pending)
|
self.import_own_transaction(chain, pending)
|
||||||
@ -1255,7 +1262,7 @@ impl miner::MinerService for Miner {
|
|||||||
chain,
|
chain,
|
||||||
&nonce_cache,
|
&nonce_cache,
|
||||||
&*engine,
|
&*engine,
|
||||||
accounts.as_ref().map(|x| &**x),
|
&*accounts,
|
||||||
refuse_service_transactions,
|
refuse_service_transactions,
|
||||||
);
|
);
|
||||||
queue.cull(client);
|
queue.cull(client);
|
||||||
@ -1292,6 +1299,7 @@ mod tests {
|
|||||||
use std::iter::FromIterator;
|
use std::iter::FromIterator;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use accounts::AccountProvider;
|
||||||
use ethkey::{Generator, Random};
|
use ethkey::{Generator, Random};
|
||||||
use hash::keccak;
|
use hash::keccak;
|
||||||
use rustc_hex::FromHex;
|
use rustc_hex::FromHex;
|
||||||
@ -1299,7 +1307,7 @@ mod tests {
|
|||||||
|
|
||||||
use client::{TestBlockChainClient, EachBlockWith, ChainInfo, ImportSealedBlock};
|
use client::{TestBlockChainClient, EachBlockWith, ChainInfo, ImportSealedBlock};
|
||||||
use miner::{MinerService, PendingOrdering};
|
use miner::{MinerService, PendingOrdering};
|
||||||
use test_helpers::{generate_dummy_client, generate_dummy_client_with_spec_and_accounts};
|
use test_helpers::{generate_dummy_client, generate_dummy_client_with_spec};
|
||||||
use types::transaction::{Transaction};
|
use types::transaction::{Transaction};
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@ -1349,7 +1357,6 @@ mod tests {
|
|||||||
enable_resubmission: true,
|
enable_resubmission: true,
|
||||||
infinite_pending_block: false,
|
infinite_pending_block: false,
|
||||||
tx_queue_penalization: Penalization::Disabled,
|
tx_queue_penalization: Penalization::Disabled,
|
||||||
tx_queue_locals: HashSet::new(),
|
|
||||||
tx_queue_strategy: PrioritizationStrategy::GasPriceOnly,
|
tx_queue_strategy: PrioritizationStrategy::GasPriceOnly,
|
||||||
tx_queue_no_unfamiliar_locals: false,
|
tx_queue_no_unfamiliar_locals: false,
|
||||||
refuse_service_transactions: false,
|
refuse_service_transactions: false,
|
||||||
@ -1363,7 +1370,7 @@ mod tests {
|
|||||||
},
|
},
|
||||||
GasPricer::new_fixed(0u64.into()),
|
GasPricer::new_fixed(0u64.into()),
|
||||||
&Spec::new_test(),
|
&Spec::new_test(),
|
||||||
None, // accounts provider
|
::std::collections::HashSet::new(), // local accounts
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1476,8 +1483,8 @@ mod tests {
|
|||||||
// given
|
// given
|
||||||
let keypair = Random.generate().unwrap();
|
let keypair = Random.generate().unwrap();
|
||||||
let client = TestBlockChainClient::default();
|
let client = TestBlockChainClient::default();
|
||||||
let account_provider = AccountProvider::transient_provider();
|
let mut local_accounts = ::std::collections::HashSet::new();
|
||||||
account_provider.insert_account(keypair.secret().clone(), &"".into()).expect("can add accounts to the provider we just created");
|
local_accounts.insert(keypair.address());
|
||||||
|
|
||||||
let miner = Miner::new(
|
let miner = Miner::new(
|
||||||
MinerOptions {
|
MinerOptions {
|
||||||
@ -1486,7 +1493,7 @@ mod tests {
|
|||||||
},
|
},
|
||||||
GasPricer::new_fixed(0u64.into()),
|
GasPricer::new_fixed(0u64.into()),
|
||||||
&Spec::new_test(),
|
&Spec::new_test(),
|
||||||
Some(Arc::new(account_provider)),
|
local_accounts,
|
||||||
);
|
);
|
||||||
let transaction = transaction();
|
let transaction = transaction();
|
||||||
let best_block = 0;
|
let best_block = 0;
|
||||||
@ -1520,22 +1527,16 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn should_prioritize_locals() {
|
fn should_prioritize_locals() {
|
||||||
let keypair = Random.generate().unwrap();
|
|
||||||
let client = TestBlockChainClient::default();
|
let client = TestBlockChainClient::default();
|
||||||
let account_provider = AccountProvider::transient_provider();
|
|
||||||
account_provider.insert_account(keypair.secret().clone(), &"".into())
|
|
||||||
.expect("can add accounts to the provider we just created");
|
|
||||||
|
|
||||||
let transaction = transaction();
|
let transaction = transaction();
|
||||||
let miner = Miner::new(
|
let miner = Miner::new(
|
||||||
MinerOptions {
|
MinerOptions {
|
||||||
tx_queue_no_unfamiliar_locals: true, // should work even with this enabled
|
tx_queue_no_unfamiliar_locals: true, // should work even with this enabled
|
||||||
tx_queue_locals: HashSet::from_iter(vec![transaction.sender()].into_iter()),
|
|
||||||
..miner().options
|
..miner().options
|
||||||
},
|
},
|
||||||
GasPricer::new_fixed(0u64.into()),
|
GasPricer::new_fixed(0u64.into()),
|
||||||
&Spec::new_test(),
|
&Spec::new_test(),
|
||||||
Some(Arc::new(account_provider)),
|
HashSet::from_iter(vec![transaction.sender()].into_iter()),
|
||||||
);
|
);
|
||||||
let best_block = 0;
|
let best_block = 0;
|
||||||
|
|
||||||
@ -1587,12 +1588,19 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn should_fail_setting_engine_signer_without_account_provider() {
|
fn should_not_fail_setting_engine_signer_without_account_provider() {
|
||||||
let spec = Spec::new_instant;
|
let spec = Spec::new_test_round;
|
||||||
let tap = Arc::new(AccountProvider::transient_provider());
|
let tap = Arc::new(AccountProvider::transient_provider());
|
||||||
let addr = tap.insert_account(keccak("1").into(), &"".into()).unwrap();
|
let addr = tap.insert_account(keccak("1").into(), &"".into()).unwrap();
|
||||||
let client = generate_dummy_client_with_spec_and_accounts(spec, None);
|
let client = generate_dummy_client_with_spec(spec);
|
||||||
assert!(match client.miner().set_author(addr, Some("".into())) { Err(AccountError::NotFound) => true, _ => false });
|
let engine_signer = Box::new((tap.clone(), addr, "".into()));
|
||||||
|
let msg = Default::default();
|
||||||
|
assert!(client.engine().sign(msg).is_err());
|
||||||
|
|
||||||
|
// should set engine signer and miner author
|
||||||
|
client.miner().set_author(Author::Sealer(engine_signer));
|
||||||
|
assert_eq!(client.miner().authoring_params().author, addr);
|
||||||
|
assert!(client.engine().sign(msg).is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -25,7 +25,8 @@ pub mod pool_client;
|
|||||||
#[cfg(feature = "stratum")]
|
#[cfg(feature = "stratum")]
|
||||||
pub mod stratum;
|
pub mod stratum;
|
||||||
|
|
||||||
pub use self::miner::{Miner, MinerOptions, Penalization, PendingSet, AuthoringParams};
|
pub use self::miner::{Miner, MinerOptions, Penalization, PendingSet, AuthoringParams, Author};
|
||||||
|
pub use ethcore_miner::local_accounts::LocalAccounts;
|
||||||
pub use ethcore_miner::pool::PendingOrdering;
|
pub use ethcore_miner::pool::PendingOrdering;
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
@ -34,7 +35,6 @@ use std::collections::{BTreeSet, BTreeMap};
|
|||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use ethcore_miner::pool::{VerifiedTransaction, QueueStatus, local_transactions};
|
use ethcore_miner::pool::{VerifiedTransaction, QueueStatus, local_transactions};
|
||||||
use ethereum_types::{H256, U256, Address};
|
use ethereum_types::{H256, U256, Address};
|
||||||
use ethkey::Password;
|
|
||||||
use types::transaction::{self, UnverifiedTransaction, SignedTransaction, PendingTransaction};
|
use types::transaction::{self, UnverifiedTransaction, SignedTransaction, PendingTransaction};
|
||||||
use types::BlockNumber;
|
use types::BlockNumber;
|
||||||
use types::block::Block;
|
use types::block::Block;
|
||||||
@ -130,8 +130,8 @@ pub trait MinerService : Send + Sync {
|
|||||||
|
|
||||||
/// Set info necessary to sign consensus messages and block authoring.
|
/// Set info necessary to sign consensus messages and block authoring.
|
||||||
///
|
///
|
||||||
/// On PoW password is optional.
|
/// On chains where sealing is done externally (e.g. PoW) we provide only reward beneficiary.
|
||||||
fn set_author(&self, address: Address, password: Option<Password>) -> Result<(), ::account_provider::SignError>;
|
fn set_author(&self, author: Author);
|
||||||
|
|
||||||
// Transaction Pool
|
// Transaction Pool
|
||||||
|
|
||||||
|
@ -23,6 +23,7 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use ethereum_types::{H256, U256, Address};
|
use ethereum_types::{H256, U256, Address};
|
||||||
|
use ethcore_miner::local_accounts::LocalAccounts;
|
||||||
use ethcore_miner::pool;
|
use ethcore_miner::pool;
|
||||||
use ethcore_miner::pool::client::NonceClient;
|
use ethcore_miner::pool::client::NonceClient;
|
||||||
use ethcore_miner::service_transaction_checker::ServiceTransactionChecker;
|
use ethcore_miner::service_transaction_checker::ServiceTransactionChecker;
|
||||||
@ -34,7 +35,6 @@ use types::transaction::{
|
|||||||
use types::header::Header;
|
use types::header::Header;
|
||||||
use parking_lot::RwLock;
|
use parking_lot::RwLock;
|
||||||
|
|
||||||
use account_provider::AccountProvider;
|
|
||||||
use call_contract::CallContract;
|
use call_contract::CallContract;
|
||||||
use client::{TransactionId, BlockInfo, Nonce};
|
use client::{TransactionId, BlockInfo, Nonce};
|
||||||
use engines::EthEngine;
|
use engines::EthEngine;
|
||||||
@ -73,7 +73,7 @@ pub struct PoolClient<'a, C: 'a> {
|
|||||||
chain: &'a C,
|
chain: &'a C,
|
||||||
cached_nonces: CachedNonceClient<'a, C>,
|
cached_nonces: CachedNonceClient<'a, C>,
|
||||||
engine: &'a EthEngine,
|
engine: &'a EthEngine,
|
||||||
accounts: Option<&'a AccountProvider>,
|
accounts: &'a LocalAccounts,
|
||||||
best_block_header: Header,
|
best_block_header: Header,
|
||||||
service_transaction_checker: Option<ServiceTransactionChecker>,
|
service_transaction_checker: Option<ServiceTransactionChecker>,
|
||||||
}
|
}
|
||||||
@ -92,14 +92,14 @@ impl<'a, C: 'a> Clone for PoolClient<'a, C> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, C: 'a> PoolClient<'a, C> where
|
impl<'a, C: 'a> PoolClient<'a, C> where
|
||||||
C: BlockInfo + CallContract,
|
C: BlockInfo + CallContract,
|
||||||
{
|
{
|
||||||
/// Creates new client given chain, nonce cache, accounts and service transaction verifier.
|
/// Creates new client given chain, nonce cache, accounts and service transaction verifier.
|
||||||
pub fn new(
|
pub fn new(
|
||||||
chain: &'a C,
|
chain: &'a C,
|
||||||
cache: &'a NonceCache,
|
cache: &'a NonceCache,
|
||||||
engine: &'a EthEngine,
|
engine: &'a EthEngine,
|
||||||
accounts: Option<&'a AccountProvider>,
|
accounts: &'a LocalAccounts,
|
||||||
refuse_service_transactions: bool,
|
refuse_service_transactions: bool,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let best_block_header = chain.best_block_header();
|
let best_block_header = chain.best_block_header();
|
||||||
@ -151,7 +151,7 @@ impl<'a, C: 'a> pool::client::Client for PoolClient<'a, C> where
|
|||||||
pool::client::AccountDetails {
|
pool::client::AccountDetails {
|
||||||
nonce: self.cached_nonces.account_nonce(address),
|
nonce: self.cached_nonces.account_nonce(address),
|
||||||
balance: self.chain.latest_balance(address),
|
balance: self.chain.latest_balance(address),
|
||||||
is_local: self.accounts.map_or(false, |accounts| accounts.has_account(*address)),
|
is_local: self.accounts.is_local(address),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -340,7 +340,7 @@ impl Service {
|
|||||||
// replace one the client's database with our own.
|
// replace one the client's database with our own.
|
||||||
fn replace_client_db(&self) -> Result<(), Error> {
|
fn replace_client_db(&self) -> Result<(), Error> {
|
||||||
let migrated_blocks = self.migrate_blocks()?;
|
let migrated_blocks = self.migrate_blocks()?;
|
||||||
trace!(target: "snapshot", "Migrated {} ancient blocks", migrated_blocks);
|
info!(target: "snapshot", "Migrated {} ancient blocks", migrated_blocks);
|
||||||
|
|
||||||
let rest_db = self.restoration_db();
|
let rest_db = self.restoration_db();
|
||||||
self.client.restore_db(&*rest_db.to_string_lossy())?;
|
self.client.restore_db(&*rest_db.to_string_lossy())?;
|
||||||
@ -424,7 +424,7 @@ impl Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if block_number % 10_000 == 0 {
|
if block_number % 10_000 == 0 {
|
||||||
trace!(target: "snapshot", "Block restoration at #{}", block_number);
|
info!(target: "snapshot", "Block restoration at #{}", block_number);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -20,12 +20,12 @@ use std::cell::RefCell;
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
|
||||||
use account_provider::AccountProvider;
|
use accounts::AccountProvider;
|
||||||
use client::{Client, BlockChainClient, ChainInfo};
|
use client::{Client, BlockChainClient, ChainInfo};
|
||||||
use ethkey::Secret;
|
use ethkey::Secret;
|
||||||
use snapshot::tests::helpers as snapshot_helpers;
|
use snapshot::tests::helpers as snapshot_helpers;
|
||||||
use spec::Spec;
|
use spec::Spec;
|
||||||
use test_helpers::generate_dummy_client_with_spec_and_accounts;
|
use test_helpers::generate_dummy_client_with_spec;
|
||||||
use types::transaction::{Transaction, Action, SignedTransaction};
|
use types::transaction::{Transaction, Action, SignedTransaction};
|
||||||
use tempdir::TempDir;
|
use tempdir::TempDir;
|
||||||
|
|
||||||
@ -88,8 +88,7 @@ enum Transition {
|
|||||||
|
|
||||||
// create a chain with the given transitions and some blocks beyond that transition.
|
// create a chain with the given transitions and some blocks beyond that transition.
|
||||||
fn make_chain(accounts: Arc<AccountProvider>, blocks_beyond: usize, transitions: Vec<Transition>) -> Arc<Client> {
|
fn make_chain(accounts: Arc<AccountProvider>, blocks_beyond: usize, transitions: Vec<Transition>) -> Arc<Client> {
|
||||||
let client = generate_dummy_client_with_spec_and_accounts(
|
let client = generate_dummy_client_with_spec(spec_fixed_to_contract);
|
||||||
spec_fixed_to_contract, Some(accounts.clone()));
|
|
||||||
|
|
||||||
let mut cur_signers = vec![*RICH_ADDR];
|
let mut cur_signers = vec![*RICH_ADDR];
|
||||||
{
|
{
|
||||||
@ -100,13 +99,14 @@ fn make_chain(accounts: Arc<AccountProvider>, blocks_beyond: usize, transitions:
|
|||||||
{
|
{
|
||||||
// push a block with given number, signed by one of the signers, with given transactions.
|
// push a block with given number, signed by one of the signers, with given transactions.
|
||||||
let push_block = |signers: &[Address], n, txs: Vec<SignedTransaction>| {
|
let push_block = |signers: &[Address], n, txs: Vec<SignedTransaction>| {
|
||||||
use miner::MinerService;
|
use miner::{self, MinerService};
|
||||||
|
|
||||||
let idx = n as usize % signers.len();
|
let idx = n as usize % signers.len();
|
||||||
trace!(target: "snapshot", "Pushing block #{}, {} txs, author={}",
|
trace!(target: "snapshot", "Pushing block #{}, {} txs, author={}",
|
||||||
n, txs.len(), signers[idx]);
|
n, txs.len(), signers[idx]);
|
||||||
|
|
||||||
client.miner().set_author(signers[idx], Some(PASS.into())).unwrap();
|
let signer = Box::new((accounts.clone(), signers[idx], PASS.into()));
|
||||||
|
client.miner().set_author(miner::Author::Sealer(signer));
|
||||||
client.miner().import_external_transactions(&*client,
|
client.miner().import_external_transactions(&*client,
|
||||||
txs.into_iter().map(Into::into).collect());
|
txs.into_iter().map(Into::into).collect());
|
||||||
|
|
||||||
|
@ -39,7 +39,6 @@ use types::header::Header;
|
|||||||
use types::view;
|
use types::view;
|
||||||
use types::views::BlockView;
|
use types::views::BlockView;
|
||||||
|
|
||||||
use account_provider::AccountProvider;
|
|
||||||
use block::{OpenBlock, Drain};
|
use block::{OpenBlock, Drain};
|
||||||
use client::{Client, ClientConfig, ChainInfo, ImportBlock, ChainNotify, ChainMessageType, PrepareOpenBlock};
|
use client::{Client, ClientConfig, ChainInfo, ImportBlock, ChainNotify, ChainMessageType, PrepareOpenBlock};
|
||||||
use factory::Factories;
|
use factory::Factories;
|
||||||
@ -109,18 +108,15 @@ pub fn generate_dummy_client_with_data(block_number: u32, txs_per_block: usize,
|
|||||||
generate_dummy_client_with_spec_and_data(Spec::new_null, block_number, txs_per_block, tx_gas_prices)
|
generate_dummy_client_with_spec_and_data(Spec::new_null, block_number, txs_per_block, tx_gas_prices)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Generates dummy client (not test client) with corresponding amount of blocks, txs per block and spec
|
|
||||||
pub fn generate_dummy_client_with_spec_and_data<F>(test_spec: F, block_number: u32, txs_per_block: usize, tx_gas_prices: &[U256]) -> Arc<Client> where F: Fn()->Spec {
|
|
||||||
generate_dummy_client_with_spec_accounts_and_data(test_spec, None, block_number, txs_per_block, tx_gas_prices)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Generates dummy client (not test client) with corresponding spec and accounts
|
/// Generates dummy client (not test client) with corresponding spec and accounts
|
||||||
pub fn generate_dummy_client_with_spec_and_accounts<F>(test_spec: F, accounts: Option<Arc<AccountProvider>>) -> Arc<Client> where F: Fn()->Spec {
|
pub fn generate_dummy_client_with_spec<F>(test_spec: F) -> Arc<Client> where F: Fn()->Spec {
|
||||||
generate_dummy_client_with_spec_accounts_and_data(test_spec, accounts, 0, 0, &[])
|
generate_dummy_client_with_spec_and_data(test_spec, 0, 0, &[])
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Generates dummy client (not test client) with corresponding blocks, accounts and spec
|
/// Generates dummy client (not test client) with corresponding amount of blocks, txs per block and spec
|
||||||
pub fn generate_dummy_client_with_spec_accounts_and_data<F>(test_spec: F, accounts: Option<Arc<AccountProvider>>, block_number: u32, txs_per_block: usize, tx_gas_prices: &[U256]) -> Arc<Client> where F: Fn()->Spec {
|
pub fn generate_dummy_client_with_spec_and_data<F>(test_spec: F, block_number: u32, txs_per_block: usize, tx_gas_prices: &[U256]) -> Arc<Client> where
|
||||||
|
F: Fn() -> Spec
|
||||||
|
{
|
||||||
let test_spec = test_spec();
|
let test_spec = test_spec();
|
||||||
let client_db = new_db();
|
let client_db = new_db();
|
||||||
|
|
||||||
@ -128,7 +124,7 @@ pub fn generate_dummy_client_with_spec_accounts_and_data<F>(test_spec: F, accoun
|
|||||||
ClientConfig::default(),
|
ClientConfig::default(),
|
||||||
&test_spec,
|
&test_spec,
|
||||||
client_db,
|
client_db,
|
||||||
Arc::new(Miner::new_for_tests(&test_spec, accounts)),
|
Arc::new(Miner::new_for_tests(&test_spec, None)),
|
||||||
IoChannel::disconnected(),
|
IoChannel::disconnected(),
|
||||||
).unwrap();
|
).unwrap();
|
||||||
let test_engine = &*test_spec.engine;
|
let test_engine = &*test_spec.engine;
|
||||||
|
@ -9,13 +9,13 @@ authors = ["Parity Technologies <admin@parity.io>"]
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
common-types = { path = "../types" }
|
common-types = { path = "../types" }
|
||||||
env_logger = "0.5"
|
|
||||||
ethcore = { path = ".." }
|
ethcore = { path = ".." }
|
||||||
ethcore-io = { path = "../../util/io" }
|
ethcore-io = { path = "../../util/io" }
|
||||||
ethcore-light = { path = "../light" }
|
ethcore-light = { path = "../light" }
|
||||||
ethcore-network = { path = "../../util/network" }
|
ethcore-network = { path = "../../util/network" }
|
||||||
ethcore-network-devp2p = { path = "../../util/network-devp2p" }
|
ethcore-network-devp2p = { path = "../../util/network-devp2p" }
|
||||||
ethereum-types = "0.4"
|
ethereum-types = "0.4"
|
||||||
|
ethkey = { path = "../../accounts/ethkey" }
|
||||||
ethstore = { path = "../../accounts/ethstore" }
|
ethstore = { path = "../../accounts/ethstore" }
|
||||||
fastmap = { path = "../../util/fastmap" }
|
fastmap = { path = "../../util/fastmap" }
|
||||||
hashdb = "0.3.0"
|
hashdb = "0.3.0"
|
||||||
@ -34,9 +34,8 @@ triehash-ethereum = {version = "0.2", path = "../../util/triehash-ethereum" }
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
env_logger = "0.5"
|
env_logger = "0.5"
|
||||||
ethcore-io = { path = "../../util/io", features = ["mio"] }
|
|
||||||
ethkey = { path = "../../accounts/ethkey" }
|
|
||||||
kvdb-memorydb = "0.1"
|
|
||||||
ethcore-private-tx = { path = "../private-tx" }
|
|
||||||
ethcore = { path = "..", features = ["test-helpers"] }
|
ethcore = { path = "..", features = ["test-helpers"] }
|
||||||
|
ethcore-io = { path = "../../util/io", features = ["mio"] }
|
||||||
|
ethcore-private-tx = { path = "../private-tx" }
|
||||||
|
kvdb-memorydb = "0.1"
|
||||||
rustc-hex = "1.0"
|
rustc-hex = "1.0"
|
||||||
|
@ -28,7 +28,7 @@ use network::{NetworkProtocolHandler, NetworkContext, PeerId, ProtocolId,
|
|||||||
use types::pruning_info::PruningInfo;
|
use types::pruning_info::PruningInfo;
|
||||||
use ethereum_types::{H256, H512, U256};
|
use ethereum_types::{H256, H512, U256};
|
||||||
use io::{TimerToken};
|
use io::{TimerToken};
|
||||||
use ethstore::ethkey::Secret;
|
use ethkey::Secret;
|
||||||
use ethcore::client::{BlockChainClient, ChainNotify, NewBlocks, ChainMessageType};
|
use ethcore::client::{BlockChainClient, ChainNotify, NewBlocks, ChainMessageType};
|
||||||
use ethcore::snapshot::SnapshotService;
|
use ethcore::snapshot::SnapshotService;
|
||||||
use types::BlockNumber;
|
use types::BlockNumber;
|
||||||
|
@ -27,6 +27,7 @@ extern crate ethcore_io as io;
|
|||||||
extern crate ethcore_network as network;
|
extern crate ethcore_network as network;
|
||||||
extern crate ethcore_network_devp2p as devp2p;
|
extern crate ethcore_network_devp2p as devp2p;
|
||||||
extern crate ethereum_types;
|
extern crate ethereum_types;
|
||||||
|
extern crate ethkey;
|
||||||
extern crate ethstore;
|
extern crate ethstore;
|
||||||
extern crate fastmap;
|
extern crate fastmap;
|
||||||
extern crate keccak_hash as hash;
|
extern crate keccak_hash as hash;
|
||||||
@ -40,7 +41,6 @@ extern crate ethcore_light as light;
|
|||||||
|
|
||||||
#[cfg(test)] extern crate env_logger;
|
#[cfg(test)] extern crate env_logger;
|
||||||
#[cfg(test)] extern crate ethcore_private_tx;
|
#[cfg(test)] extern crate ethcore_private_tx;
|
||||||
#[cfg(test)] extern crate ethkey;
|
|
||||||
#[cfg(test)] extern crate kvdb_memorydb;
|
#[cfg(test)] extern crate kvdb_memorydb;
|
||||||
#[cfg(test)] extern crate rustc_hex;
|
#[cfg(test)] extern crate rustc_hex;
|
||||||
|
|
||||||
|
@ -19,9 +19,9 @@ use hash::keccak;
|
|||||||
use ethereum_types::{U256, Address};
|
use ethereum_types::{U256, Address};
|
||||||
use io::{IoHandler, IoChannel};
|
use io::{IoHandler, IoChannel};
|
||||||
use ethcore::client::{ChainInfo, ClientIoMessage};
|
use ethcore::client::{ChainInfo, ClientIoMessage};
|
||||||
|
use ethcore::engines;
|
||||||
use ethcore::spec::Spec;
|
use ethcore::spec::Spec;
|
||||||
use ethcore::miner::MinerService;
|
use ethcore::miner::{self, MinerService};
|
||||||
use ethcore::account_provider::AccountProvider;
|
|
||||||
use ethkey::{KeyPair, Secret};
|
use ethkey::{KeyPair, Secret};
|
||||||
use types::transaction::{Action, PendingTransaction, Transaction};
|
use types::transaction::{Action, PendingTransaction, Transaction};
|
||||||
use super::helpers::*;
|
use super::helpers::*;
|
||||||
@ -43,17 +43,14 @@ fn new_tx(secret: &Secret, nonce: U256, chain_id: u64) -> PendingTransaction {
|
|||||||
fn authority_round() {
|
fn authority_round() {
|
||||||
let s0 = KeyPair::from_secret_slice(&keccak("1")).unwrap();
|
let s0 = KeyPair::from_secret_slice(&keccak("1")).unwrap();
|
||||||
let s1 = KeyPair::from_secret_slice(&keccak("0")).unwrap();
|
let s1 = KeyPair::from_secret_slice(&keccak("0")).unwrap();
|
||||||
let ap = Arc::new(AccountProvider::transient_provider());
|
|
||||||
ap.insert_account(s0.secret().clone(), &"".into()).unwrap();
|
|
||||||
ap.insert_account(s1.secret().clone(), &"".into()).unwrap();
|
|
||||||
|
|
||||||
let chain_id = Spec::new_test_round().chain_id();
|
let chain_id = Spec::new_test_round().chain_id();
|
||||||
let mut net = TestNet::with_spec_and_accounts(2, SyncConfig::default(), Spec::new_test_round, Some(ap));
|
let mut net = TestNet::with_spec(2, SyncConfig::default(), Spec::new_test_round);
|
||||||
let io_handler0: Arc<IoHandler<ClientIoMessage>> = Arc::new(TestIoHandler::new(net.peer(0).chain.clone()));
|
let io_handler0: Arc<IoHandler<ClientIoMessage>> = Arc::new(TestIoHandler::new(net.peer(0).chain.clone()));
|
||||||
let io_handler1: Arc<IoHandler<ClientIoMessage>> = Arc::new(TestIoHandler::new(net.peer(1).chain.clone()));
|
let io_handler1: Arc<IoHandler<ClientIoMessage>> = Arc::new(TestIoHandler::new(net.peer(1).chain.clone()));
|
||||||
// Push transaction to both clients. Only one of them gets lucky to produce a block.
|
// Push transaction to both clients. Only one of them gets lucky to produce a block.
|
||||||
net.peer(0).miner.set_author(s0.address(), Some("".into())).unwrap();
|
net.peer(0).miner.set_author(miner::Author::Sealer(engines::signer::from_keypair(s0.clone())));
|
||||||
net.peer(1).miner.set_author(s1.address(), Some("".into())).unwrap();
|
net.peer(1).miner.set_author(miner::Author::Sealer(engines::signer::from_keypair(s1.clone())));
|
||||||
net.peer(0).chain.engine().register_client(Arc::downgrade(&net.peer(0).chain) as _);
|
net.peer(0).chain.engine().register_client(Arc::downgrade(&net.peer(0).chain) as _);
|
||||||
net.peer(1).chain.engine().register_client(Arc::downgrade(&net.peer(1).chain) as _);
|
net.peer(1).chain.engine().register_client(Arc::downgrade(&net.peer(1).chain) as _);
|
||||||
net.peer(0).chain.set_io_channel(IoChannel::to_handler(Arc::downgrade(&io_handler1)));
|
net.peer(0).chain.set_io_channel(IoChannel::to_handler(Arc::downgrade(&io_handler1)));
|
||||||
|
@ -25,7 +25,6 @@ use ethcore::client::{TestBlockChainClient, BlockChainClient, Client as EthcoreC
|
|||||||
ClientConfig, ChainNotify, NewBlocks, ChainMessageType, ClientIoMessage};
|
ClientConfig, ChainNotify, NewBlocks, ChainMessageType, ClientIoMessage};
|
||||||
use ethcore::snapshot::SnapshotService;
|
use ethcore::snapshot::SnapshotService;
|
||||||
use ethcore::spec::Spec;
|
use ethcore::spec::Spec;
|
||||||
use ethcore::account_provider::AccountProvider;
|
|
||||||
use ethcore::miner::Miner;
|
use ethcore::miner::Miner;
|
||||||
use ethcore::test_helpers;
|
use ethcore::test_helpers;
|
||||||
use sync_io::SyncIo;
|
use sync_io::SyncIo;
|
||||||
@ -367,11 +366,10 @@ impl TestNet<EthPeer<TestBlockChainClient>> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl TestNet<EthPeer<EthcoreClient>> {
|
impl TestNet<EthPeer<EthcoreClient>> {
|
||||||
pub fn with_spec_and_accounts<F>(
|
pub fn with_spec<F>(
|
||||||
n: usize,
|
n: usize,
|
||||||
config: SyncConfig,
|
config: SyncConfig,
|
||||||
spec_factory: F,
|
spec_factory: F,
|
||||||
accounts: Option<Arc<AccountProvider>>
|
|
||||||
) -> Self
|
) -> Self
|
||||||
where F: Fn() -> Spec
|
where F: Fn() -> Spec
|
||||||
{
|
{
|
||||||
@ -381,14 +379,14 @@ impl TestNet<EthPeer<EthcoreClient>> {
|
|||||||
disconnect_events: Vec::new(),
|
disconnect_events: Vec::new(),
|
||||||
};
|
};
|
||||||
for _ in 0..n {
|
for _ in 0..n {
|
||||||
net.add_peer_with_private_config(config.clone(), spec_factory(), accounts.clone());
|
net.add_peer_with_private_config(config.clone(), spec_factory());
|
||||||
}
|
}
|
||||||
net
|
net
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_peer_with_private_config(&mut self, config: SyncConfig, spec: Spec, accounts: Option<Arc<AccountProvider>>) {
|
pub fn add_peer_with_private_config(&mut self, config: SyncConfig, spec: Spec) {
|
||||||
let channel = IoChannel::disconnected();
|
let channel = IoChannel::disconnected();
|
||||||
let miner = Arc::new(Miner::new_for_tests(&spec, accounts.clone()));
|
let miner = Arc::new(Miner::new_for_tests(&spec, None));
|
||||||
let client = EthcoreClient::new(
|
let client = EthcoreClient::new(
|
||||||
ClientConfig::default(),
|
ClientConfig::default(),
|
||||||
&spec,
|
&spec,
|
||||||
|
@ -17,16 +17,17 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use hash::keccak;
|
use hash::keccak;
|
||||||
use io::{IoHandler, IoChannel};
|
use io::{IoHandler, IoChannel};
|
||||||
use ethcore::client::{BlockChainClient, BlockId, ClientIoMessage};
|
|
||||||
use ethcore::spec::Spec;
|
|
||||||
use ethcore::miner::MinerService;
|
|
||||||
use ethcore::CreateContractAddress;
|
|
||||||
use types::transaction::{Transaction, Action};
|
use types::transaction::{Transaction, Action};
|
||||||
|
use types::ids::BlockId;
|
||||||
|
use ethcore::CreateContractAddress;
|
||||||
|
use ethcore::client::{ClientIoMessage, BlockChainClient};
|
||||||
use ethcore::executive::{contract_address};
|
use ethcore::executive::{contract_address};
|
||||||
|
use ethcore::engines;
|
||||||
|
use ethcore::miner::{self, MinerService};
|
||||||
|
use ethcore::spec::Spec;
|
||||||
use ethcore::test_helpers::{push_block_with_transactions};
|
use ethcore::test_helpers::{push_block_with_transactions};
|
||||||
use ethcore_private_tx::{Provider, ProviderConfig, NoopEncryptor, Importer, SignedPrivateTransaction, StoringKeyProvider};
|
use ethcore_private_tx::{Provider, ProviderConfig, NoopEncryptor, Importer, SignedPrivateTransaction, StoringKeyProvider};
|
||||||
use ethcore::account_provider::AccountProvider;
|
use ethkey::KeyPair;
|
||||||
use ethkey::{KeyPair};
|
|
||||||
use tests::helpers::{TestNet, TestIoHandler};
|
use tests::helpers::{TestNet, TestIoHandler};
|
||||||
use rustc_hex::FromHex;
|
use rustc_hex::FromHex;
|
||||||
use rlp::Rlp;
|
use rlp::Rlp;
|
||||||
@ -42,18 +43,17 @@ fn send_private_transaction() {
|
|||||||
// Setup two clients
|
// Setup two clients
|
||||||
let s0 = KeyPair::from_secret_slice(&keccak("1")).unwrap();
|
let s0 = KeyPair::from_secret_slice(&keccak("1")).unwrap();
|
||||||
let s1 = KeyPair::from_secret_slice(&keccak("0")).unwrap();
|
let s1 = KeyPair::from_secret_slice(&keccak("0")).unwrap();
|
||||||
let ap = Arc::new(AccountProvider::transient_provider());
|
|
||||||
ap.insert_account(s0.secret().clone(), &"".into()).unwrap();
|
|
||||||
ap.insert_account(s1.secret().clone(), &"".into()).unwrap();
|
|
||||||
|
|
||||||
let mut net = TestNet::with_spec_and_accounts(2, SyncConfig::default(), seal_spec, Some(ap.clone()));
|
let signer = Arc::new(ethcore_private_tx::KeyPairSigner(vec![s0.clone(), s1.clone()]));
|
||||||
|
|
||||||
|
let mut net = TestNet::with_spec(2, SyncConfig::default(), seal_spec);
|
||||||
let client0 = net.peer(0).chain.clone();
|
let client0 = net.peer(0).chain.clone();
|
||||||
let client1 = net.peer(1).chain.clone();
|
let client1 = net.peer(1).chain.clone();
|
||||||
let io_handler0: Arc<IoHandler<ClientIoMessage>> = Arc::new(TestIoHandler::new(net.peer(0).chain.clone()));
|
let io_handler0: Arc<IoHandler<ClientIoMessage>> = Arc::new(TestIoHandler::new(net.peer(0).chain.clone()));
|
||||||
let io_handler1: Arc<IoHandler<ClientIoMessage>> = Arc::new(TestIoHandler::new(net.peer(1).chain.clone()));
|
let io_handler1: Arc<IoHandler<ClientIoMessage>> = Arc::new(TestIoHandler::new(net.peer(1).chain.clone()));
|
||||||
|
|
||||||
net.peer(0).miner.set_author(s0.address(), Some("".into())).unwrap();
|
net.peer(0).miner.set_author(miner::Author::Sealer(engines::signer::from_keypair(s0.clone())));
|
||||||
net.peer(1).miner.set_author(s1.address(), Some("".into())).unwrap();
|
net.peer(1).miner.set_author(miner::Author::Sealer(engines::signer::from_keypair(s1.clone())));
|
||||||
net.peer(0).chain.engine().register_client(Arc::downgrade(&net.peer(0).chain) as _);
|
net.peer(0).chain.engine().register_client(Arc::downgrade(&net.peer(0).chain) as _);
|
||||||
net.peer(1).chain.engine().register_client(Arc::downgrade(&net.peer(1).chain) as _);
|
net.peer(1).chain.engine().register_client(Arc::downgrade(&net.peer(1).chain) as _);
|
||||||
net.peer(0).chain.set_io_channel(IoChannel::to_handler(Arc::downgrade(&io_handler0)));
|
net.peer(0).chain.set_io_channel(IoChannel::to_handler(Arc::downgrade(&io_handler0)));
|
||||||
@ -69,13 +69,11 @@ fn send_private_transaction() {
|
|||||||
let validator_config = ProviderConfig{
|
let validator_config = ProviderConfig{
|
||||||
validator_accounts: vec![s1.address()],
|
validator_accounts: vec![s1.address()],
|
||||||
signer_account: None,
|
signer_account: None,
|
||||||
passwords: vec!["".into()],
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let signer_config = ProviderConfig{
|
let signer_config = ProviderConfig{
|
||||||
validator_accounts: Vec::new(),
|
validator_accounts: Vec::new(),
|
||||||
signer_account: Some(s0.address()),
|
signer_account: Some(s0.address()),
|
||||||
passwords: vec!["".into()],
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let private_keys = Arc::new(StoringKeyProvider::default());
|
let private_keys = Arc::new(StoringKeyProvider::default());
|
||||||
@ -83,7 +81,7 @@ fn send_private_transaction() {
|
|||||||
let pm0 = Arc::new(Provider::new(
|
let pm0 = Arc::new(Provider::new(
|
||||||
client0.clone(),
|
client0.clone(),
|
||||||
net.peer(0).miner.clone(),
|
net.peer(0).miner.clone(),
|
||||||
ap.clone(),
|
signer.clone(),
|
||||||
Box::new(NoopEncryptor::default()),
|
Box::new(NoopEncryptor::default()),
|
||||||
signer_config,
|
signer_config,
|
||||||
IoChannel::to_handler(Arc::downgrade(&io_handler0)),
|
IoChannel::to_handler(Arc::downgrade(&io_handler0)),
|
||||||
@ -94,7 +92,7 @@ fn send_private_transaction() {
|
|||||||
let pm1 = Arc::new(Provider::new(
|
let pm1 = Arc::new(Provider::new(
|
||||||
client1.clone(),
|
client1.clone(),
|
||||||
net.peer(1).miner.clone(),
|
net.peer(1).miner.clone(),
|
||||||
ap.clone(),
|
signer.clone(),
|
||||||
Box::new(NoopEncryptor::default()),
|
Box::new(NoopEncryptor::default()),
|
||||||
validator_config,
|
validator_config,
|
||||||
IoChannel::to_handler(Arc::downgrade(&io_handler1)),
|
IoChannel::to_handler(Arc::downgrade(&io_handler1)),
|
||||||
|
@ -30,5 +30,4 @@ pub mod vm;
|
|||||||
pub mod maybe;
|
pub mod maybe;
|
||||||
pub mod state;
|
pub mod state;
|
||||||
pub mod transaction;
|
pub mod transaction;
|
||||||
pub mod misc;
|
|
||||||
pub mod test;
|
pub mod test;
|
||||||
|
@ -1,52 +0,0 @@
|
|||||||
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
|
|
||||||
// This file is part of Parity Ethereum.
|
|
||||||
|
|
||||||
// Parity Ethereum 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 Ethereum 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 Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
//! Misc deserialization.
|
|
||||||
|
|
||||||
macro_rules! impl_serialization {
|
|
||||||
($key: ty => $name: ty) => {
|
|
||||||
impl $name {
|
|
||||||
/// Read a hash map of DappId -> $name
|
|
||||||
pub fn read<R, S, D>(reader: R) -> Result<::std::collections::HashMap<D, S>, ::serde_json::Error> where
|
|
||||||
R: ::std::io::Read,
|
|
||||||
D: From<$key> + ::std::hash::Hash + Eq,
|
|
||||||
S: From<$name> + Clone,
|
|
||||||
{
|
|
||||||
::serde_json::from_reader(reader).map(|ok: ::std::collections::HashMap<$key, $name>|
|
|
||||||
ok.into_iter().map(|(a, m)| (a.into(), m.into())).collect()
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Write a hash map of DappId -> $name
|
|
||||||
pub fn write<W, S, D>(m: &::std::collections::HashMap<D, S>, writer: &mut W) -> Result<(), ::serde_json::Error> where
|
|
||||||
W: ::std::io::Write,
|
|
||||||
D: Into<$key> + ::std::hash::Hash + Eq + Clone,
|
|
||||||
S: Into<$name> + Clone,
|
|
||||||
{
|
|
||||||
::serde_json::to_writer(
|
|
||||||
writer,
|
|
||||||
&m.iter()
|
|
||||||
.map(|(a, m)| (a.clone().into(), m.clone().into()))
|
|
||||||
.collect::<::std::collections::HashMap<$key, $name>>()
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
mod account_meta;
|
|
||||||
|
|
||||||
pub use self::account_meta::AccountMeta;
|
|
@ -57,6 +57,7 @@ pub mod external;
|
|||||||
#[cfg(feature = "price-info")]
|
#[cfg(feature = "price-info")]
|
||||||
pub mod gas_price_calibrator;
|
pub mod gas_price_calibrator;
|
||||||
pub mod gas_pricer;
|
pub mod gas_pricer;
|
||||||
|
pub mod local_accounts;
|
||||||
pub mod pool;
|
pub mod pool;
|
||||||
pub mod service_transaction_checker;
|
pub mod service_transaction_checker;
|
||||||
#[cfg(feature = "work-notify")]
|
#[cfg(feature = "work-notify")]
|
||||||
|
@ -14,14 +14,30 @@
|
|||||||
// You should have received a copy of the GNU General Public License
|
// You should have received a copy of the GNU General Public License
|
||||||
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
use std::sync::Arc;
|
//! Local Accounts checker
|
||||||
use ethcore::account_provider::AccountProvider;
|
|
||||||
use jsonrpc_core::Error;
|
|
||||||
use v1::helpers::errors;
|
|
||||||
|
|
||||||
pub fn unwrap_provider(provider: &Option<Arc<AccountProvider>>) -> Result<Arc<AccountProvider>, Error> {
|
use std::collections::HashSet;
|
||||||
match *provider {
|
|
||||||
Some(ref arc) => Ok(arc.clone()),
|
use ethereum_types::Address;
|
||||||
None => Err(errors::public_unsupported(None)),
|
|
||||||
|
/// Local accounts checker
|
||||||
|
pub trait LocalAccounts: Send + Sync {
|
||||||
|
/// Returns true if given address should be considered local account.
|
||||||
|
fn is_local(&self, &Address) -> bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LocalAccounts for HashSet<Address> {
|
||||||
|
fn is_local(&self, address: &Address) -> bool {
|
||||||
|
self.contains(address)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl<A, B> LocalAccounts for (A, B) where
|
||||||
|
A: LocalAccounts,
|
||||||
|
B: LocalAccounts,
|
||||||
|
{
|
||||||
|
fn is_local(&self, address: &Address) -> bool {
|
||||||
|
self.0.is_local(address) || self.1.is_local(address)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -15,12 +15,6 @@
|
|||||||
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
use std::num::NonZeroU32;
|
use std::num::NonZeroU32;
|
||||||
use std::path::PathBuf;
|
|
||||||
use ethstore::{EthStore, SecretStore, import_account, import_accounts, read_geth_accounts};
|
|
||||||
use ethstore::accounts_dir::RootDiskDirectory;
|
|
||||||
use ethstore::SecretVaultRef;
|
|
||||||
use ethcore::account_provider::{AccountProvider, AccountProviderSettings};
|
|
||||||
use helpers::{password_prompt, password_from_file};
|
|
||||||
use params::SpecType;
|
use params::SpecType;
|
||||||
|
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Debug, PartialEq)]
|
||||||
@ -62,30 +56,45 @@ pub struct ImportFromGethAccounts {
|
|||||||
pub spec: SpecType,
|
pub spec: SpecType,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#[cfg(not(feature = "accounts"))]
|
||||||
pub fn execute(cmd: AccountCmd) -> Result<String, String> {
|
pub fn execute(cmd: AccountCmd) -> Result<String, String> {
|
||||||
|
Err("Account management is deprecated. Please see #9997 for alternatives:\nhttps://github.com/paritytech/parity-ethereum/issues/9997".into())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "accounts")]
|
||||||
|
mod command {
|
||||||
|
use super::*;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use accounts::{AccountProvider, AccountProviderSettings};
|
||||||
|
use ethstore::{EthStore, SecretStore, SecretVaultRef, import_account, import_accounts, read_geth_accounts};
|
||||||
|
use ethstore::accounts_dir::RootDiskDirectory;
|
||||||
|
use helpers::{password_prompt, password_from_file};
|
||||||
|
|
||||||
|
pub fn execute(cmd: AccountCmd) -> Result<String, String> {
|
||||||
match cmd {
|
match cmd {
|
||||||
AccountCmd::New(new_cmd) => new(new_cmd),
|
AccountCmd::New(new_cmd) => new(new_cmd),
|
||||||
AccountCmd::List(list_cmd) => list(list_cmd),
|
AccountCmd::List(list_cmd) => list(list_cmd),
|
||||||
AccountCmd::Import(import_cmd) => import(import_cmd),
|
AccountCmd::Import(import_cmd) => import(import_cmd),
|
||||||
AccountCmd::ImportFromGeth(import_geth_cmd) => import_geth(import_geth_cmd)
|
AccountCmd::ImportFromGeth(import_geth_cmd) => import_geth(import_geth_cmd)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn keys_dir(path: String, spec: SpecType) -> Result<RootDiskDirectory, String> {
|
fn keys_dir(path: String, spec: SpecType) -> Result<RootDiskDirectory, String> {
|
||||||
let spec = spec.spec(&::std::env::temp_dir())?;
|
let spec = spec.spec(&::std::env::temp_dir())?;
|
||||||
let mut path = PathBuf::from(&path);
|
let mut path = PathBuf::from(&path);
|
||||||
path.push(spec.data_dir);
|
path.push(spec.data_dir);
|
||||||
RootDiskDirectory::create(path).map_err(|e| format!("Could not open keys directory: {}", e))
|
RootDiskDirectory::create(path).map_err(|e| format!("Could not open keys directory: {}", e))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn secret_store(dir: Box<RootDiskDirectory>, iterations: Option<NonZeroU32>) -> Result<EthStore, String> {
|
fn secret_store(dir: Box<RootDiskDirectory>, iterations: Option<NonZeroU32>) -> Result<EthStore, String> {
|
||||||
match iterations {
|
match iterations {
|
||||||
Some(i) => EthStore::open_with_iterations(dir, i),
|
Some(i) => EthStore::open_with_iterations(dir, i),
|
||||||
_ => EthStore::open(dir)
|
_ => EthStore::open(dir)
|
||||||
}.map_err(|e| format!("Could not open keys store: {}", e))
|
}.map_err(|e| format!("Could not open keys store: {}", e))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn new(n: NewAccount) -> Result<String, String> {
|
fn new(n: NewAccount) -> Result<String, String> {
|
||||||
let password = match n.password_file {
|
let password = match n.password_file {
|
||||||
Some(file) => password_from_file(file)?,
|
Some(file) => password_from_file(file)?,
|
||||||
None => password_prompt()?,
|
None => password_prompt()?,
|
||||||
@ -96,9 +105,9 @@ fn new(n: NewAccount) -> Result<String, String> {
|
|||||||
let acc_provider = AccountProvider::new(secret_store, AccountProviderSettings::default());
|
let acc_provider = AccountProvider::new(secret_store, AccountProviderSettings::default());
|
||||||
let new_account = acc_provider.new_account(&password).map_err(|e| format!("Could not create new account: {}", e))?;
|
let new_account = acc_provider.new_account(&password).map_err(|e| format!("Could not create new account: {}", e))?;
|
||||||
Ok(format!("0x{:x}", new_account))
|
Ok(format!("0x{:x}", new_account))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list(list_cmd: ListAccounts) -> Result<String, String> {
|
fn list(list_cmd: ListAccounts) -> Result<String, String> {
|
||||||
let dir = Box::new(keys_dir(list_cmd.path, list_cmd.spec)?);
|
let dir = Box::new(keys_dir(list_cmd.path, list_cmd.spec)?);
|
||||||
let secret_store = Box::new(secret_store(dir, None)?);
|
let secret_store = Box::new(secret_store(dir, None)?);
|
||||||
let acc_provider = AccountProvider::new(secret_store, AccountProviderSettings::default());
|
let acc_provider = AccountProvider::new(secret_store, AccountProviderSettings::default());
|
||||||
@ -109,9 +118,9 @@ fn list(list_cmd: ListAccounts) -> Result<String, String> {
|
|||||||
.join("\n");
|
.join("\n");
|
||||||
|
|
||||||
Ok(result)
|
Ok(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn import(i: ImportAccounts) -> Result<String, String> {
|
fn import(i: ImportAccounts) -> Result<String, String> {
|
||||||
let to = keys_dir(i.to, i.spec)?;
|
let to = keys_dir(i.to, i.spec)?;
|
||||||
let mut imported = 0;
|
let mut imported = 0;
|
||||||
|
|
||||||
@ -127,9 +136,9 @@ fn import(i: ImportAccounts) -> Result<String, String> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Ok(format!("{} account(s) imported", imported))
|
Ok(format!("{} account(s) imported", imported))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn import_geth(i: ImportFromGethAccounts) -> Result<String, String> {
|
fn import_geth(i: ImportFromGethAccounts) -> Result<String, String> {
|
||||||
use std::io::ErrorKind;
|
use std::io::ErrorKind;
|
||||||
use ethstore::Error;
|
use ethstore::Error;
|
||||||
|
|
||||||
@ -141,4 +150,8 @@ fn import_geth(i: ImportFromGethAccounts) -> Result<String, String> {
|
|||||||
Err(Error::Io(ref io_err)) if io_err.kind() == ErrorKind::NotFound => Err("Failed to find geth keys folder.".into()),
|
Err(Error::Io(ref io_err)) if io_err.kind() == ErrorKind::NotFound => Err("Failed to find geth keys folder.".into()),
|
||||||
Err(err) => Err(format!("Import geth accounts failed. {}", err))
|
Err(err) => Err(format!("Import geth accounts failed. {}", err))
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "accounts")]
|
||||||
|
pub use self::command::execute;
|
||||||
|
244
parity/account_utils.rs
Normal file
244
parity/account_utils.rs
Normal file
@ -0,0 +1,244 @@
|
|||||||
|
// 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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use dir::Directories;
|
||||||
|
use ethereum_types::Address;
|
||||||
|
use ethkey::Password;
|
||||||
|
|
||||||
|
use params::{SpecType, AccountsConfig};
|
||||||
|
|
||||||
|
#[cfg(not(feature = "accounts"))]
|
||||||
|
mod accounts {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
/// Dummy AccountProvider
|
||||||
|
pub struct AccountProvider;
|
||||||
|
|
||||||
|
impl ::ethcore::miner::LocalAccounts for AccountProvider {
|
||||||
|
fn is_local(&self, address: &Address) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn prepare_account_provider(_spec: &SpecType, _dirs: &Directories, _data_dir: &str, cfg: AccountsConfig, _passwords: &[Password]) -> Result<AccountProvider, String> {
|
||||||
|
warn!("Note: Your instance of Parity Ethereum is running without account support. Some CLI options are ignored.");
|
||||||
|
Ok(AccountProvider)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn miner_local_accounts(_: Arc<AccountProvider>) -> AccountProvider {
|
||||||
|
AccountProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn miner_author(_spec: &SpecType, _dirs: &Directories, _account_provider: &Arc<AccountProvider>, _engine_signer: Address, _passwords: &[Password]) -> Result<Option<::ethcore::miner::Author>, String> {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn private_tx_signer(_account_provider: Arc<AccountProvider>, _passwords: &[Password]) -> Result<Arc<::ethcore_private_tx::Signer>, String> {
|
||||||
|
Ok(Arc::new(::ethcore_private_tx::DummySigner))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn accounts_list(_account_provider: Arc<AccountProvider>) -> Arc<Fn() -> Vec<Address> + Send + Sync> {
|
||||||
|
Arc::new(|| vec![])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "accounts")]
|
||||||
|
mod accounts {
|
||||||
|
use super::*;
|
||||||
|
use upgrade::upgrade_key_location;
|
||||||
|
|
||||||
|
pub use accounts::AccountProvider;
|
||||||
|
|
||||||
|
/// Pops along with error messages when a password is missing or invalid.
|
||||||
|
const VERIFY_PASSWORD_HINT: &str = "Make sure valid password is present in files passed using `--password` or in the configuration file.";
|
||||||
|
|
||||||
|
/// Initialize account provider
|
||||||
|
pub fn prepare_account_provider(spec: &SpecType, dirs: &Directories, data_dir: &str, cfg: AccountsConfig, passwords: &[Password]) -> Result<AccountProvider, String> {
|
||||||
|
use ethstore::EthStore;
|
||||||
|
use ethstore::accounts_dir::RootDiskDirectory;
|
||||||
|
use accounts::AccountProviderSettings;
|
||||||
|
|
||||||
|
let path = dirs.keys_path(data_dir);
|
||||||
|
upgrade_key_location(&dirs.legacy_keys_path(cfg.testnet), &path);
|
||||||
|
let dir = Box::new(RootDiskDirectory::create(&path).map_err(|e| format!("Could not open keys directory: {}", e))?);
|
||||||
|
let account_settings = AccountProviderSettings {
|
||||||
|
enable_hardware_wallets: cfg.enable_hardware_wallets,
|
||||||
|
hardware_wallet_classic_key: spec == &SpecType::Classic,
|
||||||
|
unlock_keep_secret: cfg.enable_fast_unlock,
|
||||||
|
blacklisted_accounts: match *spec {
|
||||||
|
SpecType::Morden | SpecType::Ropsten | SpecType::Kovan | SpecType::Sokol | SpecType::Dev => vec![],
|
||||||
|
_ => vec![
|
||||||
|
"00a329c0648769a73afac7f9381e08fb43dbea72".into()
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
let ethstore = EthStore::open_with_iterations(dir, cfg.iterations).map_err(|e| format!("Could not open keys directory: {}", e))?;
|
||||||
|
if cfg.refresh_time > 0 {
|
||||||
|
ethstore.set_refresh_time(::std::time::Duration::from_secs(cfg.refresh_time));
|
||||||
|
}
|
||||||
|
let account_provider = AccountProvider::new(
|
||||||
|
Box::new(ethstore),
|
||||||
|
account_settings,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Add development account if running dev chain:
|
||||||
|
if let SpecType::Dev = *spec {
|
||||||
|
insert_dev_account(&account_provider);
|
||||||
|
}
|
||||||
|
|
||||||
|
for a in cfg.unlocked_accounts {
|
||||||
|
// Check if the account exists
|
||||||
|
if !account_provider.has_account(a) {
|
||||||
|
return Err(format!("Account {} not found for the current chain. {}", a, build_create_account_hint(spec, &dirs.keys)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if any passwords have been read from the password file(s)
|
||||||
|
if passwords.is_empty() {
|
||||||
|
return Err(format!("No password found to unlock account {}. {}", a, VERIFY_PASSWORD_HINT));
|
||||||
|
}
|
||||||
|
|
||||||
|
if !passwords.iter().any(|p| account_provider.unlock_account_permanently(a, (*p).clone()).is_ok()) {
|
||||||
|
return Err(format!("No valid password to unlock account {}. {}", a, VERIFY_PASSWORD_HINT));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(account_provider)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct LocalAccounts(Arc<AccountProvider>);
|
||||||
|
impl ::ethcore::miner::LocalAccounts for LocalAccounts {
|
||||||
|
fn is_local(&self, address: &Address) -> bool {
|
||||||
|
self.0.has_account(*address)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn miner_local_accounts(account_provider: Arc<AccountProvider>) -> LocalAccounts {
|
||||||
|
LocalAccounts(account_provider)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn miner_author(spec: &SpecType, dirs: &Directories, account_provider: &Arc<AccountProvider>, engine_signer: Address, passwords: &[Password]) -> Result<Option<::ethcore::miner::Author>, String> {
|
||||||
|
use ethcore::engines::EngineSigner;
|
||||||
|
|
||||||
|
// Check if engine signer exists
|
||||||
|
if !account_provider.has_account(engine_signer) {
|
||||||
|
return Err(format!("Consensus signer account not found for the current chain. {}", build_create_account_hint(spec, &dirs.keys)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if any passwords have been read from the password file(s)
|
||||||
|
if passwords.is_empty() {
|
||||||
|
return Err(format!("No password found for the consensus signer {}. {}", engine_signer, VERIFY_PASSWORD_HINT));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut author = None;
|
||||||
|
for password in passwords {
|
||||||
|
let signer = parity_rpc::signer::EngineSigner::new(
|
||||||
|
account_provider.clone(),
|
||||||
|
engine_signer,
|
||||||
|
password.clone(),
|
||||||
|
);
|
||||||
|
if signer.sign(Default::default()).is_ok() {
|
||||||
|
author = Some(::ethcore::miner::Author::Sealer(Box::new(signer)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if author.is_none() {
|
||||||
|
return Err(format!("No valid password for the consensus signer {}. {}", engine_signer, VERIFY_PASSWORD_HINT));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(author)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
mod private_tx {
|
||||||
|
use super::*;
|
||||||
|
use ethkey::{Signature, Message};
|
||||||
|
use ethcore_private_tx::{Error};
|
||||||
|
|
||||||
|
pub struct AccountSigner {
|
||||||
|
pub accounts: Arc<AccountProvider>,
|
||||||
|
pub passwords: Vec<Password>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ::ethcore_private_tx::Signer for AccountSigner {
|
||||||
|
fn decrypt(&self, account: Address, shared_mac: &[u8], payload: &[u8]) -> Result<Vec<u8>, Error> {
|
||||||
|
let password = self.find_account_password(&account);
|
||||||
|
Ok(self.accounts.decrypt(account, password, shared_mac, payload).map_err(|e| e.to_string())?)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sign(&self, account: Address, hash: Message) -> Result<Signature, Error> {
|
||||||
|
let password = self.find_account_password(&account);
|
||||||
|
Ok(self.accounts.sign(account, password, hash).map_err(|e| e.to_string())?)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AccountSigner {
|
||||||
|
/// Try to unlock account using stored password, return found password if any
|
||||||
|
fn find_account_password(&self, account: &Address) -> Option<Password> {
|
||||||
|
for password in &self.passwords {
|
||||||
|
if let Ok(true) = self.accounts.test_password(account, password) {
|
||||||
|
return Some(password.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn private_tx_signer(accounts: Arc<AccountProvider>, passwords: &[Password]) -> Result<Arc<::ethcore_private_tx::Signer>, String> {
|
||||||
|
Ok(Arc::new(self::private_tx::AccountSigner {
|
||||||
|
accounts,
|
||||||
|
passwords: passwords.to_vec(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn accounts_list(account_provider: Arc<AccountProvider>) -> Arc<Fn() -> Vec<Address> + Send + Sync> {
|
||||||
|
Arc::new(move || account_provider.accounts().unwrap_or_default())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn insert_dev_account(account_provider: &AccountProvider) {
|
||||||
|
let secret: ethkey::Secret = "4d5db4107d237df6a3d58ee5f70ae63d73d7658d4026f2eefd2f204c81682cb7".into();
|
||||||
|
let dev_account = ethkey::KeyPair::from_secret(secret.clone()).expect("Valid secret produces valid key;qed");
|
||||||
|
if !account_provider.has_account(dev_account.address()) {
|
||||||
|
match account_provider.insert_account(secret, &Password::from(String::new())) {
|
||||||
|
Err(e) => warn!("Unable to add development account: {}", e),
|
||||||
|
Ok(address) => {
|
||||||
|
let _ = account_provider.set_account_name(address.clone(), "Development Account".into());
|
||||||
|
let _ = account_provider.set_account_meta(address, ::serde_json::to_string(&(vec![
|
||||||
|
("description", "Never use this account outside of development chain!"),
|
||||||
|
("passwordHint","Password is empty string"),
|
||||||
|
].into_iter().collect::<::std::collections::HashMap<_,_>>())).expect("Serialization of hashmap does not fail."));
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Construct an error `String` with an adaptive hint on how to create an account.
|
||||||
|
fn build_create_account_hint(spec: &SpecType, keys: &str) -> String {
|
||||||
|
format!("You can create an account via RPC, UI or `parity account new --chain {} --keys-path {}`.", spec, keys)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub use self::accounts::{
|
||||||
|
AccountProvider,
|
||||||
|
prepare_account_provider,
|
||||||
|
miner_local_accounts,
|
||||||
|
miner_author,
|
||||||
|
private_tx_signer,
|
||||||
|
accounts_list,
|
||||||
|
};
|
||||||
|
|
@ -25,9 +25,9 @@ use hash::{keccak, KECCAK_NULL_RLP};
|
|||||||
use ethereum_types::{U256, H256, Address};
|
use ethereum_types::{U256, H256, Address};
|
||||||
use bytes::ToPretty;
|
use bytes::ToPretty;
|
||||||
use rlp::PayloadInfo;
|
use rlp::PayloadInfo;
|
||||||
use ethcore::account_provider::AccountProvider;
|
use ethcore::client::{
|
||||||
use ethcore::client::{Mode, DatabaseCompactionProfile, VMType, Nonce, Balance, BlockChainClient, BlockId, BlockInfo,
|
Mode, DatabaseCompactionProfile, VMType, Nonce, Balance, BlockChainClient, BlockId, BlockInfo, ImportBlock, BlockChainReset
|
||||||
ImportBlock, BlockChainReset};
|
};
|
||||||
use ethcore::error::{ImportErrorKind, ErrorKind as EthcoreErrorKind, Error as EthcoreError};
|
use ethcore::error::{ImportErrorKind, ErrorKind as EthcoreErrorKind, Error as EthcoreError};
|
||||||
use ethcore::miner::Miner;
|
use ethcore::miner::Miner;
|
||||||
use ethcore::verification::queue::VerifierSettings;
|
use ethcore::verification::queue::VerifierSettings;
|
||||||
@ -395,7 +395,7 @@ fn execute_import(cmd: ImportBlockchain) -> Result<(), String> {
|
|||||||
// TODO [ToDr] don't use test miner here
|
// TODO [ToDr] don't use test miner here
|
||||||
// (actually don't require miner at all)
|
// (actually don't require miner at all)
|
||||||
Arc::new(Miner::new_for_tests(&spec, None)),
|
Arc::new(Miner::new_for_tests(&spec, None)),
|
||||||
Arc::new(AccountProvider::transient_provider()),
|
Arc::new(ethcore_private_tx::DummySigner),
|
||||||
Box::new(ethcore_private_tx::NoopEncryptor),
|
Box::new(ethcore_private_tx::NoopEncryptor),
|
||||||
Default::default(),
|
Default::default(),
|
||||||
Default::default(),
|
Default::default(),
|
||||||
@ -587,7 +587,7 @@ fn start_client(
|
|||||||
// It's fine to use test version here,
|
// It's fine to use test version here,
|
||||||
// since we don't care about miner parameters at all
|
// since we don't care about miner parameters at all
|
||||||
Arc::new(Miner::new_for_tests(&spec, None)),
|
Arc::new(Miner::new_for_tests(&spec, None)),
|
||||||
Arc::new(AccountProvider::transient_provider()),
|
Arc::new(ethcore_private_tx::DummySigner),
|
||||||
Box::new(ethcore_private_tx::NoopEncryptor),
|
Box::new(ethcore_private_tx::NoopEncryptor),
|
||||||
Default::default(),
|
Default::default(),
|
||||||
Default::default(),
|
Default::default(),
|
||||||
|
@ -29,7 +29,7 @@ use parity_version::{version_data, version};
|
|||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use ansi_term::Colour;
|
use ansi_term::Colour;
|
||||||
use sync::{NetworkConfiguration, validate_node_url, self};
|
use sync::{NetworkConfiguration, validate_node_url, self};
|
||||||
use ethstore::ethkey::{Secret, Public};
|
use ethkey::{Secret, Public};
|
||||||
use ethcore::client::{VMType};
|
use ethcore::client::{VMType};
|
||||||
use ethcore::miner::{stratum, MinerOptions};
|
use ethcore::miner::{stratum, MinerOptions};
|
||||||
use ethcore::snapshot::SnapshotConfiguration;
|
use ethcore::snapshot::SnapshotConfiguration;
|
||||||
@ -40,7 +40,7 @@ use num_cpus;
|
|||||||
use rpc::{IpcConfiguration, HttpConfiguration, WsConfiguration};
|
use rpc::{IpcConfiguration, HttpConfiguration, WsConfiguration};
|
||||||
use parity_rpc::NetworkSettings;
|
use parity_rpc::NetworkSettings;
|
||||||
use cache::CacheConfig;
|
use cache::CacheConfig;
|
||||||
use helpers::{to_duration, to_mode, to_block_id, to_u256, to_pending_set, to_price, geth_ipc_path, parity_ipc_path, to_bootnodes, to_addresses, to_address, to_queue_strategy, to_queue_penalization, passwords_from_files};
|
use helpers::{to_duration, to_mode, to_block_id, to_u256, to_pending_set, to_price, geth_ipc_path, parity_ipc_path, to_bootnodes, to_addresses, to_address, to_queue_strategy, to_queue_penalization};
|
||||||
use dir::helpers::{replace_home, replace_home_and_local};
|
use dir::helpers::{replace_home, replace_home_and_local};
|
||||||
use params::{ResealPolicy, AccountsConfig, GasPricerConfig, MinerExtras, SpecType};
|
use params::{ResealPolicy, AccountsConfig, GasPricerConfig, MinerExtras, SpecType};
|
||||||
use ethcore_logger::Config as LogConfig;
|
use ethcore_logger::Config as LogConfig;
|
||||||
@ -442,6 +442,7 @@ impl Configuration {
|
|||||||
gas_range_target: (floor, ceil),
|
gas_range_target: (floor, ceil),
|
||||||
engine_signer: self.engine_signer()?,
|
engine_signer: self.engine_signer()?,
|
||||||
work_notify: self.work_notify(),
|
work_notify: self.work_notify(),
|
||||||
|
local_accounts: HashSet::from_iter(to_addresses(&self.args.arg_tx_queue_locals)?.into_iter()),
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(extras)
|
Ok(extras)
|
||||||
@ -579,7 +580,6 @@ impl Configuration {
|
|||||||
infinite_pending_block: self.args.flag_infinite_pending_block,
|
infinite_pending_block: self.args.flag_infinite_pending_block,
|
||||||
|
|
||||||
tx_queue_penalization: to_queue_penalization(self.args.arg_tx_time_limit)?,
|
tx_queue_penalization: to_queue_penalization(self.args.arg_tx_time_limit)?,
|
||||||
tx_queue_locals: HashSet::from_iter(to_addresses(&self.args.arg_tx_queue_locals)?.into_iter()),
|
|
||||||
tx_queue_strategy: to_queue_strategy(&self.args.arg_tx_queue_strategy)?,
|
tx_queue_strategy: to_queue_strategy(&self.args.arg_tx_queue_strategy)?,
|
||||||
tx_queue_no_unfamiliar_locals: self.args.flag_tx_queue_no_unfamiliar_locals,
|
tx_queue_no_unfamiliar_locals: self.args.flag_tx_queue_no_unfamiliar_locals,
|
||||||
refuse_service_transactions: self.args.flag_refuse_service_transactions,
|
refuse_service_transactions: self.args.flag_refuse_service_transactions,
|
||||||
@ -916,20 +916,12 @@ impl Configuration {
|
|||||||
let provider_conf = ProviderConfig {
|
let provider_conf = ProviderConfig {
|
||||||
validator_accounts: to_addresses(&self.args.arg_private_validators)?,
|
validator_accounts: to_addresses(&self.args.arg_private_validators)?,
|
||||||
signer_account: self.args.arg_private_signer.clone().and_then(|account| to_address(Some(account)).ok()),
|
signer_account: self.args.arg_private_signer.clone().and_then(|account| to_address(Some(account)).ok()),
|
||||||
passwords: match self.args.arg_private_passwords.clone() {
|
|
||||||
Some(file) => passwords_from_files(&vec![file].as_slice())?,
|
|
||||||
None => Vec::new(),
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let encryptor_conf = EncryptorConfig {
|
let encryptor_conf = EncryptorConfig {
|
||||||
base_url: self.args.arg_private_sstore_url.clone(),
|
base_url: self.args.arg_private_sstore_url.clone(),
|
||||||
threshold: self.args.arg_private_sstore_threshold.unwrap_or(0),
|
threshold: self.args.arg_private_sstore_threshold.unwrap_or(0),
|
||||||
key_server_account: self.args.arg_private_account.clone().and_then(|account| to_address(Some(account)).ok()),
|
key_server_account: self.args.arg_private_account.clone().and_then(|account| to_address(Some(account)).ok()),
|
||||||
passwords: match self.args.arg_private_passwords.clone() {
|
|
||||||
Some(file) => passwords_from_files(&vec![file].as_slice())?,
|
|
||||||
None => Vec::new(),
|
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok((provider_conf, encryptor_conf, self.args.flag_private_enabled))
|
Ok((provider_conf, encryptor_conf, self.args.flag_private_enabled))
|
||||||
@ -1070,6 +1062,7 @@ impl Configuration {
|
|||||||
match self.args.arg_secretstore_secret {
|
match self.args.arg_secretstore_secret {
|
||||||
Some(ref s) if s.len() == 64 => Ok(Some(NodeSecretKey::Plain(s.parse()
|
Some(ref s) if s.len() == 64 => Ok(Some(NodeSecretKey::Plain(s.parse()
|
||||||
.map_err(|e| format!("Invalid secret store secret: {}. Error: {:?}", s, e))?))),
|
.map_err(|e| format!("Invalid secret store secret: {}. Error: {:?}", s, e))?))),
|
||||||
|
#[cfg(feature = "accounts")]
|
||||||
Some(ref s) if s.len() == 40 => Ok(Some(NodeSecretKey::KeyStore(s.parse()
|
Some(ref s) if s.len() == 40 => Ok(Some(NodeSecretKey::KeyStore(s.parse()
|
||||||
.map_err(|e| format!("Invalid secret store secret address: {}. Error: {:?}", s, e))?))),
|
.map_err(|e| format!("Invalid secret store secret address: {}. Error: {:?}", s, e))?))),
|
||||||
Some(_) => Err(format!("Invalid secret store secret. Must be either existing account address, or hex-encoded private key")),
|
Some(_) => Err(format!("Invalid secret store secret. Must be either existing account address, or hex-encoded private key")),
|
||||||
|
@ -43,7 +43,6 @@ extern crate toml;
|
|||||||
extern crate blooms_db;
|
extern crate blooms_db;
|
||||||
extern crate cli_signer;
|
extern crate cli_signer;
|
||||||
extern crate common_types as types;
|
extern crate common_types as types;
|
||||||
extern crate parity_bytes as bytes;
|
|
||||||
extern crate ethcore;
|
extern crate ethcore;
|
||||||
extern crate ethcore_call_contract as call_contract;
|
extern crate ethcore_call_contract as call_contract;
|
||||||
extern crate ethcore_db;
|
extern crate ethcore_db;
|
||||||
@ -56,26 +55,30 @@ extern crate ethcore_private_tx;
|
|||||||
extern crate ethcore_service;
|
extern crate ethcore_service;
|
||||||
extern crate ethcore_sync as sync;
|
extern crate ethcore_sync as sync;
|
||||||
extern crate ethereum_types;
|
extern crate ethereum_types;
|
||||||
extern crate ethstore;
|
|
||||||
extern crate ethkey;
|
extern crate ethkey;
|
||||||
|
extern crate ethstore;
|
||||||
|
extern crate journaldb;
|
||||||
|
extern crate keccak_hash as hash;
|
||||||
extern crate kvdb;
|
extern crate kvdb;
|
||||||
|
extern crate node_filter;
|
||||||
|
extern crate parity_bytes as bytes;
|
||||||
extern crate parity_hash_fetch as hash_fetch;
|
extern crate parity_hash_fetch as hash_fetch;
|
||||||
extern crate parity_ipfs_api;
|
extern crate parity_ipfs_api;
|
||||||
extern crate parity_local_store as local_store;
|
extern crate parity_local_store as local_store;
|
||||||
extern crate parity_runtime;
|
extern crate parity_path as path;
|
||||||
extern crate parity_rpc;
|
extern crate parity_rpc;
|
||||||
|
extern crate parity_runtime;
|
||||||
extern crate parity_updater as updater;
|
extern crate parity_updater as updater;
|
||||||
extern crate parity_version;
|
extern crate parity_version;
|
||||||
extern crate parity_whisper;
|
extern crate parity_whisper;
|
||||||
extern crate parity_path as path;
|
|
||||||
extern crate node_filter;
|
|
||||||
extern crate keccak_hash as hash;
|
|
||||||
extern crate journaldb;
|
|
||||||
extern crate registrar;
|
extern crate registrar;
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate log as rlog;
|
extern crate log as rlog;
|
||||||
|
|
||||||
|
#[cfg(feature = "ethcore-accounts")]
|
||||||
|
extern crate ethcore_accounts as accounts;
|
||||||
|
|
||||||
#[cfg(feature = "secretstore")]
|
#[cfg(feature = "secretstore")]
|
||||||
extern crate ethcore_secretstore;
|
extern crate ethcore_secretstore;
|
||||||
|
|
||||||
@ -91,6 +94,7 @@ extern crate tempdir;
|
|||||||
extern crate lazy_static;
|
extern crate lazy_static;
|
||||||
|
|
||||||
mod account;
|
mod account;
|
||||||
|
mod account_utils;
|
||||||
mod blockchain;
|
mod blockchain;
|
||||||
mod cache;
|
mod cache;
|
||||||
mod cli;
|
mod cli;
|
||||||
|
@ -14,9 +14,10 @@
|
|||||||
// You should have received a copy of the GNU General Public License
|
// You should have received a copy of the GNU General Public License
|
||||||
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
use std::collections::HashSet;
|
||||||
|
use std::time::Duration;
|
||||||
use std::{str, fs, fmt};
|
use std::{str, fs, fmt};
|
||||||
use std::num::NonZeroU32;
|
use std::num::NonZeroU32;
|
||||||
use std::time::Duration;
|
|
||||||
|
|
||||||
use ethcore::client::Mode;
|
use ethcore::client::Mode;
|
||||||
use ethcore::ethereum;
|
use ethcore::ethereum;
|
||||||
@ -283,6 +284,7 @@ pub struct MinerExtras {
|
|||||||
pub extra_data: Vec<u8>,
|
pub extra_data: Vec<u8>,
|
||||||
pub gas_range_target: (U256, U256),
|
pub gas_range_target: (U256, U256),
|
||||||
pub work_notify: Vec<String>,
|
pub work_notify: Vec<String>,
|
||||||
|
pub local_accounts: HashSet<Address>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for MinerExtras {
|
impl Default for MinerExtras {
|
||||||
@ -293,6 +295,7 @@ impl Default for MinerExtras {
|
|||||||
extra_data: version_data(),
|
extra_data: version_data(),
|
||||||
gas_range_target: (8_000_000.into(), 10_000_000.into()),
|
gas_range_target: (8_000_000.into(), 10_000_000.into()),
|
||||||
work_notify: Default::default(),
|
work_notify: Default::default(),
|
||||||
|
local_accounts: Default::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -14,9 +14,9 @@
|
|||||||
// You should have received a copy of the GNU General Public License
|
// You should have received a copy of the GNU General Public License
|
||||||
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
use ethstore::{PresaleWallet, EthStore};
|
|
||||||
use ethstore::accounts_dir::RootDiskDirectory;
|
use ethkey::Password;
|
||||||
use ethcore::account_provider::{AccountProvider, AccountProviderSettings};
|
use ethstore::PresaleWallet;
|
||||||
use helpers::{password_prompt, password_from_file};
|
use helpers::{password_prompt, password_from_file};
|
||||||
use params::SpecType;
|
use params::SpecType;
|
||||||
use std::num::NonZeroU32;
|
use std::num::NonZeroU32;
|
||||||
@ -31,16 +31,29 @@ pub struct ImportWallet {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn execute(cmd: ImportWallet) -> Result<String, String> {
|
pub fn execute(cmd: ImportWallet) -> Result<String, String> {
|
||||||
let password = match cmd.password_file {
|
let password = match cmd.password_file.clone() {
|
||||||
Some(file) => password_from_file(file)?,
|
Some(file) => password_from_file(file)?,
|
||||||
None => password_prompt()?,
|
None => password_prompt()?,
|
||||||
};
|
};
|
||||||
|
|
||||||
let dir = Box::new(RootDiskDirectory::create(cmd.path).unwrap());
|
let wallet = PresaleWallet::open(cmd.wallet_path.clone()).map_err(|_| "Unable to open presale wallet.")?;
|
||||||
let secret_store = Box::new(EthStore::open_with_iterations(dir, cmd.iterations).unwrap());
|
|
||||||
let acc_provider = AccountProvider::new(secret_store, AccountProviderSettings::default());
|
|
||||||
let wallet = PresaleWallet::open(cmd.wallet_path).map_err(|_| "Unable to open presale wallet.")?;
|
|
||||||
let kp = wallet.decrypt(&password).map_err(|_| "Invalid password.")?;
|
let kp = wallet.decrypt(&password).map_err(|_| "Invalid password.")?;
|
||||||
let address = acc_provider.insert_account(kp.secret().clone(), &password).unwrap();
|
let address = kp.address();
|
||||||
|
import_account(&cmd, kp, password);
|
||||||
Ok(format!("{:?}", address))
|
Ok(format!("{:?}", address))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "accounts")]
|
||||||
|
pub fn import_account(cmd: &ImportWallet, kp: ethkey::KeyPair, password: Password) {
|
||||||
|
use accounts::{AccountProvider, AccountProviderSettings};
|
||||||
|
use ethstore::EthStore;
|
||||||
|
use ethstore::accounts_dir::RootDiskDirectory;
|
||||||
|
|
||||||
|
let dir = Box::new(RootDiskDirectory::create(cmd.path.clone()).unwrap());
|
||||||
|
let secret_store = Box::new(EthStore::open_with_iterations(dir, cmd.iterations).unwrap());
|
||||||
|
let acc_provider = AccountProvider::new(secret_store, AccountProviderSettings::default());
|
||||||
|
acc_provider.insert_account(kp.secret().clone(), &password).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "accounts"))]
|
||||||
|
pub fn import_account(_cmd: &ImportWallet, _kp: ethkey::KeyPair, _password: Password) {}
|
||||||
|
@ -21,7 +21,7 @@ use std::sync::{Arc, Weak};
|
|||||||
|
|
||||||
pub use parity_rpc::signer::SignerService;
|
pub use parity_rpc::signer::SignerService;
|
||||||
|
|
||||||
use ethcore::account_provider::AccountProvider;
|
use account_utils::{self, AccountProvider};
|
||||||
use ethcore::client::Client;
|
use ethcore::client::Client;
|
||||||
use ethcore::miner::Miner;
|
use ethcore::miner::Miner;
|
||||||
use ethcore::snapshot::SnapshotService;
|
use ethcore::snapshot::SnapshotService;
|
||||||
@ -197,6 +197,26 @@ fn to_modules(apis: &HashSet<Api>) -> BTreeMap<String, String> {
|
|||||||
modules
|
modules
|
||||||
}
|
}
|
||||||
|
|
||||||
|
macro_rules! add_signing_methods {
|
||||||
|
($namespace:ident, $handler:expr, $deps:expr, $dispatch:expr) => {{
|
||||||
|
let deps = &$deps;
|
||||||
|
let (dispatcher, accounts) = $dispatch;
|
||||||
|
if deps.signer_service.is_enabled() {
|
||||||
|
$handler.extend_with($namespace::to_delegate(SigningQueueClient::new(
|
||||||
|
&deps.signer_service,
|
||||||
|
dispatcher.clone(),
|
||||||
|
deps.executor.clone(),
|
||||||
|
accounts,
|
||||||
|
)))
|
||||||
|
} else {
|
||||||
|
$handler.extend_with($namespace::to_delegate(SigningUnsafeClient::new(
|
||||||
|
accounts,
|
||||||
|
dispatcher.clone(),
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
/// RPC dependencies can be used to initialize RPC endpoints from APIs.
|
/// RPC dependencies can be used to initialize RPC endpoints from APIs.
|
||||||
pub trait Dependencies {
|
pub trait Dependencies {
|
||||||
type Notifier: ActivityNotifier;
|
type Notifier: ActivityNotifier;
|
||||||
@ -217,7 +237,7 @@ pub struct FullDependencies {
|
|||||||
pub snapshot: Arc<SnapshotService>,
|
pub snapshot: Arc<SnapshotService>,
|
||||||
pub sync: Arc<SyncProvider>,
|
pub sync: Arc<SyncProvider>,
|
||||||
pub net: Arc<ManageNetwork>,
|
pub net: Arc<ManageNetwork>,
|
||||||
pub secret_store: Arc<AccountProvider>,
|
pub accounts: Arc<AccountProvider>,
|
||||||
pub private_tx_service: Option<Arc<PrivateTxService>>,
|
pub private_tx_service: Option<Arc<PrivateTxService>>,
|
||||||
pub miner: Arc<Miner>,
|
pub miner: Arc<Miner>,
|
||||||
pub external_miner: Arc<ExternalMiner>,
|
pub external_miner: Arc<ExternalMiner>,
|
||||||
@ -247,31 +267,6 @@ impl FullDependencies {
|
|||||||
{
|
{
|
||||||
use parity_rpc::v1::*;
|
use parity_rpc::v1::*;
|
||||||
|
|
||||||
macro_rules! add_signing_methods {
|
|
||||||
($namespace:ident, $handler:expr, $deps:expr, $nonces:expr) => {{
|
|
||||||
let deps = &$deps;
|
|
||||||
let dispatcher = FullDispatcher::new(
|
|
||||||
deps.client.clone(),
|
|
||||||
deps.miner.clone(),
|
|
||||||
$nonces,
|
|
||||||
deps.gas_price_percentile,
|
|
||||||
);
|
|
||||||
if deps.signer_service.is_enabled() {
|
|
||||||
$handler.extend_with($namespace::to_delegate(SigningQueueClient::new(
|
|
||||||
&deps.signer_service,
|
|
||||||
dispatcher,
|
|
||||||
deps.executor.clone(),
|
|
||||||
&deps.secret_store,
|
|
||||||
)))
|
|
||||||
} else {
|
|
||||||
$handler.extend_with($namespace::to_delegate(SigningUnsafeClient::new(
|
|
||||||
&deps.secret_store,
|
|
||||||
dispatcher,
|
|
||||||
)))
|
|
||||||
}
|
|
||||||
}};
|
|
||||||
}
|
|
||||||
|
|
||||||
let nonces = Arc::new(Mutex::new(dispatch::Reservations::new(
|
let nonces = Arc::new(Mutex::new(dispatch::Reservations::new(
|
||||||
self.executor.clone(),
|
self.executor.clone(),
|
||||||
)));
|
)));
|
||||||
@ -281,6 +276,9 @@ impl FullDependencies {
|
|||||||
nonces.clone(),
|
nonces.clone(),
|
||||||
self.gas_price_percentile,
|
self.gas_price_percentile,
|
||||||
);
|
);
|
||||||
|
let account_signer = Arc::new(dispatch::Signer::new(self.accounts.clone())) as _;
|
||||||
|
let accounts = account_utils::accounts_list(self.accounts.clone());
|
||||||
|
|
||||||
for api in apis {
|
for api in apis {
|
||||||
match *api {
|
match *api {
|
||||||
Api::Debug => {
|
Api::Debug => {
|
||||||
@ -297,7 +295,7 @@ impl FullDependencies {
|
|||||||
&self.client,
|
&self.client,
|
||||||
&self.snapshot,
|
&self.snapshot,
|
||||||
&self.sync,
|
&self.sync,
|
||||||
&self.secret_store,
|
&accounts,
|
||||||
&self.miner,
|
&self.miner,
|
||||||
&self.external_miner,
|
&self.external_miner,
|
||||||
EthClientOptions {
|
EthClientOptions {
|
||||||
@ -319,7 +317,7 @@ impl FullDependencies {
|
|||||||
);
|
);
|
||||||
handler.extend_with(filter_client.to_delegate());
|
handler.extend_with(filter_client.to_delegate());
|
||||||
|
|
||||||
add_signing_methods!(EthSigning, handler, self, nonces.clone());
|
add_signing_methods!(EthSigning, handler, self, (&dispatcher, &account_signer));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Api::EthPubSub => {
|
Api::EthPubSub => {
|
||||||
@ -341,9 +339,10 @@ impl FullDependencies {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Api::Personal => {
|
Api::Personal => {
|
||||||
|
#[cfg(feature = "accounts")]
|
||||||
handler.extend_with(
|
handler.extend_with(
|
||||||
PersonalClient::new(
|
PersonalClient::new(
|
||||||
&self.secret_store,
|
&self.accounts,
|
||||||
dispatcher.clone(),
|
dispatcher.clone(),
|
||||||
self.geth_compatibility,
|
self.geth_compatibility,
|
||||||
self.experimental_rpcs,
|
self.experimental_rpcs,
|
||||||
@ -353,7 +352,7 @@ impl FullDependencies {
|
|||||||
Api::Signer => {
|
Api::Signer => {
|
||||||
handler.extend_with(
|
handler.extend_with(
|
||||||
SignerClient::new(
|
SignerClient::new(
|
||||||
&self.secret_store,
|
account_signer.clone(),
|
||||||
dispatcher.clone(),
|
dispatcher.clone(),
|
||||||
&self.signer_service,
|
&self.signer_service,
|
||||||
self.executor.clone(),
|
self.executor.clone(),
|
||||||
@ -372,7 +371,6 @@ impl FullDependencies {
|
|||||||
self.sync.clone(),
|
self.sync.clone(),
|
||||||
self.updater.clone(),
|
self.updater.clone(),
|
||||||
self.net_service.clone(),
|
self.net_service.clone(),
|
||||||
self.secret_store.clone(),
|
|
||||||
self.logger.clone(),
|
self.logger.clone(),
|
||||||
self.settings.clone(),
|
self.settings.clone(),
|
||||||
signer,
|
signer,
|
||||||
@ -380,9 +378,11 @@ impl FullDependencies {
|
|||||||
self.snapshot.clone().into(),
|
self.snapshot.clone().into(),
|
||||||
).to_delegate(),
|
).to_delegate(),
|
||||||
);
|
);
|
||||||
|
#[cfg(feature = "accounts")]
|
||||||
|
handler.extend_with(ParityAccountsInfo::to_delegate(ParityAccountsClient::new(&self.accounts)));
|
||||||
|
|
||||||
if !for_generic_pubsub {
|
if !for_generic_pubsub {
|
||||||
add_signing_methods!(ParitySigning, handler, self, nonces.clone());
|
add_signing_methods!(ParitySigning, handler, self, (&dispatcher, &account_signer));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Api::ParityPubSub => {
|
Api::ParityPubSub => {
|
||||||
@ -398,10 +398,11 @@ impl FullDependencies {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Api::ParityAccounts => {
|
Api::ParityAccounts => {
|
||||||
handler
|
#[cfg(feature = "accounts")]
|
||||||
.extend_with(ParityAccountsClient::new(&self.secret_store).to_delegate());
|
handler.extend_with(ParityAccounts::to_delegate(ParityAccountsClient::new(&self.accounts)));
|
||||||
}
|
}
|
||||||
Api::ParitySet => handler.extend_with(
|
Api::ParitySet => {
|
||||||
|
handler.extend_with(
|
||||||
ParitySetClient::new(
|
ParitySetClient::new(
|
||||||
&self.client,
|
&self.client,
|
||||||
&self.miner,
|
&self.miner,
|
||||||
@ -409,14 +410,23 @@ impl FullDependencies {
|
|||||||
&self.net_service,
|
&self.net_service,
|
||||||
self.fetch.clone(),
|
self.fetch.clone(),
|
||||||
).to_delegate(),
|
).to_delegate(),
|
||||||
),
|
);
|
||||||
|
#[cfg(feature = "accounts")]
|
||||||
|
handler.extend_with(
|
||||||
|
ParitySetAccountsClient::new(
|
||||||
|
&self.accounts,
|
||||||
|
&self.miner,
|
||||||
|
).to_delegate(),
|
||||||
|
);
|
||||||
|
}
|
||||||
Api::Traces => handler.extend_with(TracesClient::new(&self.client).to_delegate()),
|
Api::Traces => handler.extend_with(TracesClient::new(&self.client).to_delegate()),
|
||||||
Api::Rpc => {
|
Api::Rpc => {
|
||||||
let modules = to_modules(&apis);
|
let modules = to_modules(&apis);
|
||||||
handler.extend_with(RpcClient::new(modules).to_delegate());
|
handler.extend_with(RpcClient::new(modules).to_delegate());
|
||||||
}
|
}
|
||||||
Api::SecretStore => {
|
Api::SecretStore => {
|
||||||
handler.extend_with(SecretStoreClient::new(&self.secret_store).to_delegate());
|
#[cfg(feature = "accounts")]
|
||||||
|
handler.extend_with(SecretStoreClient::new(&self.accounts).to_delegate());
|
||||||
}
|
}
|
||||||
Api::Whisper => {
|
Api::Whisper => {
|
||||||
if let Some(ref whisper_rpc) = self.whisper_rpc {
|
if let Some(ref whisper_rpc) = self.whisper_rpc {
|
||||||
@ -475,7 +485,7 @@ pub struct LightDependencies<T> {
|
|||||||
pub client: Arc<T>,
|
pub client: Arc<T>,
|
||||||
pub sync: Arc<LightSync>,
|
pub sync: Arc<LightSync>,
|
||||||
pub net: Arc<ManageNetwork>,
|
pub net: Arc<ManageNetwork>,
|
||||||
pub secret_store: Arc<AccountProvider>,
|
pub accounts: Arc<AccountProvider>,
|
||||||
pub logger: Arc<RotatingLogger>,
|
pub logger: Arc<RotatingLogger>,
|
||||||
pub settings: Arc<NetworkSettings>,
|
pub settings: Arc<NetworkSettings>,
|
||||||
pub on_demand: Arc<::light::on_demand::OnDemand>,
|
pub on_demand: Arc<::light::on_demand::OnDemand>,
|
||||||
@ -512,27 +522,8 @@ impl<C: LightChainClient + 'static> LightDependencies<C> {
|
|||||||
))),
|
))),
|
||||||
self.gas_price_percentile,
|
self.gas_price_percentile,
|
||||||
);
|
);
|
||||||
|
let account_signer = Arc::new(dispatch::Signer::new(self.accounts.clone())) as _;
|
||||||
macro_rules! add_signing_methods {
|
let accounts = account_utils::accounts_list(self.accounts.clone());
|
||||||
($namespace:ident, $handler:expr, $deps:expr) => {{
|
|
||||||
let deps = &$deps;
|
|
||||||
let dispatcher = dispatcher.clone();
|
|
||||||
let secret_store = deps.secret_store.clone();
|
|
||||||
if deps.signer_service.is_enabled() {
|
|
||||||
$handler.extend_with($namespace::to_delegate(SigningQueueClient::new(
|
|
||||||
&deps.signer_service,
|
|
||||||
dispatcher,
|
|
||||||
deps.executor.clone(),
|
|
||||||
&secret_store,
|
|
||||||
)))
|
|
||||||
} else {
|
|
||||||
$handler.extend_with($namespace::to_delegate(SigningUnsafeClient::new(
|
|
||||||
&secret_store,
|
|
||||||
dispatcher,
|
|
||||||
)))
|
|
||||||
}
|
|
||||||
}};
|
|
||||||
}
|
|
||||||
|
|
||||||
for api in apis {
|
for api in apis {
|
||||||
match *api {
|
match *api {
|
||||||
@ -551,7 +542,7 @@ impl<C: LightChainClient + 'static> LightDependencies<C> {
|
|||||||
self.client.clone(),
|
self.client.clone(),
|
||||||
self.on_demand.clone(),
|
self.on_demand.clone(),
|
||||||
self.transaction_queue.clone(),
|
self.transaction_queue.clone(),
|
||||||
self.secret_store.clone(),
|
accounts.clone(),
|
||||||
self.cache.clone(),
|
self.cache.clone(),
|
||||||
self.gas_price_percentile,
|
self.gas_price_percentile,
|
||||||
self.poll_lifetime,
|
self.poll_lifetime,
|
||||||
@ -560,7 +551,7 @@ impl<C: LightChainClient + 'static> LightDependencies<C> {
|
|||||||
|
|
||||||
if !for_generic_pubsub {
|
if !for_generic_pubsub {
|
||||||
handler.extend_with(EthFilter::to_delegate(client));
|
handler.extend_with(EthFilter::to_delegate(client));
|
||||||
add_signing_methods!(EthSigning, handler, self);
|
add_signing_methods!(EthSigning, handler, self, (&dispatcher, &account_signer));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Api::EthPubSub => {
|
Api::EthPubSub => {
|
||||||
@ -584,9 +575,10 @@ impl<C: LightChainClient + 'static> LightDependencies<C> {
|
|||||||
handler.extend_with(EthPubSub::to_delegate(client));
|
handler.extend_with(EthPubSub::to_delegate(client));
|
||||||
}
|
}
|
||||||
Api::Personal => {
|
Api::Personal => {
|
||||||
|
#[cfg(feature = "accounts")]
|
||||||
handler.extend_with(
|
handler.extend_with(
|
||||||
PersonalClient::new(
|
PersonalClient::new(
|
||||||
&self.secret_store,
|
&self.accounts,
|
||||||
dispatcher.clone(),
|
dispatcher.clone(),
|
||||||
self.geth_compatibility,
|
self.geth_compatibility,
|
||||||
self.experimental_rpcs,
|
self.experimental_rpcs,
|
||||||
@ -596,7 +588,7 @@ impl<C: LightChainClient + 'static> LightDependencies<C> {
|
|||||||
Api::Signer => {
|
Api::Signer => {
|
||||||
handler.extend_with(
|
handler.extend_with(
|
||||||
SignerClient::new(
|
SignerClient::new(
|
||||||
&self.secret_store,
|
account_signer.clone(),
|
||||||
dispatcher.clone(),
|
dispatcher.clone(),
|
||||||
&self.signer_service,
|
&self.signer_service,
|
||||||
self.executor.clone(),
|
self.executor.clone(),
|
||||||
@ -611,7 +603,6 @@ impl<C: LightChainClient + 'static> LightDependencies<C> {
|
|||||||
handler.extend_with(
|
handler.extend_with(
|
||||||
light::ParityClient::new(
|
light::ParityClient::new(
|
||||||
Arc::new(dispatcher.clone()),
|
Arc::new(dispatcher.clone()),
|
||||||
self.secret_store.clone(),
|
|
||||||
self.logger.clone(),
|
self.logger.clone(),
|
||||||
self.settings.clone(),
|
self.settings.clone(),
|
||||||
signer,
|
signer,
|
||||||
@ -619,9 +610,13 @@ impl<C: LightChainClient + 'static> LightDependencies<C> {
|
|||||||
self.gas_price_percentile,
|
self.gas_price_percentile,
|
||||||
).to_delegate(),
|
).to_delegate(),
|
||||||
);
|
);
|
||||||
|
#[cfg(feature = "accounts")]
|
||||||
|
handler.extend_with(
|
||||||
|
ParityAccountsInfo::to_delegate(ParityAccountsClient::new(&self.accounts))
|
||||||
|
);
|
||||||
|
|
||||||
if !for_generic_pubsub {
|
if !for_generic_pubsub {
|
||||||
add_signing_methods!(ParitySigning, handler, self);
|
add_signing_methods!(ParitySigning, handler, self, (&dispatcher, &account_signer));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Api::ParityPubSub => {
|
Api::ParityPubSub => {
|
||||||
@ -637,8 +632,8 @@ impl<C: LightChainClient + 'static> LightDependencies<C> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
Api::ParityAccounts => {
|
Api::ParityAccounts => {
|
||||||
handler
|
#[cfg(feature = "accounts")]
|
||||||
.extend_with(ParityAccountsClient::new(&self.secret_store).to_delegate());
|
handler.extend_with(ParityAccounts::to_delegate(ParityAccountsClient::new(&self.accounts)));
|
||||||
}
|
}
|
||||||
Api::ParitySet => handler.extend_with(
|
Api::ParitySet => handler.extend_with(
|
||||||
light::ParitySetClient::new(self.sync.clone(), self.fetch.clone())
|
light::ParitySetClient::new(self.sync.clone(), self.fetch.clone())
|
||||||
@ -650,7 +645,8 @@ impl<C: LightChainClient + 'static> LightDependencies<C> {
|
|||||||
handler.extend_with(RpcClient::new(modules).to_delegate());
|
handler.extend_with(RpcClient::new(modules).to_delegate());
|
||||||
}
|
}
|
||||||
Api::SecretStore => {
|
Api::SecretStore => {
|
||||||
handler.extend_with(SecretStoreClient::new(&self.secret_store).to_delegate());
|
#[cfg(feature = "accounts")]
|
||||||
|
handler.extend_with(SecretStoreClient::new(&self.accounts).to_delegate());
|
||||||
}
|
}
|
||||||
Api::Whisper => {
|
Api::Whisper => {
|
||||||
if let Some(ref whisper_rpc) = self.whisper_rpc {
|
if let Some(ref whisper_rpc) = self.whisper_rpc {
|
||||||
|
132
parity/run.rs
132
parity/run.rs
@ -22,28 +22,27 @@ use std::thread;
|
|||||||
use ansi_term::Colour;
|
use ansi_term::Colour;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use call_contract::CallContract;
|
use call_contract::CallContract;
|
||||||
use ethcore::account_provider::{AccountProvider, AccountProviderSettings};
|
|
||||||
use ethcore::client::{BlockId, Client, Mode, DatabaseCompactionProfile, VMType, BlockChainClient, BlockInfo};
|
use ethcore::client::{BlockId, Client, Mode, DatabaseCompactionProfile, VMType, BlockChainClient, BlockInfo};
|
||||||
use ethstore::ethkey;
|
use ethcore::miner::{self, stratum, Miner, MinerService, MinerOptions};
|
||||||
use ethcore::miner::{stratum, Miner, MinerService, MinerOptions};
|
|
||||||
use ethcore::snapshot::{self, SnapshotConfiguration};
|
use ethcore::snapshot::{self, SnapshotConfiguration};
|
||||||
use ethcore::spec::{SpecParams, OptimizeFor};
|
use ethcore::spec::{SpecParams, OptimizeFor};
|
||||||
use ethcore::verification::queue::VerifierSettings;
|
use ethcore::verification::queue::VerifierSettings;
|
||||||
use ethcore_logger::{Config as LogConfig, RotatingLogger};
|
use ethcore_logger::{Config as LogConfig, RotatingLogger};
|
||||||
use ethcore_service::ClientService;
|
use ethcore_service::ClientService;
|
||||||
use ethereum_types::Address;
|
use ethereum_types::Address;
|
||||||
use sync::{self, SyncConfig, PrivateTxHandler};
|
|
||||||
use miner::work_notify::WorkPoster;
|
|
||||||
use futures::IntoFuture;
|
use futures::IntoFuture;
|
||||||
use hash_fetch::{self, fetch};
|
use hash_fetch::{self, fetch};
|
||||||
use informant::{Informant, LightNodeInformantData, FullNodeInformantData};
|
use informant::{Informant, LightNodeInformantData, FullNodeInformantData};
|
||||||
use journaldb::Algorithm;
|
use journaldb::Algorithm;
|
||||||
use light::Cache as LightDataCache;
|
use light::Cache as LightDataCache;
|
||||||
use miner::external::ExternalMiner;
|
use miner::external::ExternalMiner;
|
||||||
|
use miner::work_notify::WorkPoster;
|
||||||
use node_filter::NodeFilter;
|
use node_filter::NodeFilter;
|
||||||
use parity_runtime::Runtime;
|
use parity_runtime::Runtime;
|
||||||
use parity_rpc::{Origin, Metadata, NetworkSettings, informant, is_major_importing, PubSubSession, FutureResult,
|
use sync::{self, SyncConfig, PrivateTxHandler};
|
||||||
FutureResponse, FutureOutput};
|
use parity_rpc::{
|
||||||
|
Origin, Metadata, NetworkSettings, informant, is_major_importing, PubSubSession, FutureResult, FutureResponse, FutureOutput
|
||||||
|
};
|
||||||
use updater::{UpdatePolicy, Updater};
|
use updater::{UpdatePolicy, Updater};
|
||||||
use parity_version::version;
|
use parity_version::version;
|
||||||
use ethcore_private_tx::{ProviderConfig, EncryptorConfig, SecretStoreEncryptor};
|
use ethcore_private_tx::{ProviderConfig, EncryptorConfig, SecretStoreEncryptor};
|
||||||
@ -51,8 +50,8 @@ use params::{
|
|||||||
SpecType, Pruning, AccountsConfig, GasPricerConfig, MinerExtras, Switch,
|
SpecType, Pruning, AccountsConfig, GasPricerConfig, MinerExtras, Switch,
|
||||||
tracing_switch_to_bool, fatdb_switch_to_bool, mode_switch_to_bool
|
tracing_switch_to_bool, fatdb_switch_to_bool, mode_switch_to_bool
|
||||||
};
|
};
|
||||||
|
use account_utils;
|
||||||
use helpers::{to_client_config, execute_upgrades, passwords_from_files};
|
use helpers::{to_client_config, execute_upgrades, passwords_from_files};
|
||||||
use upgrade::upgrade_key_location;
|
|
||||||
use dir::{Directories, DatabaseDirectories};
|
use dir::{Directories, DatabaseDirectories};
|
||||||
use cache::CacheConfig;
|
use cache::CacheConfig;
|
||||||
use user_defaults::UserDefaults;
|
use user_defaults::UserDefaults;
|
||||||
@ -65,7 +64,6 @@ use rpc_apis;
|
|||||||
use secretstore;
|
use secretstore;
|
||||||
use signer;
|
use signer;
|
||||||
use db;
|
use db;
|
||||||
use ethkey::Password;
|
|
||||||
|
|
||||||
// how often to take periodic snapshots.
|
// how often to take periodic snapshots.
|
||||||
const SNAPSHOT_PERIOD: u64 = 5000;
|
const SNAPSHOT_PERIOD: u64 = 5000;
|
||||||
@ -77,9 +75,6 @@ const SNAPSHOT_HISTORY: u64 = 100;
|
|||||||
// Light client only.
|
// Light client only.
|
||||||
const GAS_CORPUS_EXPIRATION_MINUTES: u64 = 60 * 6;
|
const GAS_CORPUS_EXPIRATION_MINUTES: u64 = 60 * 6;
|
||||||
|
|
||||||
// Pops along with error messages when a password is missing or invalid.
|
|
||||||
const VERIFY_PASSWORD_HINT: &str = "Make sure valid password is present in files passed using `--password` or in the configuration file.";
|
|
||||||
|
|
||||||
// Full client number of DNS threads
|
// Full client number of DNS threads
|
||||||
const FETCH_FULL_NUM_DNS_THREADS: usize = 4;
|
const FETCH_FULL_NUM_DNS_THREADS: usize = 4;
|
||||||
|
|
||||||
@ -317,7 +312,7 @@ fn execute_light_impl(cmd: RunCmd, logger: Arc<RotatingLogger>) -> Result<Runnin
|
|||||||
let passwords = passwords_from_files(&cmd.acc_conf.password_files)?;
|
let passwords = passwords_from_files(&cmd.acc_conf.password_files)?;
|
||||||
|
|
||||||
// prepare account provider
|
// prepare account provider
|
||||||
let account_provider = Arc::new(prepare_account_provider(&cmd.spec, &cmd.dirs, &spec.data_dir, cmd.acc_conf, &passwords)?);
|
let account_provider = Arc::new(account_utils::prepare_account_provider(&cmd.spec, &cmd.dirs, &spec.data_dir, cmd.acc_conf, &passwords)?);
|
||||||
let rpc_stats = Arc::new(informant::RpcStats::default());
|
let rpc_stats = Arc::new(informant::RpcStats::default());
|
||||||
|
|
||||||
// the dapps server
|
// the dapps server
|
||||||
@ -329,7 +324,7 @@ fn execute_light_impl(cmd: RunCmd, logger: Arc<RotatingLogger>) -> Result<Runnin
|
|||||||
client: client.clone(),
|
client: client.clone(),
|
||||||
sync: light_sync.clone(),
|
sync: light_sync.clone(),
|
||||||
net: light_sync.clone(),
|
net: light_sync.clone(),
|
||||||
secret_store: account_provider,
|
accounts: account_provider,
|
||||||
logger: logger,
|
logger: logger,
|
||||||
settings: Arc::new(cmd.net_settings),
|
settings: Arc::new(cmd.net_settings),
|
||||||
on_demand: on_demand,
|
on_demand: on_demand,
|
||||||
@ -489,7 +484,7 @@ fn execute_impl<Cr, Rr>(cmd: RunCmd, logger: Arc<RotatingLogger>, on_client_rq:
|
|||||||
let passwords = passwords_from_files(&cmd.acc_conf.password_files)?;
|
let passwords = passwords_from_files(&cmd.acc_conf.password_files)?;
|
||||||
|
|
||||||
// prepare account provider
|
// prepare account provider
|
||||||
let account_provider = Arc::new(prepare_account_provider(&cmd.spec, &cmd.dirs, &spec.data_dir, cmd.acc_conf, &passwords)?);
|
let account_provider = Arc::new(account_utils::prepare_account_provider(&cmd.spec, &cmd.dirs, &spec.data_dir, cmd.acc_conf, &passwords)?);
|
||||||
|
|
||||||
// spin up event loop
|
// spin up event loop
|
||||||
let runtime = Runtime::with_default_thread_count();
|
let runtime = Runtime::with_default_thread_count();
|
||||||
@ -503,9 +498,12 @@ fn execute_impl<Cr, Rr>(cmd: RunCmd, logger: Arc<RotatingLogger>, on_client_rq:
|
|||||||
cmd.miner_options,
|
cmd.miner_options,
|
||||||
cmd.gas_pricer_conf.to_gas_pricer(fetch.clone(), runtime.executor()),
|
cmd.gas_pricer_conf.to_gas_pricer(fetch.clone(), runtime.executor()),
|
||||||
&spec,
|
&spec,
|
||||||
Some(account_provider.clone()),
|
(
|
||||||
|
cmd.miner_extras.local_accounts,
|
||||||
|
account_utils::miner_local_accounts(account_provider.clone()),
|
||||||
|
)
|
||||||
));
|
));
|
||||||
miner.set_author(cmd.miner_extras.author, None).expect("Fails only if password is Some; password is None; qed");
|
miner.set_author(miner::Author::External(cmd.miner_extras.author));
|
||||||
miner.set_gas_range_target(cmd.miner_extras.gas_range_target);
|
miner.set_gas_range_target(cmd.miner_extras.gas_range_target);
|
||||||
miner.set_extra_data(cmd.miner_extras.extra_data);
|
miner.set_extra_data(cmd.miner_extras.extra_data);
|
||||||
|
|
||||||
@ -517,19 +515,8 @@ fn execute_impl<Cr, Rr>(cmd: RunCmd, logger: Arc<RotatingLogger>, on_client_rq:
|
|||||||
|
|
||||||
let engine_signer = cmd.miner_extras.engine_signer;
|
let engine_signer = cmd.miner_extras.engine_signer;
|
||||||
if engine_signer != Default::default() {
|
if engine_signer != Default::default() {
|
||||||
// Check if engine signer exists
|
if let Some(author) = account_utils::miner_author(&cmd.spec, &cmd.dirs, &account_provider, engine_signer, &passwords)? {
|
||||||
if !account_provider.has_account(engine_signer) {
|
miner.set_author(author);
|
||||||
return Err(format!("Consensus signer account not found for the current chain. {}", build_create_account_hint(&cmd.spec, &cmd.dirs.keys)));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if any passwords have been read from the password file(s)
|
|
||||||
if passwords.is_empty() {
|
|
||||||
return Err(format!("No password found for the consensus signer {}. {}", engine_signer, VERIFY_PASSWORD_HINT));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Attempt to sign in the engine signer.
|
|
||||||
if !passwords.iter().any(|p| miner.set_author(engine_signer, Some(p.to_owned())).is_ok()) {
|
|
||||||
return Err(format!("No valid password for the consensus signer {}. {}", engine_signer, VERIFY_PASSWORD_HINT));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -572,6 +559,8 @@ fn execute_impl<Cr, Rr>(cmd: RunCmd, logger: Arc<RotatingLogger>, on_client_rq:
|
|||||||
let client_db = restoration_db_handler.open(&client_path)
|
let client_db = restoration_db_handler.open(&client_path)
|
||||||
.map_err(|e| format!("Failed to open database {:?}", e))?;
|
.map_err(|e| format!("Failed to open database {:?}", e))?;
|
||||||
|
|
||||||
|
let private_tx_signer = account_utils::private_tx_signer(account_provider.clone(), &passwords)?;
|
||||||
|
|
||||||
// create client service.
|
// create client service.
|
||||||
let service = ClientService::start(
|
let service = ClientService::start(
|
||||||
client_config,
|
client_config,
|
||||||
@ -581,8 +570,8 @@ fn execute_impl<Cr, Rr>(cmd: RunCmd, logger: Arc<RotatingLogger>, on_client_rq:
|
|||||||
restoration_db_handler,
|
restoration_db_handler,
|
||||||
&cmd.dirs.ipc_path(),
|
&cmd.dirs.ipc_path(),
|
||||||
miner.clone(),
|
miner.clone(),
|
||||||
account_provider.clone(),
|
private_tx_signer.clone(),
|
||||||
Box::new(SecretStoreEncryptor::new(cmd.private_encryptor_conf.clone(), fetch.clone()).map_err(|e| e.to_string())?),
|
Box::new(SecretStoreEncryptor::new(cmd.private_encryptor_conf.clone(), fetch.clone(), private_tx_signer).map_err(|e| e.to_string())?),
|
||||||
cmd.private_provider_conf,
|
cmd.private_provider_conf,
|
||||||
cmd.private_encryptor_conf,
|
cmd.private_encryptor_conf,
|
||||||
).map_err(|e| format!("Client service error: {:?}", e))?;
|
).map_err(|e| format!("Client service error: {:?}", e))?;
|
||||||
@ -743,7 +732,7 @@ fn execute_impl<Cr, Rr>(cmd: RunCmd, logger: Arc<RotatingLogger>, on_client_rq:
|
|||||||
client: client.clone(),
|
client: client.clone(),
|
||||||
sync: sync_provider.clone(),
|
sync: sync_provider.clone(),
|
||||||
net: manage_network.clone(),
|
net: manage_network.clone(),
|
||||||
secret_store: secret_store,
|
accounts: secret_store,
|
||||||
miner: miner.clone(),
|
miner: miner.clone(),
|
||||||
external_miner: external_miner.clone(),
|
external_miner: external_miner.clone(),
|
||||||
logger: logger.clone(),
|
logger: logger.clone(),
|
||||||
@ -779,7 +768,7 @@ fn execute_impl<Cr, Rr>(cmd: RunCmd, logger: Arc<RotatingLogger>, on_client_rq:
|
|||||||
client: client.clone(),
|
client: client.clone(),
|
||||||
sync: sync_provider.clone(),
|
sync: sync_provider.clone(),
|
||||||
miner: miner.clone(),
|
miner: miner.clone(),
|
||||||
account_provider: account_provider,
|
account_provider,
|
||||||
accounts_passwords: &passwords,
|
accounts_passwords: &passwords,
|
||||||
};
|
};
|
||||||
let secretstore_key_server = secretstore::start(cmd.secretstore_conf.clone(), secretstore_deps, runtime.executor())?;
|
let secretstore_key_server = secretstore::start(cmd.secretstore_conf.clone(), secretstore_deps, runtime.executor())?;
|
||||||
@ -953,80 +942,6 @@ fn print_running_environment(data_dir: &str, dirs: &Directories, db_dirs: &Datab
|
|||||||
info!("DB path {}", Colour::White.bold().paint(db_dirs.db_root_path().to_string_lossy().into_owned()));
|
info!("DB path {}", Colour::White.bold().paint(db_dirs.db_root_path().to_string_lossy().into_owned()));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn prepare_account_provider(spec: &SpecType, dirs: &Directories, data_dir: &str, cfg: AccountsConfig, passwords: &[Password]) -> Result<AccountProvider, String> {
|
|
||||||
use ethstore::EthStore;
|
|
||||||
use ethstore::accounts_dir::RootDiskDirectory;
|
|
||||||
|
|
||||||
let path = dirs.keys_path(data_dir);
|
|
||||||
upgrade_key_location(&dirs.legacy_keys_path(cfg.testnet), &path);
|
|
||||||
let dir = Box::new(RootDiskDirectory::create(&path).map_err(|e| format!("Could not open keys directory: {}", e))?);
|
|
||||||
let account_settings = AccountProviderSettings {
|
|
||||||
enable_hardware_wallets: cfg.enable_hardware_wallets,
|
|
||||||
hardware_wallet_classic_key: spec == &SpecType::Classic,
|
|
||||||
unlock_keep_secret: cfg.enable_fast_unlock,
|
|
||||||
blacklisted_accounts: match *spec {
|
|
||||||
SpecType::Morden | SpecType::Ropsten | SpecType::Kovan | SpecType::Sokol | SpecType::Dev => vec![],
|
|
||||||
_ => vec![
|
|
||||||
"00a329c0648769a73afac7f9381e08fb43dbea72".into()
|
|
||||||
],
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
let ethstore = EthStore::open_with_iterations(dir, cfg.iterations).map_err(|e| format!("Could not open keys directory: {}", e))?;
|
|
||||||
if cfg.refresh_time > 0 {
|
|
||||||
ethstore.set_refresh_time(::std::time::Duration::from_secs(cfg.refresh_time));
|
|
||||||
}
|
|
||||||
let account_provider = AccountProvider::new(
|
|
||||||
Box::new(ethstore),
|
|
||||||
account_settings,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Add development account if running dev chain:
|
|
||||||
if let SpecType::Dev = *spec {
|
|
||||||
insert_dev_account(&account_provider);
|
|
||||||
}
|
|
||||||
|
|
||||||
for a in cfg.unlocked_accounts {
|
|
||||||
// Check if the account exists
|
|
||||||
if !account_provider.has_account(a) {
|
|
||||||
return Err(format!("Account {} not found for the current chain. {}", a, build_create_account_hint(spec, &dirs.keys)));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if any passwords have been read from the password file(s)
|
|
||||||
if passwords.is_empty() {
|
|
||||||
return Err(format!("No password found to unlock account {}. {}", a, VERIFY_PASSWORD_HINT));
|
|
||||||
}
|
|
||||||
|
|
||||||
if !passwords.iter().any(|p| account_provider.unlock_account_permanently(a, (*p).clone()).is_ok()) {
|
|
||||||
return Err(format!("No valid password to unlock account {}. {}", a, VERIFY_PASSWORD_HINT));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(account_provider)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn insert_dev_account(account_provider: &AccountProvider) {
|
|
||||||
let secret: ethkey::Secret = "4d5db4107d237df6a3d58ee5f70ae63d73d7658d4026f2eefd2f204c81682cb7".into();
|
|
||||||
let dev_account = ethkey::KeyPair::from_secret(secret.clone()).expect("Valid secret produces valid key;qed");
|
|
||||||
if !account_provider.has_account(dev_account.address()) {
|
|
||||||
match account_provider.insert_account(secret, &Password::from(String::new())) {
|
|
||||||
Err(e) => warn!("Unable to add development account: {}", e),
|
|
||||||
Ok(address) => {
|
|
||||||
let _ = account_provider.set_account_name(address.clone(), "Development Account".into());
|
|
||||||
let _ = account_provider.set_account_meta(address, ::serde_json::to_string(&(vec![
|
|
||||||
("description", "Never use this account outside of development chain!"),
|
|
||||||
("passwordHint","Password is empty string"),
|
|
||||||
].into_iter().collect::<::std::collections::HashMap<_,_>>())).expect("Serialization of hashmap does not fail."));
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Construct an error `String` with an adaptive hint on how to create an account.
|
|
||||||
fn build_create_account_hint(spec: &SpecType, keys: &str) -> String {
|
|
||||||
format!("You can create an account via RPC, UI or `parity account new --chain {} --keys-path {}`.", spec, keys)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn wait_for_drop<T>(w: Weak<T>) {
|
fn wait_for_drop<T>(w: Weak<T>) {
|
||||||
let sleep_duration = Duration::from_secs(1);
|
let sleep_duration = Duration::from_secs(1);
|
||||||
let warn_timeout = Duration::from_secs(60);
|
let warn_timeout = Duration::from_secs(60);
|
||||||
@ -1050,3 +965,4 @@ fn wait_for_drop<T>(w: Weak<T>) {
|
|||||||
|
|
||||||
warn!("Shutdown timeout reached, exiting uncleanly.");
|
warn!("Shutdown timeout reached, exiting uncleanly.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -16,12 +16,12 @@
|
|||||||
|
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
use account_utils::AccountProvider;
|
||||||
use dir::default_data_path;
|
use dir::default_data_path;
|
||||||
use dir::helpers::replace_home;
|
use dir::helpers::replace_home;
|
||||||
use ethcore::account_provider::AccountProvider;
|
|
||||||
use ethcore::client::Client;
|
use ethcore::client::Client;
|
||||||
use ethcore::miner::Miner;
|
use ethcore::miner::Miner;
|
||||||
use ethkey::{Secret, Public};
|
use ethkey::{Secret, Public, Password};
|
||||||
use sync::SyncProvider;
|
use sync::SyncProvider;
|
||||||
use ethereum_types::Address;
|
use ethereum_types::Address;
|
||||||
use parity_runtime::Executor;
|
use parity_runtime::Executor;
|
||||||
@ -32,6 +32,7 @@ pub enum NodeSecretKey {
|
|||||||
/// Stored as plain text in configuration file.
|
/// Stored as plain text in configuration file.
|
||||||
Plain(Secret),
|
Plain(Secret),
|
||||||
/// Stored as account in key store.
|
/// Stored as account in key store.
|
||||||
|
#[cfg(feature = "accounts")]
|
||||||
KeyStore(Address),
|
KeyStore(Address),
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -141,6 +142,7 @@ mod server {
|
|||||||
let self_secret: Arc<ethcore_secretstore::NodeKeyPair> = match conf.self_secret.take() {
|
let self_secret: Arc<ethcore_secretstore::NodeKeyPair> = match conf.self_secret.take() {
|
||||||
Some(NodeSecretKey::Plain(secret)) => Arc::new(ethcore_secretstore::PlainNodeKeyPair::new(
|
Some(NodeSecretKey::Plain(secret)) => Arc::new(ethcore_secretstore::PlainNodeKeyPair::new(
|
||||||
KeyPair::from_secret(secret).map_err(|e| format!("invalid secret: {}", e))?)),
|
KeyPair::from_secret(secret).map_err(|e| format!("invalid secret: {}", e))?)),
|
||||||
|
#[cfg(feature = "accounts")]
|
||||||
Some(NodeSecretKey::KeyStore(account)) => {
|
Some(NodeSecretKey::KeyStore(account)) => {
|
||||||
// Check if account exists
|
// Check if account exists
|
||||||
if !deps.account_provider.has_account(account.clone()) {
|
if !deps.account_provider.has_account(account.clone()) {
|
||||||
@ -209,7 +211,6 @@ mod server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub use self::server::KeyServer;
|
pub use self::server::KeyServer;
|
||||||
use ethkey::Password;
|
|
||||||
|
|
||||||
impl Default for Configuration {
|
impl Default for Configuration {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
|
@ -21,7 +21,6 @@ use std::path::{Path, PathBuf};
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use hash::keccak;
|
use hash::keccak;
|
||||||
use ethcore::account_provider::AccountProvider;
|
|
||||||
use ethcore::snapshot::{Progress, RestorationStatus, SnapshotConfiguration, SnapshotService as SS};
|
use ethcore::snapshot::{Progress, RestorationStatus, SnapshotConfiguration, SnapshotService as SS};
|
||||||
use ethcore::snapshot::io::{SnapshotReader, PackedReader, PackedWriter};
|
use ethcore::snapshot::io::{SnapshotReader, PackedReader, PackedWriter};
|
||||||
use ethcore::snapshot::service::Service as SnapshotService;
|
use ethcore::snapshot::service::Service as SnapshotService;
|
||||||
@ -199,7 +198,7 @@ impl SnapshotCommand {
|
|||||||
// TODO [ToDr] don't use test miner here
|
// TODO [ToDr] don't use test miner here
|
||||||
// (actually don't require miner at all)
|
// (actually don't require miner at all)
|
||||||
Arc::new(Miner::new_for_tests(&spec, None)),
|
Arc::new(Miner::new_for_tests(&spec, None)),
|
||||||
Arc::new(AccountProvider::transient_provider()),
|
Arc::new(ethcore_private_tx::DummySigner),
|
||||||
Box::new(ethcore_private_tx::NoopEncryptor),
|
Box::new(ethcore_private_tx::NoopEncryptor),
|
||||||
Default::default(),
|
Default::default(),
|
||||||
Default::default(),
|
Default::default(),
|
||||||
|
@ -37,9 +37,7 @@ jsonrpc-pubsub = "10.0.1"
|
|||||||
common-types = { path = "../ethcore/types" }
|
common-types = { path = "../ethcore/types" }
|
||||||
ethash = { path = "../ethash" }
|
ethash = { path = "../ethash" }
|
||||||
ethcore = { path = "../ethcore", features = ["test-helpers"] }
|
ethcore = { path = "../ethcore", features = ["test-helpers"] }
|
||||||
fastmap = { path = "../util/fastmap" }
|
ethcore-accounts = { path = "../accounts", optional = true }
|
||||||
parity-bytes = "0.1"
|
|
||||||
parity-crypto = "0.3.0"
|
|
||||||
ethcore-io = { path = "../util/io" }
|
ethcore-io = { path = "../util/io" }
|
||||||
ethcore-light = { path = "../ethcore/light" }
|
ethcore-light = { path = "../ethcore/light" }
|
||||||
ethcore-logger = { path = "../parity/logger" }
|
ethcore-logger = { path = "../parity/logger" }
|
||||||
@ -47,7 +45,11 @@ ethcore-miner = { path = "../miner" }
|
|||||||
ethcore-private-tx = { path = "../ethcore/private-tx" }
|
ethcore-private-tx = { path = "../ethcore/private-tx" }
|
||||||
ethcore-sync = { path = "../ethcore/sync" }
|
ethcore-sync = { path = "../ethcore/sync" }
|
||||||
ethereum-types = "0.4"
|
ethereum-types = "0.4"
|
||||||
|
fastmap = { path = "../util/fastmap" }
|
||||||
|
parity-bytes = "0.1"
|
||||||
|
parity-crypto = "0.3.0"
|
||||||
|
|
||||||
|
eip-712 = { path = "../util/EIP-712" }
|
||||||
ethjson = { path = "../json" }
|
ethjson = { path = "../json" }
|
||||||
ethkey = { path = "../accounts/ethkey" }
|
ethkey = { path = "../accounts/ethkey" }
|
||||||
ethstore = { path = "../accounts/ethstore" }
|
ethstore = { path = "../accounts/ethstore" }
|
||||||
@ -58,21 +60,18 @@ parity-updater = { path = "../updater" }
|
|||||||
parity-version = { path = "../util/version" }
|
parity-version = { path = "../util/version" }
|
||||||
patricia-trie = "0.3.0"
|
patricia-trie = "0.3.0"
|
||||||
rlp = { version = "0.3.0", features = ["ethereum"] }
|
rlp = { version = "0.3.0", features = ["ethereum"] }
|
||||||
eip-712 = { path = "../util/EIP-712" }
|
|
||||||
stats = { path = "../util/stats" }
|
stats = { path = "../util/stats" }
|
||||||
vm = { path = "../ethcore/vm" }
|
vm = { path = "../ethcore/vm" }
|
||||||
|
|
||||||
[target.'cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))'.dependencies]
|
|
||||||
hardware-wallet = { path = "../accounts/hw" }
|
|
||||||
|
|
||||||
[target.'cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))'.dependencies]
|
|
||||||
fake-hardware-wallet = { path = "../accounts/fake-hardware-wallet" }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
ethcore = { path = "../ethcore", features = ["test-helpers"] }
|
ethcore = { path = "../ethcore", features = ["test-helpers"] }
|
||||||
|
ethcore-accounts = { path = "../accounts" }
|
||||||
ethcore-network = { path = "../util/network" }
|
ethcore-network = { path = "../util/network" }
|
||||||
fake-fetch = { path = "../util/fake-fetch" }
|
fake-fetch = { path = "../util/fake-fetch" }
|
||||||
kvdb-memorydb = "0.1"
|
kvdb-memorydb = "0.1"
|
||||||
macros = { path = "../util/macros" }
|
macros = { path = "../util/macros" }
|
||||||
pretty_assertions = "0.1"
|
pretty_assertions = "0.1"
|
||||||
transaction-pool = "1.13"
|
transaction-pool = "1.13"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
accounts = ["ethcore-accounts"]
|
||||||
|
@ -68,10 +68,8 @@ extern crate rlp;
|
|||||||
extern crate stats;
|
extern crate stats;
|
||||||
extern crate vm;
|
extern crate vm;
|
||||||
|
|
||||||
#[cfg(any(target_os = "linux", target_os = "macos", target_os = "windows"))]
|
#[cfg(any(test, feature = "ethcore-accounts"))]
|
||||||
extern crate hardware_wallet;
|
extern crate ethcore_accounts as accounts;
|
||||||
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
|
|
||||||
extern crate fake_hardware_wallet as hardware_wallet;
|
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate log;
|
extern crate log;
|
||||||
|
111
rpc/src/v1/helpers/deprecated.rs
Normal file
111
rpc/src/v1/helpers/deprecated.rs
Normal file
@ -0,0 +1,111 @@
|
|||||||
|
// 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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
//! Deprecation notice for RPC methods.
|
||||||
|
//!
|
||||||
|
//! Displays a warning but avoids spamming the log.
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
|
||||||
|
use parking_lot::RwLock;
|
||||||
|
|
||||||
|
/// Deprecation messages
|
||||||
|
pub mod msgs {
|
||||||
|
pub const ACCOUNTS: Option<&str> = Some("Account management is being phased out see #9997 for alternatives.");
|
||||||
|
}
|
||||||
|
|
||||||
|
type MethodName = &'static str;
|
||||||
|
|
||||||
|
const PRINT_INTERVAL: Duration = Duration::from_secs(60);
|
||||||
|
|
||||||
|
/// Displays a deprecation notice without spamming the log.
|
||||||
|
pub struct DeprecationNotice<T = fn() -> Instant> {
|
||||||
|
now: T,
|
||||||
|
next_warning_at: RwLock<HashMap<String, Instant>>,
|
||||||
|
printer: Box<Fn(MethodName, Option<&str>) + Send + Sync>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for DeprecationNotice {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new(Instant::now, |method, more| {
|
||||||
|
let more = more.map(|x| format!(": {}", x)).unwrap_or_else(|| ".".into());
|
||||||
|
warn!(target: "rpc", "{} is deprecated and will be removed in future versions{}", method, more);
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<N: Fn() -> Instant> DeprecationNotice<N> {
|
||||||
|
/// Create new deprecation notice printer with custom display and interval.
|
||||||
|
pub fn new<T>(now: N, printer: T) -> Self where
|
||||||
|
T: Fn(MethodName, Option<&str>) + Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
DeprecationNotice {
|
||||||
|
now,
|
||||||
|
next_warning_at: Default::default(),
|
||||||
|
printer: Box::new(printer),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Print deprecation notice for given method and with some additional details (explanations).
|
||||||
|
pub fn print<'a, T: Into<Option<&'a str>>>(&self, method: MethodName, details: T) {
|
||||||
|
let now = (self.now)();
|
||||||
|
match self.next_warning_at.read().get(method) {
|
||||||
|
Some(next) if next > &now => return,
|
||||||
|
_ => {},
|
||||||
|
}
|
||||||
|
|
||||||
|
self.next_warning_at.write().insert(method.to_owned(), now + PRINT_INTERVAL);
|
||||||
|
(self.printer)(method, details.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn should_throttle_printing() {
|
||||||
|
let saved = Arc::new(RwLock::new(None));
|
||||||
|
let s = saved.clone();
|
||||||
|
let printer = move |method: MethodName, more: Option<&str>| {
|
||||||
|
*s.write() = Some((method, more.map(|s| s.to_owned())));
|
||||||
|
};
|
||||||
|
|
||||||
|
let now = Arc::new(RwLock::new(Instant::now()));
|
||||||
|
let n = now.clone();
|
||||||
|
let get_now = || n.read().clone();
|
||||||
|
let notice = DeprecationNotice::new(get_now, printer);
|
||||||
|
|
||||||
|
let details = Some("See issue #123456");
|
||||||
|
notice.print("eth_test", details.clone());
|
||||||
|
// printer shouldn't be called
|
||||||
|
notice.print("eth_test", None);
|
||||||
|
assert_eq!(saved.read().clone().unwrap(), ("eth_test", details.as_ref().map(|x| x.to_string())));
|
||||||
|
// but calling a different method is fine
|
||||||
|
notice.print("eth_test2", None);
|
||||||
|
assert_eq!(saved.read().clone().unwrap(), ("eth_test2", None));
|
||||||
|
|
||||||
|
// wait and call again
|
||||||
|
*now.write() = Instant::now() + PRINT_INTERVAL;
|
||||||
|
notice.print("eth_test", None);
|
||||||
|
assert_eq!(saved.read().clone().unwrap(), ("eth_test", None));
|
||||||
|
}
|
||||||
|
}
|
@ -1,879 +0,0 @@
|
|||||||
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
|
|
||||||
// This file is part of Parity Ethereum.
|
|
||||||
|
|
||||||
// Parity Ethereum 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 Ethereum 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 Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
|
||||||
|
|
||||||
//! Utilities and helpers for transaction dispatch.
|
|
||||||
|
|
||||||
use std::fmt::Debug;
|
|
||||||
use std::ops::Deref;
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
use light::cache::Cache as LightDataCache;
|
|
||||||
use light::client::LightChainClient;
|
|
||||||
use light::on_demand::{request, OnDemand};
|
|
||||||
use light::TransactionQueue as LightTransactionQueue;
|
|
||||||
use hash::keccak;
|
|
||||||
use ethereum_types::{H256, H520, Address, U256};
|
|
||||||
use bytes::Bytes;
|
|
||||||
use parking_lot::{Mutex, RwLock};
|
|
||||||
use stats::Corpus;
|
|
||||||
|
|
||||||
use crypto::DEFAULT_MAC;
|
|
||||||
use ethcore::account_provider::AccountProvider;
|
|
||||||
use ethcore::client::BlockChainClient;
|
|
||||||
use ethcore::miner::{self, MinerService};
|
|
||||||
use ethkey::{Password, Signature};
|
|
||||||
use sync::LightSync;
|
|
||||||
use types::transaction::{Action, SignedTransaction, PendingTransaction, Transaction, Error as TransactionError};
|
|
||||||
use types::basic_account::BasicAccount;
|
|
||||||
use types::ids::BlockId;
|
|
||||||
|
|
||||||
use jsonrpc_core::{BoxFuture, Result, Error};
|
|
||||||
use jsonrpc_core::futures::{future, Future, Poll, Async, IntoFuture};
|
|
||||||
use jsonrpc_core::futures::future::Either;
|
|
||||||
use v1::helpers::{errors, nonce, TransactionRequest, FilledTransactionRequest, ConfirmationPayload};
|
|
||||||
use v1::types::{
|
|
||||||
H520 as RpcH520, Bytes as RpcBytes,
|
|
||||||
RichRawTransaction as RpcRichRawTransaction,
|
|
||||||
ConfirmationPayload as RpcConfirmationPayload,
|
|
||||||
ConfirmationResponse,
|
|
||||||
EthSignRequest as RpcEthSignRequest,
|
|
||||||
EIP191SignRequest as RpcSignRequest,
|
|
||||||
DecryptRequest as RpcDecryptRequest,
|
|
||||||
};
|
|
||||||
use rlp;
|
|
||||||
|
|
||||||
pub use self::nonce::Reservations;
|
|
||||||
|
|
||||||
/// Has the capability to dispatch, sign, and decrypt.
|
|
||||||
///
|
|
||||||
/// Requires a clone implementation, with the implication that it be cheap;
|
|
||||||
/// usually just bumping a reference count or two.
|
|
||||||
pub trait Dispatcher: Send + Sync + Clone {
|
|
||||||
// TODO: when ATC exist, use zero-cost
|
|
||||||
// type Out<T>: IntoFuture<T, Error>
|
|
||||||
|
|
||||||
/// Fill optional fields of a transaction request, fetching gas price but not nonce.
|
|
||||||
fn fill_optional_fields(&self, request: TransactionRequest, default_sender: Address, force_nonce: bool)
|
|
||||||
-> BoxFuture<FilledTransactionRequest>;
|
|
||||||
|
|
||||||
/// Sign the given transaction request, fetching appropriate nonce and executing the PostSign action
|
|
||||||
fn sign<P>(
|
|
||||||
&self,
|
|
||||||
accounts: Arc<AccountProvider>,
|
|
||||||
filled: FilledTransactionRequest,
|
|
||||||
password: SignWith,
|
|
||||||
post_sign: P
|
|
||||||
) -> BoxFuture<P::Item>
|
|
||||||
where
|
|
||||||
P: PostSign + 'static,
|
|
||||||
<P::Out as futures::future::IntoFuture>::Future: Send;
|
|
||||||
|
|
||||||
/// Converts a `SignedTransaction` into `RichRawTransaction`
|
|
||||||
fn enrich(&self, signed: SignedTransaction) -> RpcRichRawTransaction;
|
|
||||||
|
|
||||||
/// "Dispatch" a local transaction.
|
|
||||||
fn dispatch_transaction(&self, signed_transaction: PendingTransaction)
|
|
||||||
-> Result<H256>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A dispatcher which uses references to a client and miner in order to sign
|
|
||||||
/// requests locally.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct FullDispatcher<C, M> {
|
|
||||||
client: Arc<C>,
|
|
||||||
miner: Arc<M>,
|
|
||||||
nonces: Arc<Mutex<nonce::Reservations>>,
|
|
||||||
gas_price_percentile: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<C, M> FullDispatcher<C, M> {
|
|
||||||
/// Create a `FullDispatcher` from Arc references to a client and miner.
|
|
||||||
pub fn new(
|
|
||||||
client: Arc<C>,
|
|
||||||
miner: Arc<M>,
|
|
||||||
nonces: Arc<Mutex<nonce::Reservations>>,
|
|
||||||
gas_price_percentile: usize,
|
|
||||||
) -> Self {
|
|
||||||
FullDispatcher {
|
|
||||||
client,
|
|
||||||
miner,
|
|
||||||
nonces,
|
|
||||||
gas_price_percentile,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<C, M> Clone for FullDispatcher<C, M> {
|
|
||||||
fn clone(&self) -> Self {
|
|
||||||
FullDispatcher {
|
|
||||||
client: self.client.clone(),
|
|
||||||
miner: self.miner.clone(),
|
|
||||||
nonces: self.nonces.clone(),
|
|
||||||
gas_price_percentile: self.gas_price_percentile,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<C: miner::BlockChainClient, M: MinerService> FullDispatcher<C, M> {
|
|
||||||
fn state_nonce(&self, from: &Address) -> U256 {
|
|
||||||
self.miner.next_nonce(&*self.client, from)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Imports transaction to the miner's queue.
|
|
||||||
pub fn dispatch_transaction(client: &C, miner: &M, signed_transaction: PendingTransaction, trusted: bool) -> Result<H256> {
|
|
||||||
let hash = signed_transaction.transaction.hash();
|
|
||||||
|
|
||||||
// use `import_claimed_local_transaction` so we can decide (based on config flags) if we want to treat
|
|
||||||
// it as local or not. Nodes with public RPC interfaces will want these transactions to be treated like
|
|
||||||
// external transactions.
|
|
||||||
miner.import_claimed_local_transaction(client, signed_transaction, trusted)
|
|
||||||
.map_err(errors::transaction)
|
|
||||||
.map(|_| hash)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<C: miner::BlockChainClient + BlockChainClient, M: MinerService> Dispatcher for FullDispatcher<C, M> {
|
|
||||||
fn fill_optional_fields(&self, request: TransactionRequest, default_sender: Address, force_nonce: bool)
|
|
||||||
-> BoxFuture<FilledTransactionRequest>
|
|
||||||
{
|
|
||||||
let request = request;
|
|
||||||
let from = request.from.unwrap_or(default_sender);
|
|
||||||
let nonce = if force_nonce {
|
|
||||||
request.nonce.or_else(|| Some(self.state_nonce(&from)))
|
|
||||||
} else {
|
|
||||||
request.nonce
|
|
||||||
};
|
|
||||||
|
|
||||||
Box::new(future::ok(FilledTransactionRequest {
|
|
||||||
from,
|
|
||||||
used_default_from: request.from.is_none(),
|
|
||||||
to: request.to,
|
|
||||||
nonce,
|
|
||||||
gas_price: request.gas_price.unwrap_or_else(|| {
|
|
||||||
default_gas_price(&*self.client, &*self.miner, self.gas_price_percentile)
|
|
||||||
}),
|
|
||||||
gas: request.gas.unwrap_or_else(|| self.miner.sensible_gas_limit()),
|
|
||||||
value: request.value.unwrap_or_else(|| 0.into()),
|
|
||||||
data: request.data.unwrap_or_else(Vec::new),
|
|
||||||
condition: request.condition,
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn sign<P>(
|
|
||||||
&self,
|
|
||||||
accounts: Arc<AccountProvider>,
|
|
||||||
filled: FilledTransactionRequest,
|
|
||||||
password: SignWith,
|
|
||||||
post_sign: P
|
|
||||||
) -> BoxFuture<P::Item>
|
|
||||||
where
|
|
||||||
P: PostSign + 'static,
|
|
||||||
<P::Out as futures::future::IntoFuture>::Future: Send
|
|
||||||
{
|
|
||||||
let chain_id = self.client.signing_chain_id();
|
|
||||||
|
|
||||||
if let Some(nonce) = filled.nonce {
|
|
||||||
let future = sign_transaction(&*accounts, filled, chain_id, nonce, password)
|
|
||||||
.into_future()
|
|
||||||
.and_then(move |signed| post_sign.execute(signed));
|
|
||||||
Box::new(future)
|
|
||||||
} else {
|
|
||||||
let state = self.state_nonce(&filled.from);
|
|
||||||
let reserved = self.nonces.lock().reserve(filled.from, state);
|
|
||||||
|
|
||||||
Box::new(ProspectiveSigner::new(accounts, filled, chain_id, reserved, password, post_sign))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn enrich(&self, signed_transaction: SignedTransaction) -> RpcRichRawTransaction {
|
|
||||||
RpcRichRawTransaction::from_signed(signed_transaction)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn dispatch_transaction(&self, signed_transaction: PendingTransaction) -> Result<H256> {
|
|
||||||
Self::dispatch_transaction(&*self.client, &*self.miner, signed_transaction, true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get a recent gas price corpus.
|
|
||||||
// TODO: this could be `impl Trait`.
|
|
||||||
pub fn fetch_gas_price_corpus(
|
|
||||||
sync: Arc<LightSync>,
|
|
||||||
client: Arc<LightChainClient>,
|
|
||||||
on_demand: Arc<OnDemand>,
|
|
||||||
cache: Arc<Mutex<LightDataCache>>,
|
|
||||||
) -> BoxFuture<Corpus<U256>> {
|
|
||||||
const GAS_PRICE_SAMPLE_SIZE: usize = 100;
|
|
||||||
|
|
||||||
if let Some(cached) = { cache.lock().gas_price_corpus() } {
|
|
||||||
return Box::new(future::ok(cached))
|
|
||||||
}
|
|
||||||
|
|
||||||
let cache = cache.clone();
|
|
||||||
let eventual_corpus = sync.with_context(|ctx| {
|
|
||||||
// get some recent headers with gas used,
|
|
||||||
// and request each of the blocks from the network.
|
|
||||||
let block_requests = client.ancestry_iter(BlockId::Latest)
|
|
||||||
.filter(|hdr| hdr.gas_used() != U256::default())
|
|
||||||
.take(GAS_PRICE_SAMPLE_SIZE)
|
|
||||||
.map(|hdr| request::Body(hdr.into()))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
// when the blocks come in, collect gas prices into a vector
|
|
||||||
on_demand.request(ctx, block_requests)
|
|
||||||
.expect("no back-references; therefore all back-references are valid; qed")
|
|
||||||
.map(|bodies| {
|
|
||||||
bodies.into_iter().fold(Vec::new(), |mut v, block| {
|
|
||||||
for t in block.transaction_views().iter() {
|
|
||||||
v.push(t.gas_price())
|
|
||||||
}
|
|
||||||
v
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.map(move |prices| {
|
|
||||||
// produce a corpus from the vector and cache it.
|
|
||||||
// It's later used to get a percentile for default gas price.
|
|
||||||
let corpus: ::stats::Corpus<_> = prices.into();
|
|
||||||
cache.lock().set_gas_price_corpus(corpus.clone());
|
|
||||||
corpus
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
match eventual_corpus {
|
|
||||||
Some(corp) => Box::new(corp.map_err(|_| errors::no_light_peers())),
|
|
||||||
None => Box::new(future::err(errors::network_disabled())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Returns a eth_sign-compatible hash of data to sign.
|
|
||||||
/// The data is prepended with special message to prevent
|
|
||||||
/// malicious DApps from using the function to sign forged transactions.
|
|
||||||
pub fn eth_data_hash(mut data: Bytes) -> H256 {
|
|
||||||
let mut message_data =
|
|
||||||
format!("\x19Ethereum Signed Message:\n{}", data.len())
|
|
||||||
.into_bytes();
|
|
||||||
message_data.append(&mut data);
|
|
||||||
keccak(message_data)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Dispatcher for light clients -- fetches default gas price, next nonce, etc. from network.
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct LightDispatcher {
|
|
||||||
/// Sync service.
|
|
||||||
pub sync: Arc<LightSync>,
|
|
||||||
/// Header chain client.
|
|
||||||
pub client: Arc<LightChainClient>,
|
|
||||||
/// On-demand request service.
|
|
||||||
pub on_demand: Arc<OnDemand>,
|
|
||||||
/// Data cache.
|
|
||||||
pub cache: Arc<Mutex<LightDataCache>>,
|
|
||||||
/// Transaction queue.
|
|
||||||
pub transaction_queue: Arc<RwLock<LightTransactionQueue>>,
|
|
||||||
/// Nonce reservations
|
|
||||||
pub nonces: Arc<Mutex<nonce::Reservations>>,
|
|
||||||
/// Gas Price percentile value used as default gas price.
|
|
||||||
pub gas_price_percentile: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LightDispatcher {
|
|
||||||
/// Create a new `LightDispatcher` from its requisite parts.
|
|
||||||
///
|
|
||||||
/// For correct operation, the OnDemand service is assumed to be registered as a network handler,
|
|
||||||
pub fn new(
|
|
||||||
sync: Arc<LightSync>,
|
|
||||||
client: Arc<LightChainClient>,
|
|
||||||
on_demand: Arc<OnDemand>,
|
|
||||||
cache: Arc<Mutex<LightDataCache>>,
|
|
||||||
transaction_queue: Arc<RwLock<LightTransactionQueue>>,
|
|
||||||
nonces: Arc<Mutex<nonce::Reservations>>,
|
|
||||||
gas_price_percentile: usize,
|
|
||||||
) -> Self {
|
|
||||||
LightDispatcher {
|
|
||||||
sync,
|
|
||||||
client,
|
|
||||||
on_demand,
|
|
||||||
cache,
|
|
||||||
transaction_queue,
|
|
||||||
nonces,
|
|
||||||
gas_price_percentile,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get a recent gas price corpus.
|
|
||||||
// TODO: this could be `impl Trait`.
|
|
||||||
pub fn gas_price_corpus(&self) -> BoxFuture<Corpus<U256>> {
|
|
||||||
fetch_gas_price_corpus(
|
|
||||||
self.sync.clone(),
|
|
||||||
self.client.clone(),
|
|
||||||
self.on_demand.clone(),
|
|
||||||
self.cache.clone(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get an account's state
|
|
||||||
fn account(&self, addr: Address) -> BoxFuture<Option<BasicAccount>> {
|
|
||||||
let best_header = self.client.best_block_header();
|
|
||||||
let account_future = self.sync.with_context(|ctx| self.on_demand.request(ctx, request::Account {
|
|
||||||
header: best_header.into(),
|
|
||||||
address: addr,
|
|
||||||
}).expect("no back-references; therefore all back-references valid; qed"));
|
|
||||||
|
|
||||||
match account_future {
|
|
||||||
Some(response) => Box::new(response.map_err(|_| errors::no_light_peers())),
|
|
||||||
None => Box::new(future::err(errors::network_disabled())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get an account's next nonce.
|
|
||||||
pub fn next_nonce(&self, addr: Address) -> BoxFuture<U256> {
|
|
||||||
let account_start_nonce = self.client.engine().account_start_nonce(self.client.best_block_header().number());
|
|
||||||
Box::new(self.account(addr)
|
|
||||||
.and_then(move |maybe_account| {
|
|
||||||
future::ok(maybe_account.map_or(account_start_nonce, |account| account.nonce))
|
|
||||||
})
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Dispatcher for LightDispatcher {
|
|
||||||
// Ignore the `force_nonce` flag in order to always query the network when fetching the nonce and
|
|
||||||
// the account state. If the nonce is specified in the transaction use that nonce instead but do the
|
|
||||||
// network request anyway to the account state (balance)
|
|
||||||
fn fill_optional_fields(&self, request: TransactionRequest, default_sender: Address, _force_nonce: bool)
|
|
||||||
-> BoxFuture<FilledTransactionRequest>
|
|
||||||
{
|
|
||||||
const DEFAULT_GAS_PRICE: U256 = U256([0, 0, 0, 21_000_000]);
|
|
||||||
|
|
||||||
let gas_limit = self.client.best_block_header().gas_limit();
|
|
||||||
let request_gas_price = request.gas_price.clone();
|
|
||||||
let from = request.from.unwrap_or(default_sender);
|
|
||||||
|
|
||||||
let with_gas_price = move |gas_price| {
|
|
||||||
let request = request;
|
|
||||||
FilledTransactionRequest {
|
|
||||||
from: from.clone(),
|
|
||||||
used_default_from: request.from.is_none(),
|
|
||||||
to: request.to,
|
|
||||||
nonce: request.nonce,
|
|
||||||
gas_price: gas_price,
|
|
||||||
gas: request.gas.unwrap_or_else(|| gas_limit / 3),
|
|
||||||
value: request.value.unwrap_or_else(|| 0.into()),
|
|
||||||
data: request.data.unwrap_or_else(Vec::new),
|
|
||||||
condition: request.condition,
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// fast path for known gas price.
|
|
||||||
let gas_price_percentile = self.gas_price_percentile;
|
|
||||||
let gas_price = match request_gas_price {
|
|
||||||
Some(gas_price) => Either::A(future::ok(with_gas_price(gas_price))),
|
|
||||||
None => Either::B(fetch_gas_price_corpus(
|
|
||||||
self.sync.clone(),
|
|
||||||
self.client.clone(),
|
|
||||||
self.on_demand.clone(),
|
|
||||||
self.cache.clone()
|
|
||||||
).and_then(move |corp| match corp.percentile(gas_price_percentile) {
|
|
||||||
Some(percentile) => Ok(*percentile),
|
|
||||||
None => Ok(DEFAULT_GAS_PRICE), // fall back to default on error.
|
|
||||||
}).map(with_gas_price))
|
|
||||||
};
|
|
||||||
|
|
||||||
let future_account = self.account(from);
|
|
||||||
|
|
||||||
Box::new(gas_price.and_then(move |mut filled| {
|
|
||||||
future_account
|
|
||||||
.and_then(move |maybe_account| {
|
|
||||||
let cost = filled.value.saturating_add(filled.gas.saturating_mul(filled.gas_price));
|
|
||||||
match maybe_account {
|
|
||||||
Some(ref account) if cost > account.balance => {
|
|
||||||
Err(errors::transaction(TransactionError::InsufficientBalance {
|
|
||||||
balance: account.balance,
|
|
||||||
cost,
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
Some(account) => {
|
|
||||||
if filled.nonce.is_none() {
|
|
||||||
filled.nonce = Some(account.nonce);
|
|
||||||
}
|
|
||||||
Ok(filled)
|
|
||||||
}
|
|
||||||
None => Err(errors::account("Account not found", "")),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn sign<P>(
|
|
||||||
&self,
|
|
||||||
accounts: Arc<AccountProvider>,
|
|
||||||
filled: FilledTransactionRequest,
|
|
||||||
password: SignWith,
|
|
||||||
post_sign: P
|
|
||||||
) -> BoxFuture<P::Item>
|
|
||||||
where
|
|
||||||
P: PostSign + 'static,
|
|
||||||
<P::Out as futures::future::IntoFuture>::Future: Send
|
|
||||||
{
|
|
||||||
let chain_id = self.client.signing_chain_id();
|
|
||||||
let nonce = filled.nonce.expect("nonce is always provided; qed");
|
|
||||||
|
|
||||||
let future = sign_transaction(&*accounts, filled, chain_id, nonce, password)
|
|
||||||
.into_future()
|
|
||||||
.and_then(move |signed| post_sign.execute(signed));
|
|
||||||
Box::new(future)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn enrich(&self, signed_transaction: SignedTransaction) -> RpcRichRawTransaction {
|
|
||||||
RpcRichRawTransaction::from_signed(signed_transaction)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn dispatch_transaction(&self, signed_transaction: PendingTransaction) -> Result<H256> {
|
|
||||||
let hash = signed_transaction.transaction.hash();
|
|
||||||
|
|
||||||
self.transaction_queue.write().import(signed_transaction)
|
|
||||||
.map_err(errors::transaction)
|
|
||||||
.map(|_| hash)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn sign_transaction(
|
|
||||||
accounts: &AccountProvider,
|
|
||||||
filled: FilledTransactionRequest,
|
|
||||||
chain_id: Option<u64>,
|
|
||||||
nonce: U256,
|
|
||||||
password: SignWith,
|
|
||||||
) -> Result<WithToken<SignedTransaction>> {
|
|
||||||
let t = Transaction {
|
|
||||||
nonce: nonce,
|
|
||||||
action: filled.to.map_or(Action::Create, Action::Call),
|
|
||||||
gas: filled.gas,
|
|
||||||
gas_price: filled.gas_price,
|
|
||||||
value: filled.value,
|
|
||||||
data: filled.data,
|
|
||||||
};
|
|
||||||
|
|
||||||
if accounts.is_hardware_address(&filled.from) {
|
|
||||||
return hardware_signature(accounts, filled.from, t, chain_id).map(WithToken::No)
|
|
||||||
}
|
|
||||||
|
|
||||||
let hash = t.hash(chain_id);
|
|
||||||
let signature = signature(accounts, filled.from, hash, password)?;
|
|
||||||
|
|
||||||
Ok(signature.map(|sig| {
|
|
||||||
SignedTransaction::new(t.with_signature(sig, chain_id))
|
|
||||||
.expect("Transaction was signed by AccountsProvider; it never produces invalid signatures; qed")
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
|
||||||
enum ProspectiveSignerState {
|
|
||||||
TryProspectiveSign,
|
|
||||||
WaitForPostSign,
|
|
||||||
WaitForNonce,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct ProspectiveSigner<P: PostSign> {
|
|
||||||
accounts: Arc<AccountProvider>,
|
|
||||||
filled: FilledTransactionRequest,
|
|
||||||
chain_id: Option<u64>,
|
|
||||||
reserved: nonce::Reserved,
|
|
||||||
password: SignWith,
|
|
||||||
state: ProspectiveSignerState,
|
|
||||||
prospective: Option<WithToken<SignedTransaction>>,
|
|
||||||
ready: Option<nonce::Ready>,
|
|
||||||
post_sign: Option<P>,
|
|
||||||
post_sign_future: Option<<P::Out as IntoFuture>::Future>
|
|
||||||
}
|
|
||||||
|
|
||||||
/// action to execute after signing
|
|
||||||
/// e.g importing a transaction into the chain
|
|
||||||
pub trait PostSign: Send {
|
|
||||||
/// item that this PostSign returns
|
|
||||||
type Item: Send;
|
|
||||||
/// incase you need to perform async PostSign actions
|
|
||||||
type Out: IntoFuture<Item = Self::Item, Error = Error> + Send;
|
|
||||||
/// perform an action with the signed transaction
|
|
||||||
fn execute(self, signer: WithToken<SignedTransaction>) -> Self::Out;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PostSign for () {
|
|
||||||
type Item = WithToken<SignedTransaction>;
|
|
||||||
type Out = Result<Self::Item>;
|
|
||||||
fn execute(self, signed: WithToken<SignedTransaction>) -> Self::Out {
|
|
||||||
Ok(signed)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<F: Send, T: Send> PostSign for F
|
|
||||||
where F: FnOnce(WithToken<SignedTransaction>) -> Result<T>
|
|
||||||
{
|
|
||||||
type Item = T;
|
|
||||||
type Out = Result<Self::Item>;
|
|
||||||
fn execute(self, signed: WithToken<SignedTransaction>) -> Self::Out {
|
|
||||||
(self)(signed)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<P: PostSign> ProspectiveSigner<P> {
|
|
||||||
pub fn new(
|
|
||||||
accounts: Arc<AccountProvider>,
|
|
||||||
filled: FilledTransactionRequest,
|
|
||||||
chain_id: Option<u64>,
|
|
||||||
reserved: nonce::Reserved,
|
|
||||||
password: SignWith,
|
|
||||||
post_sign: P
|
|
||||||
) -> Self {
|
|
||||||
// If the account is permanently unlocked we can try to sign
|
|
||||||
// using prospective nonce. This should speed up sending
|
|
||||||
// multiple subsequent transactions in multi-threaded RPC environment.
|
|
||||||
let is_unlocked_permanently = accounts.is_unlocked_permanently(&filled.from);
|
|
||||||
let has_password = password.is_password();
|
|
||||||
|
|
||||||
ProspectiveSigner {
|
|
||||||
accounts,
|
|
||||||
filled,
|
|
||||||
chain_id,
|
|
||||||
reserved,
|
|
||||||
password,
|
|
||||||
state: if is_unlocked_permanently || has_password {
|
|
||||||
ProspectiveSignerState::TryProspectiveSign
|
|
||||||
} else {
|
|
||||||
ProspectiveSignerState::WaitForNonce
|
|
||||||
},
|
|
||||||
prospective: None,
|
|
||||||
ready: None,
|
|
||||||
post_sign: Some(post_sign),
|
|
||||||
post_sign_future: None
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn sign(&self, nonce: &U256) -> Result<WithToken<SignedTransaction>> {
|
|
||||||
sign_transaction(
|
|
||||||
&*self.accounts,
|
|
||||||
self.filled.clone(),
|
|
||||||
self.chain_id,
|
|
||||||
*nonce,
|
|
||||||
self.password.clone()
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn poll_reserved(&mut self) -> Poll<nonce::Ready, Error> {
|
|
||||||
self.reserved.poll().map_err(|_| errors::internal("Nonce reservation failure", ""))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<P: PostSign> Future for ProspectiveSigner<P> {
|
|
||||||
type Item = P::Item;
|
|
||||||
type Error = Error;
|
|
||||||
|
|
||||||
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
|
||||||
use self::ProspectiveSignerState::*;
|
|
||||||
|
|
||||||
loop {
|
|
||||||
match self.state {
|
|
||||||
TryProspectiveSign => {
|
|
||||||
// Try to poll reserved, it might be ready.
|
|
||||||
match self.poll_reserved()? {
|
|
||||||
Async::NotReady => {
|
|
||||||
self.state = WaitForNonce;
|
|
||||||
self.prospective = Some(self.sign(self.reserved.prospective_value())?);
|
|
||||||
},
|
|
||||||
Async::Ready(nonce) => {
|
|
||||||
self.state = WaitForPostSign;
|
|
||||||
self.post_sign_future = Some(self.post_sign.take()
|
|
||||||
.expect("post_sign is set on creation; qed")
|
|
||||||
.execute(self.sign(nonce.value())?)
|
|
||||||
.into_future());
|
|
||||||
self.ready = Some(nonce);
|
|
||||||
},
|
|
||||||
}
|
|
||||||
},
|
|
||||||
WaitForNonce => {
|
|
||||||
let nonce = try_ready!(self.poll_reserved());
|
|
||||||
let prospective = match (self.prospective.take(), nonce.matches_prospective()) {
|
|
||||||
(Some(prospective), true) => prospective,
|
|
||||||
_ => self.sign(nonce.value())?,
|
|
||||||
};
|
|
||||||
self.ready = Some(nonce);
|
|
||||||
self.state = WaitForPostSign;
|
|
||||||
self.post_sign_future = Some(self.post_sign.take()
|
|
||||||
.expect("post_sign is set on creation; qed")
|
|
||||||
.execute(prospective)
|
|
||||||
.into_future());
|
|
||||||
},
|
|
||||||
WaitForPostSign => {
|
|
||||||
if let Some(mut fut) = self.post_sign_future.as_mut() {
|
|
||||||
match fut.poll()? {
|
|
||||||
Async::Ready(item) => {
|
|
||||||
let nonce = self.ready
|
|
||||||
.take()
|
|
||||||
.expect("nonce is set before state transitions to WaitForPostSign; qed");
|
|
||||||
nonce.mark_used();
|
|
||||||
return Ok(Async::Ready(item))
|
|
||||||
},
|
|
||||||
Async::NotReady => {
|
|
||||||
return Ok(Async::NotReady)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
panic!("Poll after ready.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Single-use account token.
|
|
||||||
pub type AccountToken = Password;
|
|
||||||
|
|
||||||
/// Values used to unlock accounts for signing.
|
|
||||||
#[derive(Clone, PartialEq)]
|
|
||||||
pub enum SignWith {
|
|
||||||
/// Nothing -- implies the account is already unlocked.
|
|
||||||
Nothing,
|
|
||||||
/// Unlock with password.
|
|
||||||
Password(Password),
|
|
||||||
/// Unlock with single-use token.
|
|
||||||
Token(AccountToken),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SignWith {
|
|
||||||
fn is_password(&self) -> bool {
|
|
||||||
if let SignWith::Password(_) = *self {
|
|
||||||
true
|
|
||||||
} else {
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A value, potentially accompanied by a signing token.
|
|
||||||
pub enum WithToken<T> {
|
|
||||||
/// No token.
|
|
||||||
No(T),
|
|
||||||
/// With token.
|
|
||||||
Yes(T, AccountToken),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: Debug> Deref for WithToken<T> {
|
|
||||||
type Target = T;
|
|
||||||
|
|
||||||
fn deref(&self) -> &Self::Target {
|
|
||||||
match *self {
|
|
||||||
WithToken::No(ref v) => v,
|
|
||||||
WithToken::Yes(ref v, _) => v,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: Debug> WithToken<T> {
|
|
||||||
/// Map the value with the given closure, preserving the token.
|
|
||||||
pub fn map<S, F>(self, f: F) -> WithToken<S> where
|
|
||||||
S: Debug,
|
|
||||||
F: FnOnce(T) -> S,
|
|
||||||
{
|
|
||||||
match self {
|
|
||||||
WithToken::No(v) => WithToken::No(f(v)),
|
|
||||||
WithToken::Yes(v, token) => WithToken::Yes(f(v), token),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Convert into inner value, ignoring possible token.
|
|
||||||
pub fn into_value(self) -> T {
|
|
||||||
match self {
|
|
||||||
WithToken::No(v) => v,
|
|
||||||
WithToken::Yes(v, _) => v,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Convert the `WithToken` into a tuple.
|
|
||||||
pub fn into_tuple(self) -> (T, Option<AccountToken>) {
|
|
||||||
match self {
|
|
||||||
WithToken::No(v) => (v, None),
|
|
||||||
WithToken::Yes(v, token) => (v, Some(token))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: Debug> From<(T, AccountToken)> for WithToken<T> {
|
|
||||||
fn from(tuple: (T, AccountToken)) -> Self {
|
|
||||||
WithToken::Yes(tuple.0, tuple.1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T: Debug> From<(T, Option<AccountToken>)> for WithToken<T> {
|
|
||||||
fn from(tuple: (T, Option<AccountToken>)) -> Self {
|
|
||||||
match tuple.1 {
|
|
||||||
Some(token) => WithToken::Yes(tuple.0, token),
|
|
||||||
None => WithToken::No(tuple.0),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Execute a confirmation payload.
|
|
||||||
pub fn execute<D: Dispatcher + 'static>(
|
|
||||||
dispatcher: D,
|
|
||||||
accounts: Arc<AccountProvider>,
|
|
||||||
payload: ConfirmationPayload,
|
|
||||||
pass: SignWith
|
|
||||||
) -> BoxFuture<WithToken<ConfirmationResponse>> {
|
|
||||||
match payload {
|
|
||||||
ConfirmationPayload::SendTransaction(request) => {
|
|
||||||
let condition = request.condition.clone().map(Into::into);
|
|
||||||
let cloned_dispatcher = dispatcher.clone();
|
|
||||||
let post_sign = move |with_token_signed: WithToken<SignedTransaction>| {
|
|
||||||
let (signed, token) = with_token_signed.into_tuple();
|
|
||||||
let signed_transaction = PendingTransaction::new(signed, condition);
|
|
||||||
cloned_dispatcher.dispatch_transaction(signed_transaction)
|
|
||||||
.map(|hash| (hash, token))
|
|
||||||
};
|
|
||||||
let future = dispatcher.sign(accounts, request, pass, post_sign)
|
|
||||||
.map(|(hash, token)| {
|
|
||||||
WithToken::from((ConfirmationResponse::SendTransaction(hash.into()), token))
|
|
||||||
});
|
|
||||||
Box::new(future)
|
|
||||||
},
|
|
||||||
ConfirmationPayload::SignTransaction(request) => {
|
|
||||||
Box::new(dispatcher.sign(accounts, request, pass, ())
|
|
||||||
.map(move |result| result
|
|
||||||
.map(move |tx| dispatcher.enrich(tx))
|
|
||||||
.map(ConfirmationResponse::SignTransaction)
|
|
||||||
))
|
|
||||||
},
|
|
||||||
ConfirmationPayload::EthSignMessage(address, data) => {
|
|
||||||
if accounts.is_hardware_address(&address) {
|
|
||||||
let signature = accounts.sign_message_with_hardware(&address, &data)
|
|
||||||
.map(|s| H520(s.into_electrum()))
|
|
||||||
.map(RpcH520::from)
|
|
||||||
.map(ConfirmationResponse::Signature)
|
|
||||||
// TODO: is this correct? I guess the `token` is the wallet in this context
|
|
||||||
.map(WithToken::No)
|
|
||||||
.map_err(|e| errors::account("Error signing message with hardware_wallet", e));
|
|
||||||
|
|
||||||
return Box::new(future::done(signature));
|
|
||||||
}
|
|
||||||
let hash = eth_data_hash(data);
|
|
||||||
let res = signature(&accounts, address, hash, pass)
|
|
||||||
.map(|result| result
|
|
||||||
.map(|rsv| H520(rsv.into_electrum()))
|
|
||||||
.map(RpcH520::from)
|
|
||||||
.map(ConfirmationResponse::Signature)
|
|
||||||
);
|
|
||||||
Box::new(future::done(res))
|
|
||||||
},
|
|
||||||
ConfirmationPayload::SignMessage(address, data) => {
|
|
||||||
if accounts.is_hardware_address(&address) {
|
|
||||||
return Box::new(future::err(errors::account("Error signing message with hardware_wallet",
|
|
||||||
"Message signing is unsupported")));
|
|
||||||
}
|
|
||||||
let res = signature(&accounts, address, data, pass)
|
|
||||||
.map(|result| result
|
|
||||||
.map(|rsv| H520(rsv.into_electrum()))
|
|
||||||
.map(RpcH520::from)
|
|
||||||
.map(ConfirmationResponse::Signature)
|
|
||||||
);
|
|
||||||
Box::new(future::done(res))
|
|
||||||
},
|
|
||||||
ConfirmationPayload::Decrypt(address, data) => {
|
|
||||||
if accounts.is_hardware_address(&address) {
|
|
||||||
return Box::new(future::err(errors::unsupported("Decrypting via hardware wallets is not supported.", None)));
|
|
||||||
}
|
|
||||||
let res = decrypt(&accounts, address, data, pass)
|
|
||||||
.map(|result| result
|
|
||||||
.map(RpcBytes)
|
|
||||||
.map(ConfirmationResponse::Decrypt)
|
|
||||||
);
|
|
||||||
Box::new(future::done(res))
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn signature(accounts: &AccountProvider, address: Address, hash: H256, password: SignWith) -> Result<WithToken<Signature>> {
|
|
||||||
match password.clone() {
|
|
||||||
SignWith::Nothing => accounts.sign(address, None, hash).map(WithToken::No),
|
|
||||||
SignWith::Password(pass) => accounts.sign(address, Some(pass), hash).map(WithToken::No),
|
|
||||||
SignWith::Token(token) => accounts.sign_with_token(address, token, hash).map(Into::into),
|
|
||||||
}.map_err(|e| match password {
|
|
||||||
SignWith::Nothing => errors::signing(e),
|
|
||||||
_ => errors::password(e),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// obtain a hardware signature from the given account.
|
|
||||||
fn hardware_signature(accounts: &AccountProvider, address: Address, t: Transaction, chain_id: Option<u64>)
|
|
||||||
-> Result<SignedTransaction>
|
|
||||||
{
|
|
||||||
debug_assert!(accounts.is_hardware_address(&address));
|
|
||||||
|
|
||||||
let mut stream = rlp::RlpStream::new();
|
|
||||||
t.rlp_append_unsigned_transaction(&mut stream, chain_id);
|
|
||||||
let signature = accounts.sign_transaction_with_hardware(&address, &t, chain_id, &stream.as_raw())
|
|
||||||
.map_err(|e| {
|
|
||||||
debug!(target: "miner", "Error signing transaction with hardware wallet: {}", e);
|
|
||||||
errors::account("Error signing transaction with hardware wallet", e)
|
|
||||||
})?;
|
|
||||||
|
|
||||||
SignedTransaction::new(t.with_signature(signature, chain_id))
|
|
||||||
.map_err(|e| {
|
|
||||||
debug!(target: "miner", "Hardware wallet has produced invalid signature: {}", e);
|
|
||||||
errors::account("Invalid signature generated", e)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn decrypt(accounts: &AccountProvider, address: Address, msg: Bytes, password: SignWith) -> Result<WithToken<Bytes>> {
|
|
||||||
match password.clone() {
|
|
||||||
SignWith::Nothing => accounts.decrypt(address, None, &DEFAULT_MAC, &msg).map(WithToken::No),
|
|
||||||
SignWith::Password(pass) => accounts.decrypt(address, Some(pass), &DEFAULT_MAC, &msg).map(WithToken::No),
|
|
||||||
SignWith::Token(token) => accounts.decrypt_with_token(address, token, &DEFAULT_MAC, &msg).map(Into::into),
|
|
||||||
}.map_err(|e| match password {
|
|
||||||
SignWith::Nothing => errors::signing(e),
|
|
||||||
_ => errors::password(e),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Extract the default gas price from a client and miner.
|
|
||||||
pub fn default_gas_price<C, M>(client: &C, miner: &M, percentile: usize) -> U256 where
|
|
||||||
C: BlockChainClient,
|
|
||||||
M: MinerService,
|
|
||||||
{
|
|
||||||
client.gas_price_corpus(100).percentile(percentile).cloned().unwrap_or_else(|| miner.sensible_gas_price())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Convert RPC confirmation payload to signer confirmation payload.
|
|
||||||
/// May need to resolve in the future to fetch things like gas price.
|
|
||||||
pub fn from_rpc<D>(payload: RpcConfirmationPayload, default_account: Address, dispatcher: &D) -> BoxFuture<ConfirmationPayload>
|
|
||||||
where D: Dispatcher
|
|
||||||
{
|
|
||||||
match payload {
|
|
||||||
RpcConfirmationPayload::SendTransaction(request) => {
|
|
||||||
Box::new(dispatcher.fill_optional_fields(request.into(), default_account, false)
|
|
||||||
.map(ConfirmationPayload::SendTransaction))
|
|
||||||
},
|
|
||||||
RpcConfirmationPayload::SignTransaction(request) => {
|
|
||||||
Box::new(dispatcher.fill_optional_fields(request.into(), default_account, false)
|
|
||||||
.map(ConfirmationPayload::SignTransaction))
|
|
||||||
},
|
|
||||||
RpcConfirmationPayload::Decrypt(RpcDecryptRequest { address, msg }) => {
|
|
||||||
Box::new(future::ok(ConfirmationPayload::Decrypt(address.into(), msg.into())))
|
|
||||||
},
|
|
||||||
RpcConfirmationPayload::EthSignMessage(RpcEthSignRequest { address, data }) => {
|
|
||||||
Box::new(future::ok(ConfirmationPayload::EthSignMessage(address.into(), data.into())))
|
|
||||||
},
|
|
||||||
RpcConfirmationPayload::EIP191SignMessage(RpcSignRequest { address, data }) => {
|
|
||||||
Box::new(future::ok(ConfirmationPayload::SignMessage(address.into(), data.into())))
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
151
rpc/src/v1/helpers/dispatch/full.rs
Normal file
151
rpc/src/v1/helpers/dispatch/full.rs
Normal file
@ -0,0 +1,151 @@
|
|||||||
|
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
|
||||||
|
// This file is part of Parity Ethereum.
|
||||||
|
|
||||||
|
// Parity Ethereum 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 Ethereum 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 Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use ethcore::client::BlockChainClient;
|
||||||
|
use ethcore::miner::{self, MinerService};
|
||||||
|
use ethereum_types::{H256, U256, Address};
|
||||||
|
use types::transaction::{SignedTransaction, PendingTransaction};
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
|
||||||
|
use jsonrpc_core::{BoxFuture, Result};
|
||||||
|
use jsonrpc_core::futures::{future, Future, IntoFuture};
|
||||||
|
use v1::helpers::{errors, nonce, TransactionRequest, FilledTransactionRequest};
|
||||||
|
use v1::types::{RichRawTransaction as RpcRichRawTransaction};
|
||||||
|
|
||||||
|
use super::prospective_signer::ProspectiveSigner;
|
||||||
|
use super::{Dispatcher, Accounts, SignWith, PostSign, default_gas_price};
|
||||||
|
|
||||||
|
/// A dispatcher which uses references to a client and miner in order to sign
|
||||||
|
/// requests locally.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct FullDispatcher<C, M> {
|
||||||
|
client: Arc<C>,
|
||||||
|
miner: Arc<M>,
|
||||||
|
nonces: Arc<Mutex<nonce::Reservations>>,
|
||||||
|
gas_price_percentile: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<C, M> FullDispatcher<C, M> {
|
||||||
|
/// Create a `FullDispatcher` from Arc references to a client and miner.
|
||||||
|
pub fn new(
|
||||||
|
client: Arc<C>,
|
||||||
|
miner: Arc<M>,
|
||||||
|
nonces: Arc<Mutex<nonce::Reservations>>,
|
||||||
|
gas_price_percentile: usize,
|
||||||
|
) -> Self {
|
||||||
|
FullDispatcher {
|
||||||
|
client,
|
||||||
|
miner,
|
||||||
|
nonces,
|
||||||
|
gas_price_percentile,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<C, M> Clone for FullDispatcher<C, M> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
FullDispatcher {
|
||||||
|
client: self.client.clone(),
|
||||||
|
miner: self.miner.clone(),
|
||||||
|
nonces: self.nonces.clone(),
|
||||||
|
gas_price_percentile: self.gas_price_percentile,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<C: miner::BlockChainClient, M: MinerService> FullDispatcher<C, M> {
|
||||||
|
fn state_nonce(&self, from: &Address) -> U256 {
|
||||||
|
self.miner.next_nonce(&*self.client, from)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Post transaction to the network.
|
||||||
|
///
|
||||||
|
/// If transaction is trusted we are more likely to assume it is coming from a local account.
|
||||||
|
pub fn dispatch_transaction(client: &C, miner: &M, signed_transaction: PendingTransaction, trusted: bool) -> Result<H256> {
|
||||||
|
let hash = signed_transaction.transaction.hash();
|
||||||
|
|
||||||
|
// use `import_claimed_local_transaction` so we can decide (based on config flags) if we want to treat
|
||||||
|
// it as local or not. Nodes with public RPC interfaces will want these transactions to be treated like
|
||||||
|
// external transactions.
|
||||||
|
miner.import_claimed_local_transaction(client, signed_transaction, trusted)
|
||||||
|
.map_err(errors::transaction)
|
||||||
|
.map(|_| hash)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<C: miner::BlockChainClient + BlockChainClient, M: MinerService> Dispatcher for FullDispatcher<C, M> {
|
||||||
|
fn fill_optional_fields(&self, request: TransactionRequest, default_sender: Address, force_nonce: bool)
|
||||||
|
-> BoxFuture<FilledTransactionRequest>
|
||||||
|
{
|
||||||
|
let request = request;
|
||||||
|
let from = request.from.unwrap_or(default_sender);
|
||||||
|
let nonce = if force_nonce {
|
||||||
|
request.nonce.or_else(|| Some(self.state_nonce(&from)))
|
||||||
|
} else {
|
||||||
|
request.nonce
|
||||||
|
};
|
||||||
|
|
||||||
|
Box::new(future::ok(FilledTransactionRequest {
|
||||||
|
from,
|
||||||
|
used_default_from: request.from.is_none(),
|
||||||
|
to: request.to,
|
||||||
|
nonce,
|
||||||
|
gas_price: request.gas_price.unwrap_or_else(|| {
|
||||||
|
default_gas_price(&*self.client, &*self.miner, self.gas_price_percentile)
|
||||||
|
}),
|
||||||
|
gas: request.gas.unwrap_or_else(|| self.miner.sensible_gas_limit()),
|
||||||
|
value: request.value.unwrap_or_else(|| 0.into()),
|
||||||
|
data: request.data.unwrap_or_else(Vec::new),
|
||||||
|
condition: request.condition,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sign<P>(
|
||||||
|
&self,
|
||||||
|
filled: FilledTransactionRequest,
|
||||||
|
signer: &Arc<Accounts>,
|
||||||
|
password: SignWith,
|
||||||
|
post_sign: P,
|
||||||
|
) -> BoxFuture<P::Item>
|
||||||
|
where
|
||||||
|
P: PostSign + 'static,
|
||||||
|
<P::Out as IntoFuture>::Future: Send,
|
||||||
|
{
|
||||||
|
let chain_id = self.client.signing_chain_id();
|
||||||
|
|
||||||
|
if let Some(nonce) = filled.nonce {
|
||||||
|
let future = signer.sign_transaction(filled, chain_id, nonce, password)
|
||||||
|
.into_future()
|
||||||
|
.and_then(move |signed| post_sign.execute(signed));
|
||||||
|
Box::new(future)
|
||||||
|
} else {
|
||||||
|
let state = self.state_nonce(&filled.from);
|
||||||
|
let reserved = self.nonces.lock().reserve(filled.from, state);
|
||||||
|
|
||||||
|
Box::new(ProspectiveSigner::new(signer.clone(), filled, chain_id, reserved, password, post_sign))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn enrich(&self, signed_transaction: SignedTransaction) -> RpcRichRawTransaction {
|
||||||
|
RpcRichRawTransaction::from_signed(signed_transaction)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dispatch_transaction(&self, signed_transaction: PendingTransaction) -> Result<H256> {
|
||||||
|
Self::dispatch_transaction(&*self.client, &*self.miner, signed_transaction, true)
|
||||||
|
}
|
||||||
|
}
|
266
rpc/src/v1/helpers/dispatch/light.rs
Normal file
266
rpc/src/v1/helpers/dispatch/light.rs
Normal file
@ -0,0 +1,266 @@
|
|||||||
|
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
|
||||||
|
// This file is part of Parity Ethereum.
|
||||||
|
|
||||||
|
// Parity Ethereum 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 Ethereum 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 Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use ethereum_types::{H256, Address, U256};
|
||||||
|
use light::TransactionQueue as LightTransactionQueue;
|
||||||
|
use light::cache::Cache as LightDataCache;
|
||||||
|
use light::client::LightChainClient;
|
||||||
|
use light::on_demand::{request, OnDemand};
|
||||||
|
use parking_lot::{Mutex, RwLock};
|
||||||
|
use stats::Corpus;
|
||||||
|
use sync::LightSync;
|
||||||
|
use types::basic_account::BasicAccount;
|
||||||
|
use types::ids::BlockId;
|
||||||
|
use types::transaction::{SignedTransaction, PendingTransaction, Error as TransactionError};
|
||||||
|
|
||||||
|
use jsonrpc_core::{BoxFuture, Result};
|
||||||
|
use jsonrpc_core::futures::{future, Future, IntoFuture};
|
||||||
|
use jsonrpc_core::futures::future::Either;
|
||||||
|
use v1::helpers::{errors, nonce, TransactionRequest, FilledTransactionRequest};
|
||||||
|
use v1::types::{RichRawTransaction as RpcRichRawTransaction,};
|
||||||
|
|
||||||
|
use super::{Dispatcher, Accounts, SignWith, PostSign};
|
||||||
|
|
||||||
|
/// Dispatcher for light clients -- fetches default gas price, next nonce, etc. from network.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct LightDispatcher {
|
||||||
|
/// Sync service.
|
||||||
|
pub sync: Arc<LightSync>,
|
||||||
|
/// Header chain client.
|
||||||
|
pub client: Arc<LightChainClient>,
|
||||||
|
/// On-demand request service.
|
||||||
|
pub on_demand: Arc<OnDemand>,
|
||||||
|
/// Data cache.
|
||||||
|
pub cache: Arc<Mutex<LightDataCache>>,
|
||||||
|
/// Transaction queue.
|
||||||
|
pub transaction_queue: Arc<RwLock<LightTransactionQueue>>,
|
||||||
|
/// Nonce reservations
|
||||||
|
pub nonces: Arc<Mutex<nonce::Reservations>>,
|
||||||
|
/// Gas Price percentile value used as default gas price.
|
||||||
|
pub gas_price_percentile: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LightDispatcher {
|
||||||
|
/// Create a new `LightDispatcher` from its requisite parts.
|
||||||
|
///
|
||||||
|
/// For correct operation, the OnDemand service is assumed to be registered as a network handler,
|
||||||
|
pub fn new(
|
||||||
|
sync: Arc<LightSync>,
|
||||||
|
client: Arc<LightChainClient>,
|
||||||
|
on_demand: Arc<OnDemand>,
|
||||||
|
cache: Arc<Mutex<LightDataCache>>,
|
||||||
|
transaction_queue: Arc<RwLock<LightTransactionQueue>>,
|
||||||
|
nonces: Arc<Mutex<nonce::Reservations>>,
|
||||||
|
gas_price_percentile: usize,
|
||||||
|
) -> Self {
|
||||||
|
LightDispatcher {
|
||||||
|
sync,
|
||||||
|
client,
|
||||||
|
on_demand,
|
||||||
|
cache,
|
||||||
|
transaction_queue,
|
||||||
|
nonces,
|
||||||
|
gas_price_percentile,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get a recent gas price corpus.
|
||||||
|
// TODO: this could be `impl Trait`.
|
||||||
|
pub fn gas_price_corpus(&self) -> BoxFuture<Corpus<U256>> {
|
||||||
|
fetch_gas_price_corpus(
|
||||||
|
self.sync.clone(),
|
||||||
|
self.client.clone(),
|
||||||
|
self.on_demand.clone(),
|
||||||
|
self.cache.clone(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get an account's state
|
||||||
|
fn account(&self, addr: Address) -> BoxFuture<Option<BasicAccount>> {
|
||||||
|
let best_header = self.client.best_block_header();
|
||||||
|
let account_future = self.sync.with_context(|ctx| self.on_demand.request(ctx, request::Account {
|
||||||
|
header: best_header.into(),
|
||||||
|
address: addr,
|
||||||
|
}).expect("no back-references; therefore all back-references valid; qed"));
|
||||||
|
|
||||||
|
match account_future {
|
||||||
|
Some(response) => Box::new(response.map_err(|_| errors::no_light_peers())),
|
||||||
|
None => Box::new(future::err(errors::network_disabled())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get an account's next nonce.
|
||||||
|
pub fn next_nonce(&self, addr: Address) -> BoxFuture<U256> {
|
||||||
|
let account_start_nonce = self.client.engine().account_start_nonce(self.client.best_block_header().number());
|
||||||
|
Box::new(self.account(addr)
|
||||||
|
.and_then(move |maybe_account| {
|
||||||
|
future::ok(maybe_account.map_or(account_start_nonce, |account| account.nonce))
|
||||||
|
})
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Dispatcher for LightDispatcher {
|
||||||
|
// Ignore the `force_nonce` flag in order to always query the network when fetching the nonce and
|
||||||
|
// the account state. If the nonce is specified in the transaction use that nonce instead but do the
|
||||||
|
// network request anyway to the account state (balance)
|
||||||
|
fn fill_optional_fields(&self, request: TransactionRequest, default_sender: Address, _force_nonce: bool)
|
||||||
|
-> BoxFuture<FilledTransactionRequest>
|
||||||
|
{
|
||||||
|
const DEFAULT_GAS_PRICE: U256 = U256([0, 0, 0, 21_000_000]);
|
||||||
|
|
||||||
|
let gas_limit = self.client.best_block_header().gas_limit();
|
||||||
|
let request_gas_price = request.gas_price.clone();
|
||||||
|
let from = request.from.unwrap_or(default_sender);
|
||||||
|
|
||||||
|
let with_gas_price = move |gas_price| {
|
||||||
|
let request = request;
|
||||||
|
FilledTransactionRequest {
|
||||||
|
from: from.clone(),
|
||||||
|
used_default_from: request.from.is_none(),
|
||||||
|
to: request.to,
|
||||||
|
nonce: request.nonce,
|
||||||
|
gas_price: gas_price,
|
||||||
|
gas: request.gas.unwrap_or_else(|| gas_limit / 3),
|
||||||
|
value: request.value.unwrap_or_else(|| 0.into()),
|
||||||
|
data: request.data.unwrap_or_else(Vec::new),
|
||||||
|
condition: request.condition,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// fast path for known gas price.
|
||||||
|
let gas_price_percentile = self.gas_price_percentile;
|
||||||
|
let gas_price = match request_gas_price {
|
||||||
|
Some(gas_price) => Either::A(future::ok(with_gas_price(gas_price))),
|
||||||
|
None => Either::B(fetch_gas_price_corpus(
|
||||||
|
self.sync.clone(),
|
||||||
|
self.client.clone(),
|
||||||
|
self.on_demand.clone(),
|
||||||
|
self.cache.clone()
|
||||||
|
).and_then(move |corp| match corp.percentile(gas_price_percentile) {
|
||||||
|
Some(percentile) => Ok(*percentile),
|
||||||
|
None => Ok(DEFAULT_GAS_PRICE), // fall back to default on error.
|
||||||
|
}).map(with_gas_price))
|
||||||
|
};
|
||||||
|
|
||||||
|
let future_account = self.account(from);
|
||||||
|
|
||||||
|
Box::new(gas_price.and_then(move |mut filled| {
|
||||||
|
future_account
|
||||||
|
.and_then(move |maybe_account| {
|
||||||
|
let cost = filled.value.saturating_add(filled.gas.saturating_mul(filled.gas_price));
|
||||||
|
match maybe_account {
|
||||||
|
Some(ref account) if cost > account.balance => {
|
||||||
|
Err(errors::transaction(TransactionError::InsufficientBalance {
|
||||||
|
balance: account.balance,
|
||||||
|
cost,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
Some(account) => {
|
||||||
|
if filled.nonce.is_none() {
|
||||||
|
filled.nonce = Some(account.nonce);
|
||||||
|
}
|
||||||
|
Ok(filled)
|
||||||
|
}
|
||||||
|
None => Err(errors::account("Account not found", "")),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sign<P>(
|
||||||
|
&self,
|
||||||
|
filled: FilledTransactionRequest,
|
||||||
|
signer: &Arc<Accounts>,
|
||||||
|
password: SignWith,
|
||||||
|
post_sign: P
|
||||||
|
) -> BoxFuture<P::Item>
|
||||||
|
where
|
||||||
|
P: PostSign + 'static,
|
||||||
|
<P::Out as futures::future::IntoFuture>::Future: Send,
|
||||||
|
{
|
||||||
|
let chain_id = self.client.signing_chain_id();
|
||||||
|
let nonce = filled.nonce.expect("nonce is always provided; qed");
|
||||||
|
let future = signer.sign_transaction(filled, chain_id, nonce, password)
|
||||||
|
.into_future()
|
||||||
|
.and_then(move |signed| post_sign.execute(signed));
|
||||||
|
Box::new(future)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn enrich(&self, signed_transaction: SignedTransaction) -> RpcRichRawTransaction {
|
||||||
|
RpcRichRawTransaction::from_signed(signed_transaction)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dispatch_transaction(&self, signed_transaction: PendingTransaction) -> Result<H256> {
|
||||||
|
let hash = signed_transaction.transaction.hash();
|
||||||
|
|
||||||
|
self.transaction_queue.write().import(signed_transaction)
|
||||||
|
.map_err(errors::transaction)
|
||||||
|
.map(|_| hash)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get a recent gas price corpus.
|
||||||
|
// TODO: this could be `impl Trait`.
|
||||||
|
pub fn fetch_gas_price_corpus(
|
||||||
|
sync: Arc<LightSync>,
|
||||||
|
client: Arc<LightChainClient>,
|
||||||
|
on_demand: Arc<OnDemand>,
|
||||||
|
cache: Arc<Mutex<LightDataCache>>,
|
||||||
|
) -> BoxFuture<Corpus<U256>> {
|
||||||
|
const GAS_PRICE_SAMPLE_SIZE: usize = 100;
|
||||||
|
|
||||||
|
if let Some(cached) = { cache.lock().gas_price_corpus() } {
|
||||||
|
return Box::new(future::ok(cached))
|
||||||
|
}
|
||||||
|
|
||||||
|
let cache = cache.clone();
|
||||||
|
let eventual_corpus = sync.with_context(|ctx| {
|
||||||
|
// get some recent headers with gas used,
|
||||||
|
// and request each of the blocks from the network.
|
||||||
|
let block_requests = client.ancestry_iter(BlockId::Latest)
|
||||||
|
.filter(|hdr| hdr.gas_used() != U256::default())
|
||||||
|
.take(GAS_PRICE_SAMPLE_SIZE)
|
||||||
|
.map(|hdr| request::Body(hdr.into()))
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
// when the blocks come in, collect gas prices into a vector
|
||||||
|
on_demand.request(ctx, block_requests)
|
||||||
|
.expect("no back-references; therefore all back-references are valid; qed")
|
||||||
|
.map(|bodies| {
|
||||||
|
bodies.into_iter().fold(Vec::new(), |mut v, block| {
|
||||||
|
for t in block.transaction_views().iter() {
|
||||||
|
v.push(t.gas_price())
|
||||||
|
}
|
||||||
|
v
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.map(move |prices| {
|
||||||
|
// produce a corpus from the vector and cache it.
|
||||||
|
// It's later used to get a percentile for default gas price.
|
||||||
|
let corpus: ::stats::Corpus<_> = prices.into();
|
||||||
|
cache.lock().set_gas_price_corpus(corpus.clone());
|
||||||
|
corpus
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
match eventual_corpus {
|
||||||
|
Some(corp) => Box::new(corp.map_err(|_| errors::no_light_peers())),
|
||||||
|
None => Box::new(future::err(errors::network_disabled())),
|
||||||
|
}
|
||||||
|
}
|
381
rpc/src/v1/helpers/dispatch/mod.rs
Normal file
381
rpc/src/v1/helpers/dispatch/mod.rs
Normal file
@ -0,0 +1,381 @@
|
|||||||
|
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
|
||||||
|
// This file is part of Parity Ethereum.
|
||||||
|
|
||||||
|
// Parity Ethereum 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 Ethereum 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 Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
//! Utilities and helpers for transaction dispatch.
|
||||||
|
|
||||||
|
pub(crate) mod light;
|
||||||
|
mod full;
|
||||||
|
mod prospective_signer;
|
||||||
|
|
||||||
|
#[cfg(any(test, feature = "accounts"))]
|
||||||
|
mod signing;
|
||||||
|
#[cfg(not(any(test, feature = "accounts")))]
|
||||||
|
mod signing {
|
||||||
|
use super::*;
|
||||||
|
use v1::helpers::errors;
|
||||||
|
|
||||||
|
/// Dummy signer implementation
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct Signer;
|
||||||
|
|
||||||
|
impl Signer {
|
||||||
|
/// Create new instance of dummy signer (accept any AccountProvider)
|
||||||
|
pub fn new<T>(_ap: T) -> Self {
|
||||||
|
Signer
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl super::Accounts for Signer {
|
||||||
|
fn sign_transaction(&self, _filled: FilledTransactionRequest, _chain_id: Option<u64>, _nonce: U256, _password: SignWith) -> Result<WithToken<SignedTransaction>> {
|
||||||
|
Err(errors::account("Signing unsupported", "See #9997"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sign_message(&self, _address: Address, _password: SignWith, _hash: SignMessage) -> Result<WithToken<Signature>> {
|
||||||
|
Err(errors::account("Signing unsupported", "See #9997"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decrypt(&self, _address: Address, _password: SignWith, _data: Bytes) -> Result<WithToken<Bytes>> {
|
||||||
|
Err(errors::account("Signing unsupported", "See #9997"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supports_prospective_signing(&self, _address: &Address, _password: &SignWith) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_account(&self) -> Address {
|
||||||
|
Default::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_unlocked(&self, _address: &Address) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub use self::light::LightDispatcher;
|
||||||
|
pub use self::full::FullDispatcher;
|
||||||
|
pub use self::signing::Signer;
|
||||||
|
pub use v1::helpers::nonce::Reservations;
|
||||||
|
|
||||||
|
use std::fmt::Debug;
|
||||||
|
use std::ops::Deref;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use bytes::Bytes;
|
||||||
|
use ethcore::client::BlockChainClient;
|
||||||
|
use ethcore::miner::MinerService;
|
||||||
|
use ethereum_types::{H520, H256, U256, Address};
|
||||||
|
use ethkey::{Password, Signature};
|
||||||
|
use hash::keccak;
|
||||||
|
use types::transaction::{SignedTransaction, PendingTransaction};
|
||||||
|
|
||||||
|
use jsonrpc_core::{BoxFuture, Result, Error};
|
||||||
|
use jsonrpc_core::futures::{future, Future, IntoFuture};
|
||||||
|
use v1::helpers::{TransactionRequest, FilledTransactionRequest, ConfirmationPayload};
|
||||||
|
use v1::types::{
|
||||||
|
H520 as RpcH520, Bytes as RpcBytes,
|
||||||
|
RichRawTransaction as RpcRichRawTransaction,
|
||||||
|
ConfirmationPayload as RpcConfirmationPayload,
|
||||||
|
ConfirmationResponse,
|
||||||
|
EthSignRequest as RpcEthSignRequest,
|
||||||
|
EIP191SignRequest as RpcSignRequest,
|
||||||
|
DecryptRequest as RpcDecryptRequest,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Has the capability to dispatch, sign, and decrypt.
|
||||||
|
///
|
||||||
|
/// Requires a clone implementation, with the implication that it be cheap;
|
||||||
|
/// usually just bumping a reference count or two.
|
||||||
|
pub trait Dispatcher: Send + Sync + Clone {
|
||||||
|
// TODO: when ATC exist, use zero-cost
|
||||||
|
// type Out<T>: IntoFuture<T, Error>
|
||||||
|
|
||||||
|
/// Fill optional fields of a transaction request, fetching gas price but not nonce.
|
||||||
|
fn fill_optional_fields(&self, request: TransactionRequest, default_sender: Address, force_nonce: bool)
|
||||||
|
-> BoxFuture<FilledTransactionRequest>;
|
||||||
|
|
||||||
|
/// Sign the given transaction request without dispatching, fetching appropriate nonce.
|
||||||
|
fn sign<P>(
|
||||||
|
&self,
|
||||||
|
filled: FilledTransactionRequest,
|
||||||
|
signer: &Arc<Accounts>,
|
||||||
|
password: SignWith,
|
||||||
|
post_sign: P,
|
||||||
|
) -> BoxFuture<P::Item> where
|
||||||
|
P: PostSign + 'static,
|
||||||
|
<P::Out as futures::future::IntoFuture>::Future: Send;
|
||||||
|
|
||||||
|
/// Converts a `SignedTransaction` into `RichRawTransaction`
|
||||||
|
fn enrich(&self, SignedTransaction) -> RpcRichRawTransaction;
|
||||||
|
|
||||||
|
/// "Dispatch" a local transaction.
|
||||||
|
fn dispatch_transaction(&self, signed_transaction: PendingTransaction) -> Result<H256>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Payload to sign
|
||||||
|
pub enum SignMessage {
|
||||||
|
/// Eth-sign kind data (requires prefixing)
|
||||||
|
Data(Bytes),
|
||||||
|
/// Prefixed data hash
|
||||||
|
Hash(H256),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Abstract transaction signer.
|
||||||
|
///
|
||||||
|
/// NOTE This signer is semi-correct, it's a temporary measure to avoid moving too much code.
|
||||||
|
/// If accounts are ultimately removed all password-dealing endpoints will be wiped out.
|
||||||
|
pub trait Accounts: Send + Sync {
|
||||||
|
/// Sign given filled transaction request for the specified chain_id.
|
||||||
|
fn sign_transaction(&self, filled: FilledTransactionRequest, chain_id: Option<u64>, nonce: U256, password: SignWith) -> Result<WithToken<SignedTransaction>>;
|
||||||
|
|
||||||
|
/// Sign given message.
|
||||||
|
fn sign_message(&self, address: Address, password: SignWith, hash: SignMessage) -> Result<WithToken<Signature>>;
|
||||||
|
|
||||||
|
/// Decrypt given message.
|
||||||
|
fn decrypt(&self, address: Address, password: SignWith, data: Bytes) -> Result<WithToken<Bytes>>;
|
||||||
|
|
||||||
|
/// Returns `true` if the accounts can sign multiple times.
|
||||||
|
fn supports_prospective_signing(&self, address: &Address, password: &SignWith) -> bool;
|
||||||
|
|
||||||
|
/// Returns default account.
|
||||||
|
fn default_account(&self) -> Address;
|
||||||
|
|
||||||
|
/// Returns true if account is unlocked (i.e. can sign without a password)
|
||||||
|
fn is_unlocked(&self, address: &Address) -> bool;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// action to execute after signing
|
||||||
|
/// e.g importing a transaction into the chain
|
||||||
|
pub trait PostSign: Send {
|
||||||
|
/// item that this PostSign returns
|
||||||
|
type Item: Send;
|
||||||
|
/// incase you need to perform async PostSign actions
|
||||||
|
type Out: IntoFuture<Item = Self::Item, Error = Error> + Send;
|
||||||
|
/// perform an action with the signed transaction
|
||||||
|
fn execute(self, signer: WithToken<SignedTransaction>) -> Self::Out;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PostSign for () {
|
||||||
|
type Item = WithToken<SignedTransaction>;
|
||||||
|
type Out = Result<Self::Item>;
|
||||||
|
fn execute(self, signed: WithToken<SignedTransaction>) -> Self::Out {
|
||||||
|
Ok(signed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<F: Send, T: Send> PostSign for F
|
||||||
|
where F: FnOnce(WithToken<SignedTransaction>) -> Result<T>
|
||||||
|
{
|
||||||
|
type Item = T;
|
||||||
|
type Out = Result<Self::Item>;
|
||||||
|
fn execute(self, signed: WithToken<SignedTransaction>) -> Self::Out {
|
||||||
|
(self)(signed)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Single-use account token.
|
||||||
|
pub type AccountToken = Password;
|
||||||
|
|
||||||
|
/// Values used to unlock accounts for signing.
|
||||||
|
#[derive(Clone, PartialEq)]
|
||||||
|
pub enum SignWith {
|
||||||
|
/// Nothing -- implies the account is already unlocked.
|
||||||
|
Nothing,
|
||||||
|
/// Unlock with password.
|
||||||
|
Password(Password),
|
||||||
|
/// Unlock with single-use token.
|
||||||
|
Token(AccountToken),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SignWith {
|
||||||
|
fn is_password(&self) -> bool {
|
||||||
|
if let SignWith::Password(_) = *self {
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A value, potentially accompanied by a signing token.
|
||||||
|
pub enum WithToken<T> {
|
||||||
|
/// No token.
|
||||||
|
No(T),
|
||||||
|
/// With token.
|
||||||
|
Yes(T, AccountToken),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Debug> Deref for WithToken<T> {
|
||||||
|
type Target = T;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
match *self {
|
||||||
|
WithToken::No(ref v) => v,
|
||||||
|
WithToken::Yes(ref v, _) => v,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Debug> WithToken<T> {
|
||||||
|
/// Map the value with the given closure, preserving the token.
|
||||||
|
pub fn map<S, F>(self, f: F) -> WithToken<S> where
|
||||||
|
S: Debug,
|
||||||
|
F: FnOnce(T) -> S,
|
||||||
|
{
|
||||||
|
match self {
|
||||||
|
WithToken::No(v) => WithToken::No(f(v)),
|
||||||
|
WithToken::Yes(v, token) => WithToken::Yes(f(v), token),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convert into inner value, ignoring possible token.
|
||||||
|
pub fn into_value(self) -> T {
|
||||||
|
match self {
|
||||||
|
WithToken::No(v) => v,
|
||||||
|
WithToken::Yes(v, _) => v,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convert the `WithToken` into a tuple.
|
||||||
|
pub fn into_tuple(self) -> (T, Option<AccountToken>) {
|
||||||
|
match self {
|
||||||
|
WithToken::No(v) => (v, None),
|
||||||
|
WithToken::Yes(v, token) => (v, Some(token))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Debug> From<(T, AccountToken)> for WithToken<T> {
|
||||||
|
fn from(tuple: (T, AccountToken)) -> Self {
|
||||||
|
WithToken::Yes(tuple.0, tuple.1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Debug> From<(T, Option<AccountToken>)> for WithToken<T> {
|
||||||
|
fn from(tuple: (T, Option<AccountToken>)) -> Self {
|
||||||
|
match tuple.1 {
|
||||||
|
Some(token) => WithToken::Yes(tuple.0, token),
|
||||||
|
None => WithToken::No(tuple.0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Execute a confirmation payload.
|
||||||
|
pub fn execute<D: Dispatcher + 'static>(
|
||||||
|
dispatcher: D,
|
||||||
|
signer: &Arc<Accounts>,
|
||||||
|
payload: ConfirmationPayload,
|
||||||
|
pass: SignWith
|
||||||
|
) -> BoxFuture<WithToken<ConfirmationResponse>> {
|
||||||
|
match payload {
|
||||||
|
ConfirmationPayload::SendTransaction(request) => {
|
||||||
|
let condition = request.condition.clone().map(Into::into);
|
||||||
|
let cloned_dispatcher = dispatcher.clone();
|
||||||
|
let post_sign = move |with_token_signed: WithToken<SignedTransaction>| {
|
||||||
|
let (signed, token) = with_token_signed.into_tuple();
|
||||||
|
let signed_transaction = PendingTransaction::new(signed, condition);
|
||||||
|
cloned_dispatcher.dispatch_transaction(signed_transaction)
|
||||||
|
.map(|hash| (hash, token))
|
||||||
|
};
|
||||||
|
|
||||||
|
Box::new(
|
||||||
|
dispatcher.sign(request, &signer, pass, post_sign).map(|(hash, token)| {
|
||||||
|
WithToken::from((ConfirmationResponse::SendTransaction(hash.into()), token))
|
||||||
|
})
|
||||||
|
)
|
||||||
|
},
|
||||||
|
ConfirmationPayload::SignTransaction(request) => {
|
||||||
|
Box::new(dispatcher.sign(request, &signer, pass, ())
|
||||||
|
.map(move |result| result
|
||||||
|
.map(move |tx| dispatcher.enrich(tx))
|
||||||
|
.map(ConfirmationResponse::SignTransaction)
|
||||||
|
))
|
||||||
|
},
|
||||||
|
ConfirmationPayload::EthSignMessage(address, data) => {
|
||||||
|
let res = signer.sign_message(address, pass, SignMessage::Data(data))
|
||||||
|
.map(|result| result
|
||||||
|
.map(|s| H520(s.into_electrum()))
|
||||||
|
.map(RpcH520::from)
|
||||||
|
.map(ConfirmationResponse::Signature)
|
||||||
|
);
|
||||||
|
|
||||||
|
Box::new(future::done(res))
|
||||||
|
},
|
||||||
|
ConfirmationPayload::SignMessage(address, data) => {
|
||||||
|
let res = signer.sign_message(address, pass, SignMessage::Hash(data))
|
||||||
|
.map(|result| result
|
||||||
|
.map(|rsv| H520(rsv.into_electrum()))
|
||||||
|
.map(RpcH520::from)
|
||||||
|
.map(ConfirmationResponse::Signature)
|
||||||
|
);
|
||||||
|
|
||||||
|
Box::new(future::done(res))
|
||||||
|
},
|
||||||
|
ConfirmationPayload::Decrypt(address, data) => {
|
||||||
|
let res = signer.decrypt(address, pass, data)
|
||||||
|
.map(|result| result
|
||||||
|
.map(RpcBytes)
|
||||||
|
.map(ConfirmationResponse::Decrypt)
|
||||||
|
);
|
||||||
|
Box::new(future::done(res))
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a eth_sign-compatible hash of data to sign.
|
||||||
|
/// The data is prepended with special message to prevent
|
||||||
|
/// malicious DApps from using the function to sign forged transactions.
|
||||||
|
pub fn eth_data_hash(mut data: Bytes) -> H256 {
|
||||||
|
let mut message_data =
|
||||||
|
format!("\x19Ethereum Signed Message:\n{}", data.len())
|
||||||
|
.into_bytes();
|
||||||
|
message_data.append(&mut data);
|
||||||
|
keccak(message_data)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extract the default gas price from a client and miner.
|
||||||
|
pub fn default_gas_price<C, M>(client: &C, miner: &M, percentile: usize) -> U256 where
|
||||||
|
C: BlockChainClient,
|
||||||
|
M: MinerService,
|
||||||
|
{
|
||||||
|
client.gas_price_corpus(100).percentile(percentile).cloned().unwrap_or_else(|| miner.sensible_gas_price())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convert RPC confirmation payload to signer confirmation payload.
|
||||||
|
/// May need to resolve in the future to fetch things like gas price.
|
||||||
|
pub fn from_rpc<D>(payload: RpcConfirmationPayload, default_account: Address, dispatcher: &D) -> BoxFuture<ConfirmationPayload>
|
||||||
|
where D: Dispatcher
|
||||||
|
{
|
||||||
|
match payload {
|
||||||
|
RpcConfirmationPayload::SendTransaction(request) => {
|
||||||
|
Box::new(dispatcher.fill_optional_fields(request.into(), default_account, false)
|
||||||
|
.map(ConfirmationPayload::SendTransaction))
|
||||||
|
},
|
||||||
|
RpcConfirmationPayload::SignTransaction(request) => {
|
||||||
|
Box::new(dispatcher.fill_optional_fields(request.into(), default_account, false)
|
||||||
|
.map(ConfirmationPayload::SignTransaction))
|
||||||
|
},
|
||||||
|
RpcConfirmationPayload::Decrypt(RpcDecryptRequest { address, msg }) => {
|
||||||
|
Box::new(future::ok(ConfirmationPayload::Decrypt(address.into(), msg.into())))
|
||||||
|
},
|
||||||
|
RpcConfirmationPayload::EthSignMessage(RpcEthSignRequest { address, data }) => {
|
||||||
|
Box::new(future::ok(ConfirmationPayload::EthSignMessage(address.into(), data.into())))
|
||||||
|
},
|
||||||
|
RpcConfirmationPayload::EIP191SignMessage(RpcSignRequest { address, data }) => {
|
||||||
|
Box::new(future::ok(ConfirmationPayload::SignMessage(address.into(), data.into())))
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
152
rpc/src/v1/helpers/dispatch/prospective_signer.rs
Normal file
152
rpc/src/v1/helpers/dispatch/prospective_signer.rs
Normal file
@ -0,0 +1,152 @@
|
|||||||
|
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
|
||||||
|
// This file is part of Parity Ethereum.
|
||||||
|
|
||||||
|
// Parity Ethereum 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 Ethereum 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 Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use ethereum_types::U256;
|
||||||
|
use jsonrpc_core::{Result, Error};
|
||||||
|
use jsonrpc_core::futures::{Future, Poll, Async, IntoFuture};
|
||||||
|
use types::transaction::SignedTransaction;
|
||||||
|
|
||||||
|
use v1::helpers::{errors, nonce, FilledTransactionRequest};
|
||||||
|
use super::{Accounts, SignWith, WithToken, PostSign};
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
enum ProspectiveSignerState {
|
||||||
|
TryProspectiveSign,
|
||||||
|
WaitForPostSign,
|
||||||
|
WaitForNonce,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ProspectiveSigner<P: PostSign> {
|
||||||
|
signer: Arc<Accounts>,
|
||||||
|
filled: FilledTransactionRequest,
|
||||||
|
chain_id: Option<u64>,
|
||||||
|
reserved: nonce::Reserved,
|
||||||
|
password: SignWith,
|
||||||
|
state: ProspectiveSignerState,
|
||||||
|
prospective: Option<WithToken<SignedTransaction>>,
|
||||||
|
ready: Option<nonce::Ready>,
|
||||||
|
post_sign: Option<P>,
|
||||||
|
post_sign_future: Option<<P::Out as IntoFuture>::Future>
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: PostSign> ProspectiveSigner<P> {
|
||||||
|
pub fn new(
|
||||||
|
signer: Arc<Accounts>,
|
||||||
|
filled: FilledTransactionRequest,
|
||||||
|
chain_id: Option<u64>,
|
||||||
|
reserved: nonce::Reserved,
|
||||||
|
password: SignWith,
|
||||||
|
post_sign: P
|
||||||
|
) -> Self {
|
||||||
|
let supports_prospective = signer.supports_prospective_signing(&filled.from, &password);
|
||||||
|
|
||||||
|
ProspectiveSigner {
|
||||||
|
signer,
|
||||||
|
filled,
|
||||||
|
chain_id,
|
||||||
|
reserved,
|
||||||
|
password,
|
||||||
|
state: if supports_prospective {
|
||||||
|
ProspectiveSignerState::TryProspectiveSign
|
||||||
|
} else {
|
||||||
|
ProspectiveSignerState::WaitForNonce
|
||||||
|
},
|
||||||
|
prospective: None,
|
||||||
|
ready: None,
|
||||||
|
post_sign: Some(post_sign),
|
||||||
|
post_sign_future: None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sign(&self, nonce: &U256) -> Result<WithToken<SignedTransaction>> {
|
||||||
|
self.signer.sign_transaction(
|
||||||
|
self.filled.clone(),
|
||||||
|
self.chain_id,
|
||||||
|
*nonce,
|
||||||
|
self.password.clone()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn poll_reserved(&mut self) -> Poll<nonce::Ready, Error> {
|
||||||
|
self.reserved.poll().map_err(|_| errors::internal("Nonce reservation failure", ""))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<P: PostSign> Future for ProspectiveSigner<P> {
|
||||||
|
type Item = P::Item;
|
||||||
|
type Error = Error;
|
||||||
|
|
||||||
|
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
|
||||||
|
use self::ProspectiveSignerState::*;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
match self.state {
|
||||||
|
TryProspectiveSign => {
|
||||||
|
// Try to poll reserved, it might be ready.
|
||||||
|
match self.poll_reserved()? {
|
||||||
|
Async::NotReady => {
|
||||||
|
self.state = WaitForNonce;
|
||||||
|
self.prospective = Some(self.sign(self.reserved.prospective_value())?);
|
||||||
|
},
|
||||||
|
Async::Ready(nonce) => {
|
||||||
|
self.state = WaitForPostSign;
|
||||||
|
self.post_sign_future = Some(
|
||||||
|
self.post_sign.take()
|
||||||
|
.expect("post_sign is set on creation; qed")
|
||||||
|
.execute(self.sign(nonce.value())?)
|
||||||
|
.into_future()
|
||||||
|
);
|
||||||
|
self.ready = Some(nonce);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
WaitForNonce => {
|
||||||
|
let nonce = try_ready!(self.poll_reserved());
|
||||||
|
let prospective = match (self.prospective.take(), nonce.matches_prospective()) {
|
||||||
|
(Some(prospective), true) => prospective,
|
||||||
|
_ => self.sign(nonce.value())?,
|
||||||
|
};
|
||||||
|
self.ready = Some(nonce);
|
||||||
|
self.state = WaitForPostSign;
|
||||||
|
self.post_sign_future = Some(self.post_sign.take()
|
||||||
|
.expect("post_sign is set on creation; qed")
|
||||||
|
.execute(prospective)
|
||||||
|
.into_future());
|
||||||
|
},
|
||||||
|
WaitForPostSign => {
|
||||||
|
if let Some(mut fut) = self.post_sign_future.as_mut() {
|
||||||
|
match fut.poll()? {
|
||||||
|
Async::Ready(item) => {
|
||||||
|
let nonce = self.ready
|
||||||
|
.take()
|
||||||
|
.expect("nonce is set before state transitions to WaitForPostSign; qed");
|
||||||
|
nonce.mark_used();
|
||||||
|
return Ok(Async::Ready(item))
|
||||||
|
},
|
||||||
|
Async::NotReady => {
|
||||||
|
return Ok(Async::NotReady)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
panic!("Poll after ready.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
156
rpc/src/v1/helpers/dispatch/signing.rs
Normal file
156
rpc/src/v1/helpers/dispatch/signing.rs
Normal file
@ -0,0 +1,156 @@
|
|||||||
|
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
|
||||||
|
// This file is part of Parity Ethereum.
|
||||||
|
|
||||||
|
// Parity Ethereum 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 Ethereum 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 Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use accounts::AccountProvider;
|
||||||
|
use bytes::Bytes;
|
||||||
|
use crypto::DEFAULT_MAC;
|
||||||
|
use ethereum_types::{H256, U256, Address};
|
||||||
|
use ethkey::{Signature};
|
||||||
|
use types::transaction::{Transaction, Action, SignedTransaction};
|
||||||
|
|
||||||
|
use jsonrpc_core::Result;
|
||||||
|
use v1::helpers::{errors, FilledTransactionRequest};
|
||||||
|
|
||||||
|
use super::{eth_data_hash, WithToken, SignWith, SignMessage};
|
||||||
|
|
||||||
|
/// Account-aware signer
|
||||||
|
pub struct Signer {
|
||||||
|
accounts: Arc<AccountProvider>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Signer {
|
||||||
|
/// Create new instance of signer
|
||||||
|
pub fn new(accounts: Arc<AccountProvider>) -> Self {
|
||||||
|
Signer { accounts }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl super::Accounts for Signer {
|
||||||
|
fn sign_transaction(&self, filled: FilledTransactionRequest, chain_id: Option<u64>, nonce: U256, password: SignWith) -> Result<WithToken<SignedTransaction>> {
|
||||||
|
let t = Transaction {
|
||||||
|
nonce: nonce,
|
||||||
|
action: filled.to.map_or(Action::Create, Action::Call),
|
||||||
|
gas: filled.gas,
|
||||||
|
gas_price: filled.gas_price,
|
||||||
|
value: filled.value,
|
||||||
|
data: filled.data,
|
||||||
|
};
|
||||||
|
|
||||||
|
if self.accounts.is_hardware_address(&filled.from) {
|
||||||
|
return hardware_signature(&*self.accounts, filled.from, t, chain_id).map(WithToken::No)
|
||||||
|
}
|
||||||
|
|
||||||
|
let hash = t.hash(chain_id);
|
||||||
|
let signature = signature(&*self.accounts, filled.from, hash, password)?;
|
||||||
|
|
||||||
|
Ok(signature.map(|sig| {
|
||||||
|
SignedTransaction::new(t.with_signature(sig, chain_id))
|
||||||
|
.expect("Transaction was signed by AccountsProvider; it never produces invalid signatures; qed")
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sign_message(&self, address: Address, password: SignWith, hash: SignMessage) -> Result<WithToken<Signature>> {
|
||||||
|
if self.accounts.is_hardware_address(&address) {
|
||||||
|
return if let SignMessage::Data(data) = hash {
|
||||||
|
let signature = self.accounts.sign_message_with_hardware(&address, &data)
|
||||||
|
// TODO: is this correct? I guess the `token` is the wallet in this context
|
||||||
|
.map(WithToken::No)
|
||||||
|
.map_err(|e| errors::account("Error signing message with hardware_wallet", e));
|
||||||
|
|
||||||
|
signature
|
||||||
|
} else {
|
||||||
|
Err(errors::account("Error signing message with hardware_wallet", "Message signing is unsupported"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match hash {
|
||||||
|
SignMessage::Data(data) => {
|
||||||
|
let hash = eth_data_hash(data);
|
||||||
|
signature(&self.accounts, address, hash, password)
|
||||||
|
},
|
||||||
|
SignMessage::Hash(hash) => {
|
||||||
|
signature(&self.accounts, address, hash, password)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decrypt(&self, address: Address, password: SignWith, data: Bytes) -> Result<WithToken<Bytes>> {
|
||||||
|
if self.accounts.is_hardware_address(&address) {
|
||||||
|
return Err(errors::unsupported("Decrypting via hardware wallets is not supported.", None));
|
||||||
|
}
|
||||||
|
|
||||||
|
match password.clone() {
|
||||||
|
SignWith::Nothing => self.accounts.decrypt(address, None, &DEFAULT_MAC, &data).map(WithToken::No),
|
||||||
|
SignWith::Password(pass) => self.accounts.decrypt(address, Some(pass), &DEFAULT_MAC, &data).map(WithToken::No),
|
||||||
|
SignWith::Token(token) => self.accounts.decrypt_with_token(address, token, &DEFAULT_MAC, &data).map(Into::into),
|
||||||
|
}.map_err(|e| match password {
|
||||||
|
SignWith::Nothing => errors::signing(e),
|
||||||
|
_ => errors::password(e),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supports_prospective_signing(&self, address: &Address, password: &SignWith) -> bool {
|
||||||
|
// If the account is permanently unlocked we can try to sign
|
||||||
|
// using prospective nonce. This should speed up sending
|
||||||
|
// multiple subsequent transactions in multi-threaded RPC environment.
|
||||||
|
let is_unlocked_permanently = self.accounts.is_unlocked_permanently(address);
|
||||||
|
let has_password = password.is_password();
|
||||||
|
|
||||||
|
is_unlocked_permanently || has_password
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_account(&self) -> Address {
|
||||||
|
self.accounts.default_account().ok().unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_unlocked(&self, address: &Address) -> bool {
|
||||||
|
self.accounts.is_unlocked(address)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn signature(accounts: &AccountProvider, address: Address, hash: H256, password: SignWith) -> Result<WithToken<Signature>> {
|
||||||
|
match password.clone() {
|
||||||
|
SignWith::Nothing => accounts.sign(address, None, hash).map(WithToken::No),
|
||||||
|
SignWith::Password(pass) => accounts.sign(address, Some(pass), hash).map(WithToken::No),
|
||||||
|
SignWith::Token(token) => accounts.sign_with_token(address, token, hash).map(Into::into),
|
||||||
|
}.map_err(|e| match password {
|
||||||
|
SignWith::Nothing => errors::signing(e),
|
||||||
|
_ => errors::password(e),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// obtain a hardware signature from the given account.
|
||||||
|
fn hardware_signature(accounts: &AccountProvider, address: Address, t: Transaction, chain_id: Option<u64>)
|
||||||
|
-> Result<SignedTransaction>
|
||||||
|
{
|
||||||
|
debug_assert!(accounts.is_hardware_address(&address));
|
||||||
|
|
||||||
|
let mut stream = rlp::RlpStream::new();
|
||||||
|
t.rlp_append_unsigned_transaction(&mut stream, chain_id);
|
||||||
|
let signature = accounts.sign_transaction_with_hardware(&address, &t, chain_id, &stream.as_raw())
|
||||||
|
.map_err(|e| {
|
||||||
|
debug!(target: "miner", "Error signing transaction with hardware wallet: {}", e);
|
||||||
|
errors::account("Error signing transaction with hardware wallet", e)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
SignedTransaction::new(t.with_signature(signature, chain_id))
|
||||||
|
.map_err(|e| {
|
||||||
|
debug!(target: "miner", "Hardware wallet has produced invalid signature: {}", e);
|
||||||
|
errors::account("Invalid signature generated", e)
|
||||||
|
})
|
||||||
|
}
|
51
rpc/src/v1/helpers/engine_signer.rs
Normal file
51
rpc/src/v1/helpers/engine_signer.rs
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
// 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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use accounts::AccountProvider;
|
||||||
|
use ethkey::{self, Address, Password};
|
||||||
|
|
||||||
|
/// An implementation of EngineSigner using internal account management.
|
||||||
|
pub struct EngineSigner {
|
||||||
|
accounts: Arc<AccountProvider>,
|
||||||
|
address: Address,
|
||||||
|
password: Password,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EngineSigner {
|
||||||
|
/// Creates new `EngineSigner` given account manager and account details.
|
||||||
|
pub fn new(accounts: Arc<AccountProvider>, address: Address, password: Password) -> Self {
|
||||||
|
EngineSigner { accounts, address, password }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ethcore::engines::EngineSigner for EngineSigner {
|
||||||
|
fn sign(&self, message: ethkey::Message) -> Result<ethkey::Signature, ethkey::Error> {
|
||||||
|
match self.accounts.sign(self.address, Some(self.password.clone()), message) {
|
||||||
|
Ok(ok) => Ok(ok),
|
||||||
|
Err(e) => {
|
||||||
|
warn!("Unable to sign consensus message: {:?}", e);
|
||||||
|
Err(ethkey::Error::InvalidSecret)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn address(&self) -> Address {
|
||||||
|
self.address
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -18,7 +18,6 @@
|
|||||||
|
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
use ethcore::account_provider::SignError as AccountError;
|
|
||||||
use ethcore::error::{Error as EthcoreError, ErrorKind, CallError};
|
use ethcore::error::{Error as EthcoreError, ErrorKind, CallError};
|
||||||
use ethcore::client::BlockId;
|
use ethcore::client::BlockId;
|
||||||
use jsonrpc_core::{futures, Result as RpcResult, Error, ErrorCode, Value};
|
use jsonrpc_core::{futures, Result as RpcResult, Error, ErrorCode, Value};
|
||||||
@ -337,14 +336,6 @@ pub fn fetch<T: fmt::Debug>(error: T) -> Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn signing(error: AccountError) -> Error {
|
|
||||||
Error {
|
|
||||||
code: ErrorCode::ServerError(codes::ACCOUNT_LOCKED),
|
|
||||||
message: "Your account is locked. Unlock the account via CLI, personal_unlockAccount or use Trusted Signer.".into(),
|
|
||||||
data: Some(Value::String(format!("{:?}", error))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn invalid_call_data<T: fmt::Display>(error: T) -> Error {
|
pub fn invalid_call_data<T: fmt::Display>(error: T) -> Error {
|
||||||
Error {
|
Error {
|
||||||
code: ErrorCode::ServerError(codes::ENCODING_ERROR),
|
code: ErrorCode::ServerError(codes::ENCODING_ERROR),
|
||||||
@ -353,7 +344,17 @@ pub fn invalid_call_data<T: fmt::Display>(error: T) -> Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn password(error: AccountError) -> Error {
|
#[cfg(any(test, feature = "accounts"))]
|
||||||
|
pub fn signing(error: ::accounts::SignError) -> Error {
|
||||||
|
Error {
|
||||||
|
code: ErrorCode::ServerError(codes::ACCOUNT_LOCKED),
|
||||||
|
message: "Your account is locked. Unlock the account via CLI, personal_unlockAccount or use Trusted Signer.".into(),
|
||||||
|
data: Some(Value::String(format!("{:?}", error))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(any(test, feature = "accounts"))]
|
||||||
|
pub fn password(error: ::accounts::SignError) -> Error {
|
||||||
Error {
|
Error {
|
||||||
code: ErrorCode::ServerError(codes::PASSWORD_INVALID),
|
code: ErrorCode::ServerError(codes::PASSWORD_INVALID),
|
||||||
message: "Account password is invalid or account does not exist.".into(),
|
message: "Account password is invalid or account does not exist.".into(),
|
||||||
|
@ -14,23 +14,22 @@
|
|||||||
// You should have received a copy of the GNU General Public License
|
// You should have received a copy of the GNU General Public License
|
||||||
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
//! An list of requests to be confirmed or signed by an external approver/signer.
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::ops::Deref;
|
use std::ops::Deref;
|
||||||
use http::Origin;
|
|
||||||
use parking_lot::Mutex;
|
|
||||||
use transient_hashmap::TransientHashMap;
|
|
||||||
|
|
||||||
use ethstore::random_string;
|
mod oneshot;
|
||||||
|
mod signing_queue;
|
||||||
|
|
||||||
use v1::helpers::signing_queue::{ConfirmationsQueue};
|
pub use self::signing_queue::{SigningQueue, ConfirmationsQueue, ConfirmationReceiver, ConfirmationResult};
|
||||||
|
#[cfg(test)]
|
||||||
const TOKEN_LIFETIME_SECS: u32 = 3600;
|
pub use self::signing_queue::QueueEvent;
|
||||||
|
|
||||||
/// Manages communication with Signer crate
|
/// Manages communication with Signer crate
|
||||||
pub struct SignerService {
|
pub struct SignerService {
|
||||||
is_enabled: bool,
|
is_enabled: bool,
|
||||||
queue: Arc<ConfirmationsQueue>,
|
queue: Arc<ConfirmationsQueue>,
|
||||||
web_proxy_tokens: Mutex<TransientHashMap<String, Origin>>,
|
|
||||||
generate_new_token: Box<Fn() -> Result<String, String> + Send + Sync + 'static>,
|
generate_new_token: Box<Fn() -> Result<String, String> + Send + Sync + 'static>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -40,26 +39,11 @@ impl SignerService {
|
|||||||
where F: Fn() -> Result<String, String> + Send + Sync + 'static {
|
where F: Fn() -> Result<String, String> + Send + Sync + 'static {
|
||||||
SignerService {
|
SignerService {
|
||||||
queue: Arc::new(ConfirmationsQueue::default()),
|
queue: Arc::new(ConfirmationsQueue::default()),
|
||||||
web_proxy_tokens: Mutex::new(TransientHashMap::new(TOKEN_LIFETIME_SECS)),
|
|
||||||
generate_new_token: Box::new(new_token),
|
generate_new_token: Box::new(new_token),
|
||||||
is_enabled: is_enabled,
|
is_enabled: is_enabled,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Checks if the token is valid web proxy access token.
|
|
||||||
pub fn web_proxy_access_token_domain(&self, token: &String) -> Option<Origin> {
|
|
||||||
self.web_proxy_tokens.lock().get(token).cloned()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Generates a new web proxy access token.
|
|
||||||
pub fn generate_web_proxy_access_token(&self, domain: Origin) -> String {
|
|
||||||
let token = random_string(16);
|
|
||||||
let mut tokens = self.web_proxy_tokens.lock();
|
|
||||||
tokens.prune();
|
|
||||||
tokens.insert(token.clone(), domain);
|
|
||||||
token
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Generates new signer authorization token.
|
/// Generates new signer authorization token.
|
||||||
pub fn generate_token(&self) -> Result<String, String> {
|
pub fn generate_token(&self) -> Result<String, String> {
|
||||||
(self.generate_new_token)()
|
(self.generate_new_token)()
|
@ -15,28 +15,18 @@
|
|||||||
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
use ethereum_types::{U256, Address};
|
use ethereum_types::U256;
|
||||||
use parking_lot::{Mutex, RwLock};
|
use parking_lot::{Mutex, RwLock};
|
||||||
use v1::helpers::{ConfirmationRequest, ConfirmationPayload, oneshot, errors};
|
use super::oneshot;
|
||||||
use v1::types::{ConfirmationResponse, H160 as RpcH160, Origin};
|
use v1::helpers::errors;
|
||||||
|
use v1::helpers::requests::{ConfirmationRequest, ConfirmationPayload};
|
||||||
|
use v1::types::{ConfirmationResponse, Origin};
|
||||||
|
|
||||||
use jsonrpc_core::Error;
|
use jsonrpc_core::Error;
|
||||||
|
|
||||||
/// Result that can be returned from JSON RPC.
|
/// Result that can be returned from JSON RPC.
|
||||||
pub type ConfirmationResult = Result<ConfirmationResponse, Error>;
|
pub type ConfirmationResult = Result<ConfirmationResponse, Error>;
|
||||||
|
|
||||||
/// Type of default account
|
|
||||||
pub enum DefaultAccount {
|
|
||||||
/// Default account is known
|
|
||||||
Provided(Address),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<RpcH160> for DefaultAccount {
|
|
||||||
fn from(address: RpcH160) -> Self {
|
|
||||||
DefaultAccount::Provided(address.into())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Possible events happening in the queue that can be listened to.
|
/// Possible events happening in the queue that can be listened to.
|
||||||
#[derive(Debug, PartialEq, Clone)]
|
#[derive(Debug, PartialEq, Clone)]
|
||||||
pub enum QueueEvent {
|
pub enum QueueEvent {
|
||||||
@ -225,9 +215,8 @@ mod test {
|
|||||||
use ethereum_types::{U256, Address};
|
use ethereum_types::{U256, Address};
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use jsonrpc_core::futures::Future;
|
use jsonrpc_core::futures::Future;
|
||||||
use v1::helpers::{
|
use v1::helpers::external_signer::{SigningQueue, ConfirmationsQueue, QueueEvent};
|
||||||
SigningQueue, ConfirmationsQueue, QueueEvent, FilledTransactionRequest, ConfirmationPayload,
|
use v1::helpers::{FilledTransactionRequest, ConfirmationPayload};
|
||||||
};
|
|
||||||
use v1::types::ConfirmationResponse;
|
use v1::types::ConfirmationResponse;
|
||||||
|
|
||||||
fn request() -> ConfirmationPayload {
|
fn request() -> ConfirmationPayload {
|
||||||
@ -299,3 +288,4 @@ mod test {
|
|||||||
assert_eq!(el.payload, request);
|
assert_eq!(el.payload, request);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -231,7 +231,7 @@ impl LightFetch {
|
|||||||
let gas_price_percentile = self.gas_price_percentile;
|
let gas_price_percentile = self.gas_price_percentile;
|
||||||
let gas_price_fut = match req.gas_price {
|
let gas_price_fut = match req.gas_price {
|
||||||
Some(price) => Either::A(future::ok(price)),
|
Some(price) => Either::A(future::ok(price)),
|
||||||
None => Either::B(dispatch::fetch_gas_price_corpus(
|
None => Either::B(dispatch::light::fetch_gas_price_corpus(
|
||||||
self.sync.clone(),
|
self.sync.clone(),
|
||||||
self.client.clone(),
|
self.client.clone(),
|
||||||
self.on_demand.clone(),
|
self.on_demand.clone(),
|
||||||
|
@ -18,21 +18,22 @@
|
|||||||
pub mod errors;
|
pub mod errors;
|
||||||
|
|
||||||
pub mod block_import;
|
pub mod block_import;
|
||||||
|
pub mod deprecated;
|
||||||
pub mod dispatch;
|
pub mod dispatch;
|
||||||
|
pub mod eip191;
|
||||||
|
#[cfg(any(test, feature = "accounts"))]
|
||||||
|
pub mod engine_signer;
|
||||||
|
pub mod external_signer;
|
||||||
pub mod fake_sign;
|
pub mod fake_sign;
|
||||||
pub mod ipfs;
|
pub mod ipfs;
|
||||||
pub mod light_fetch;
|
pub mod light_fetch;
|
||||||
pub mod nonce;
|
pub mod nonce;
|
||||||
pub mod oneshot;
|
|
||||||
pub mod secretstore;
|
pub mod secretstore;
|
||||||
pub mod eip191;
|
|
||||||
|
|
||||||
mod network_settings;
|
mod network_settings;
|
||||||
mod poll_filter;
|
mod poll_filter;
|
||||||
mod poll_manager;
|
mod poll_manager;
|
||||||
mod requests;
|
mod requests;
|
||||||
mod signer;
|
|
||||||
mod signing_queue;
|
|
||||||
mod subscribers;
|
mod subscribers;
|
||||||
mod subscription_manager;
|
mod subscription_manager;
|
||||||
mod work;
|
mod work;
|
||||||
@ -46,12 +47,6 @@ pub use self::poll_filter::{PollFilter, SyncPollFilter, limit_logs};
|
|||||||
pub use self::requests::{
|
pub use self::requests::{
|
||||||
TransactionRequest, FilledTransactionRequest, ConfirmationRequest, ConfirmationPayload, CallRequest,
|
TransactionRequest, FilledTransactionRequest, ConfirmationRequest, ConfirmationPayload, CallRequest,
|
||||||
};
|
};
|
||||||
pub use self::signing_queue::{
|
|
||||||
ConfirmationsQueue, ConfirmationReceiver, ConfirmationResult, ConfirmationSender,
|
|
||||||
SigningQueue, QueueEvent, DefaultAccount,
|
|
||||||
QUEUE_LIMIT as SIGNING_QUEUE_LIMIT,
|
|
||||||
};
|
|
||||||
pub use self::signer::SignerService;
|
|
||||||
pub use self::subscribers::Subscribers;
|
pub use self::subscribers::Subscribers;
|
||||||
pub use self::subscription_manager::GenericPollManager;
|
pub use self::subscription_manager::GenericPollManager;
|
||||||
pub use self::work::submit_work_detail;
|
pub use self::work::submit_work_detail;
|
||||||
|
@ -14,11 +14,10 @@
|
|||||||
// You should have received a copy of the GNU General Public License
|
// You should have received a copy of the GNU General Public License
|
||||||
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
use ethereum_types::{U256, Address};
|
use ethereum_types::{U256, H256, Address};
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
|
|
||||||
use v1::types::{Origin, TransactionCondition};
|
use v1::types::{Origin, TransactionCondition};
|
||||||
use ethereum_types::H256;
|
|
||||||
|
|
||||||
/// Transaction request coming from RPC
|
/// Transaction request coming from RPC
|
||||||
#[derive(Debug, Clone, Default, Eq, PartialEq, Hash)]
|
#[derive(Debug, Clone, Default, Eq, PartialEq, Hash)]
|
||||||
|
@ -53,8 +53,7 @@ pub fn verify_signature(
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use std::sync::Arc;
|
use ethkey::Generator;
|
||||||
use ethcore::account_provider::AccountProvider;
|
|
||||||
use v1::types::H160;
|
use v1::types::H160;
|
||||||
|
|
||||||
pub fn add_chain_replay_protection(v: u64, chain_id: Option<u64>) -> u64 {
|
pub fn add_chain_replay_protection(v: u64, chain_id: Option<u64>) -> u64 {
|
||||||
@ -71,9 +70,9 @@ mod tests {
|
|||||||
/// mocked signer
|
/// mocked signer
|
||||||
fn sign(should_prefix: bool, data: Vec<u8>, signing_chain_id: Option<u64>) -> (H160, [u8; 32], [u8; 32], U64) {
|
fn sign(should_prefix: bool, data: Vec<u8>, signing_chain_id: Option<u64>) -> (H160, [u8; 32], [u8; 32], U64) {
|
||||||
let hash = if should_prefix { eth_data_hash(data) } else { keccak(data) };
|
let hash = if should_prefix { eth_data_hash(data) } else { keccak(data) };
|
||||||
let accounts = Arc::new(AccountProvider::transient_provider());
|
let account = ethkey::Random.generate().unwrap();
|
||||||
let address = accounts.new_account(&"password123".into()).unwrap();
|
let address = account.address();
|
||||||
let sig = accounts.sign(address, Some("password123".into()), hash).unwrap();
|
let sig = ethkey::sign(account.secret(), &hash).unwrap();
|
||||||
let (r, s, v) = (sig.r(), sig.s(), sig.v());
|
let (r, s, v) = (sig.r(), sig.s(), sig.v());
|
||||||
let v = add_chain_replay_protection(v as u64, signing_chain_id);
|
let v = add_chain_replay_protection(v as u64, signing_chain_id);
|
||||||
let (r_buf, s_buf) = {
|
let (r_buf, s_buf) = {
|
||||||
|
@ -25,7 +25,6 @@ use ethereum_types::{U256, H256, H160, Address};
|
|||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
|
|
||||||
use ethash::{self, SeedHashCompute};
|
use ethash::{self, SeedHashCompute};
|
||||||
use ethcore::account_provider::AccountProvider;
|
|
||||||
use ethcore::client::{BlockChainClient, BlockId, TransactionId, UncleId, StateOrBlock, StateClient, StateInfo, Call, EngineInfo, ProvingBlockChainClient};
|
use ethcore::client::{BlockChainClient, BlockId, TransactionId, UncleId, StateOrBlock, StateClient, StateInfo, Call, EngineInfo, ProvingBlockChainClient};
|
||||||
use ethcore::miner::{self, MinerService};
|
use ethcore::miner::{self, MinerService};
|
||||||
use ethcore::snapshot::SnapshotService;
|
use ethcore::snapshot::SnapshotService;
|
||||||
@ -41,6 +40,7 @@ use jsonrpc_core::{BoxFuture, Result};
|
|||||||
use jsonrpc_core::futures::future;
|
use jsonrpc_core::futures::future;
|
||||||
|
|
||||||
use v1::helpers::{self, errors, limit_logs, fake_sign};
|
use v1::helpers::{self, errors, limit_logs, fake_sign};
|
||||||
|
use v1::helpers::deprecated::{self, DeprecationNotice};
|
||||||
use v1::helpers::dispatch::{FullDispatcher, default_gas_price};
|
use v1::helpers::dispatch::{FullDispatcher, default_gas_price};
|
||||||
use v1::helpers::block_import::is_major_importing;
|
use v1::helpers::block_import::is_major_importing;
|
||||||
use v1::traits::Eth;
|
use v1::traits::Eth;
|
||||||
@ -105,11 +105,12 @@ pub struct EthClient<C, SN: ?Sized, S: ?Sized, M, EM> where
|
|||||||
client: Arc<C>,
|
client: Arc<C>,
|
||||||
snapshot: Arc<SN>,
|
snapshot: Arc<SN>,
|
||||||
sync: Arc<S>,
|
sync: Arc<S>,
|
||||||
accounts: Arc<AccountProvider>,
|
accounts: Arc<Fn() -> Vec<Address> + Send + Sync>,
|
||||||
miner: Arc<M>,
|
miner: Arc<M>,
|
||||||
external_miner: Arc<EM>,
|
external_miner: Arc<EM>,
|
||||||
seed_compute: Mutex<SeedHashCompute>,
|
seed_compute: Mutex<SeedHashCompute>,
|
||||||
options: EthClientOptions,
|
options: EthClientOptions,
|
||||||
|
deprecation_notice: DeprecationNotice,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@ -184,7 +185,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> EthClient<C, SN, S
|
|||||||
client: &Arc<C>,
|
client: &Arc<C>,
|
||||||
snapshot: &Arc<SN>,
|
snapshot: &Arc<SN>,
|
||||||
sync: &Arc<S>,
|
sync: &Arc<S>,
|
||||||
accounts: &Arc<AccountProvider>,
|
accounts: &Arc<Fn() -> Vec<Address> + Send + Sync>,
|
||||||
miner: &Arc<M>,
|
miner: &Arc<M>,
|
||||||
em: &Arc<EM>,
|
em: &Arc<EM>,
|
||||||
options: EthClientOptions
|
options: EthClientOptions
|
||||||
@ -198,6 +199,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> EthClient<C, SN, S
|
|||||||
external_miner: em.clone(),
|
external_miner: em.clone(),
|
||||||
seed_compute: Mutex::new(SeedHashCompute::default()),
|
seed_compute: Mutex::new(SeedHashCompute::default()),
|
||||||
options: options,
|
options: options,
|
||||||
|
deprecation_notice: Default::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -531,9 +533,9 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
|
|||||||
fn author(&self) -> Result<RpcH160> {
|
fn author(&self) -> Result<RpcH160> {
|
||||||
let miner = self.miner.authoring_params().author;
|
let miner = self.miner.authoring_params().author;
|
||||||
if miner == 0.into() {
|
if miner == 0.into() {
|
||||||
self.accounts.accounts()
|
(self.accounts)()
|
||||||
.ok()
|
.first()
|
||||||
.and_then(|a| a.first().cloned())
|
.cloned()
|
||||||
.map(From::from)
|
.map(From::from)
|
||||||
.ok_or_else(|| errors::account("No accounts were found", ""))
|
.ok_or_else(|| errors::account("No accounts were found", ""))
|
||||||
} else {
|
} else {
|
||||||
@ -558,8 +560,9 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn accounts(&self) -> Result<Vec<RpcH160>> {
|
fn accounts(&self) -> Result<Vec<RpcH160>> {
|
||||||
let accounts = self.accounts.accounts()
|
self.deprecation_notice.print("eth_accounts", deprecated::msgs::ACCOUNTS);
|
||||||
.map_err(|e| errors::account("Could not fetch accounts.", e))?;
|
|
||||||
|
let accounts = (self.accounts)();
|
||||||
Ok(accounts.into_iter().map(Into::into).collect())
|
Ok(accounts.into_iter().map(Into::into).collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -593,7 +596,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
|
|||||||
BlockNumber::Earliest => BlockId::Earliest,
|
BlockNumber::Earliest => BlockId::Earliest,
|
||||||
BlockNumber::Latest => BlockId::Latest,
|
BlockNumber::Latest => BlockId::Latest,
|
||||||
BlockNumber::Pending => {
|
BlockNumber::Pending => {
|
||||||
warn!("`Pending` is deprecated and may be removed in future versions. Falling back to `Latest`");
|
self.deprecation_notice.print("`Pending`", Some("falling back to `Latest`"));
|
||||||
BlockId::Latest
|
BlockId::Latest
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
@ -28,8 +28,7 @@ use light::client::LightChainClient;
|
|||||||
use light::{cht, TransactionQueue};
|
use light::{cht, TransactionQueue};
|
||||||
use light::on_demand::{request, OnDemand};
|
use light::on_demand::{request, OnDemand};
|
||||||
|
|
||||||
use ethcore::account_provider::AccountProvider;
|
use ethereum_types::{U256, Address};
|
||||||
use ethereum_types::U256;
|
|
||||||
use hash::{KECCAK_NULL_RLP, KECCAK_EMPTY_LIST_RLP};
|
use hash::{KECCAK_NULL_RLP, KECCAK_EMPTY_LIST_RLP};
|
||||||
use parking_lot::{RwLock, Mutex};
|
use parking_lot::{RwLock, Mutex};
|
||||||
use rlp::Rlp;
|
use rlp::Rlp;
|
||||||
@ -42,6 +41,7 @@ use types::ids::BlockId;
|
|||||||
use v1::impls::eth_filter::Filterable;
|
use v1::impls::eth_filter::Filterable;
|
||||||
use v1::helpers::{errors, limit_logs};
|
use v1::helpers::{errors, limit_logs};
|
||||||
use v1::helpers::{SyncPollFilter, PollManager};
|
use v1::helpers::{SyncPollFilter, PollManager};
|
||||||
|
use v1::helpers::deprecated::{self, DeprecationNotice};
|
||||||
use v1::helpers::light_fetch::{self, LightFetch};
|
use v1::helpers::light_fetch::{self, LightFetch};
|
||||||
use v1::traits::Eth;
|
use v1::traits::Eth;
|
||||||
use v1::types::{
|
use v1::types::{
|
||||||
@ -60,11 +60,12 @@ pub struct EthClient<T> {
|
|||||||
client: Arc<T>,
|
client: Arc<T>,
|
||||||
on_demand: Arc<OnDemand>,
|
on_demand: Arc<OnDemand>,
|
||||||
transaction_queue: Arc<RwLock<TransactionQueue>>,
|
transaction_queue: Arc<RwLock<TransactionQueue>>,
|
||||||
accounts: Arc<AccountProvider>,
|
accounts: Arc<Fn() -> Vec<Address> + Send + Sync>,
|
||||||
cache: Arc<Mutex<LightDataCache>>,
|
cache: Arc<Mutex<LightDataCache>>,
|
||||||
polls: Mutex<PollManager<SyncPollFilter>>,
|
polls: Mutex<PollManager<SyncPollFilter>>,
|
||||||
poll_lifetime: u32,
|
poll_lifetime: u32,
|
||||||
gas_price_percentile: usize,
|
gas_price_percentile: usize,
|
||||||
|
deprecation_notice: DeprecationNotice,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Clone for EthClient<T> {
|
impl<T> Clone for EthClient<T> {
|
||||||
@ -80,6 +81,7 @@ impl<T> Clone for EthClient<T> {
|
|||||||
polls: Mutex::new(PollManager::new(self.poll_lifetime)),
|
polls: Mutex::new(PollManager::new(self.poll_lifetime)),
|
||||||
poll_lifetime: self.poll_lifetime,
|
poll_lifetime: self.poll_lifetime,
|
||||||
gas_price_percentile: self.gas_price_percentile,
|
gas_price_percentile: self.gas_price_percentile,
|
||||||
|
deprecation_notice: Default::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -92,7 +94,7 @@ impl<T: LightChainClient + 'static> EthClient<T> {
|
|||||||
client: Arc<T>,
|
client: Arc<T>,
|
||||||
on_demand: Arc<OnDemand>,
|
on_demand: Arc<OnDemand>,
|
||||||
transaction_queue: Arc<RwLock<TransactionQueue>>,
|
transaction_queue: Arc<RwLock<TransactionQueue>>,
|
||||||
accounts: Arc<AccountProvider>,
|
accounts: Arc<Fn() -> Vec<Address> + Send + Sync>,
|
||||||
cache: Arc<Mutex<LightDataCache>>,
|
cache: Arc<Mutex<LightDataCache>>,
|
||||||
gas_price_percentile: usize,
|
gas_price_percentile: usize,
|
||||||
poll_lifetime: u32
|
poll_lifetime: u32
|
||||||
@ -107,6 +109,7 @@ impl<T: LightChainClient + 'static> EthClient<T> {
|
|||||||
polls: Mutex::new(PollManager::new(poll_lifetime)),
|
polls: Mutex::new(PollManager::new(poll_lifetime)),
|
||||||
poll_lifetime,
|
poll_lifetime,
|
||||||
gas_price_percentile,
|
gas_price_percentile,
|
||||||
|
deprecation_notice: Default::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -235,9 +238,9 @@ impl<T: LightChainClient + 'static> Eth for EthClient<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn author(&self) -> Result<RpcH160> {
|
fn author(&self) -> Result<RpcH160> {
|
||||||
self.accounts.accounts()
|
(self.accounts)()
|
||||||
.ok()
|
.first()
|
||||||
.and_then(|a| a.first().cloned())
|
.cloned()
|
||||||
.map(From::from)
|
.map(From::from)
|
||||||
.ok_or_else(|| errors::account("No accounts were found", ""))
|
.ok_or_else(|| errors::account("No accounts were found", ""))
|
||||||
}
|
}
|
||||||
@ -262,9 +265,12 @@ impl<T: LightChainClient + 'static> Eth for EthClient<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn accounts(&self) -> Result<Vec<RpcH160>> {
|
fn accounts(&self) -> Result<Vec<RpcH160>> {
|
||||||
self.accounts.accounts()
|
self.deprecation_notice.print("eth_accounts", deprecated::msgs::ACCOUNTS);
|
||||||
.map_err(|e| errors::account("Could not fetch accounts.", e))
|
|
||||||
.map(|accs| accs.into_iter().map(Into::<RpcH160>::into).collect())
|
Ok((self.accounts)()
|
||||||
|
.into_iter()
|
||||||
|
.map(Into::into)
|
||||||
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn block_number(&self) -> Result<RpcU256> {
|
fn block_number(&self) -> Result<RpcU256> {
|
||||||
|
@ -16,7 +16,7 @@
|
|||||||
|
|
||||||
//! Parity-specific rpc implementation.
|
//! Parity-specific rpc implementation.
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::collections::{BTreeMap, HashSet};
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use version::version_data;
|
use version::version_data;
|
||||||
|
|
||||||
@ -24,12 +24,12 @@ use crypto::DEFAULT_MAC;
|
|||||||
use ethkey::{crypto::ecies, Brain, Generator};
|
use ethkey::{crypto::ecies, Brain, Generator};
|
||||||
use ethstore::random_phrase;
|
use ethstore::random_phrase;
|
||||||
use sync::LightSyncProvider;
|
use sync::LightSyncProvider;
|
||||||
use ethcore::account_provider::AccountProvider;
|
|
||||||
use ethcore_logger::RotatingLogger;
|
use ethcore_logger::RotatingLogger;
|
||||||
|
|
||||||
use jsonrpc_core::{Result, BoxFuture};
|
use jsonrpc_core::{Result, BoxFuture};
|
||||||
use jsonrpc_core::futures::{future, Future};
|
use jsonrpc_core::futures::{future, Future};
|
||||||
use v1::helpers::{self, errors, ipfs, SigningQueue, SignerService, NetworkSettings, verify_signature};
|
use v1::helpers::{self, errors, ipfs, NetworkSettings, verify_signature};
|
||||||
|
use v1::helpers::external_signer::{SignerService, SigningQueue};
|
||||||
use v1::helpers::dispatch::LightDispatcher;
|
use v1::helpers::dispatch::LightDispatcher;
|
||||||
use v1::helpers::light_fetch::{LightFetch, light_all_transactions};
|
use v1::helpers::light_fetch::{LightFetch, light_all_transactions};
|
||||||
use v1::metadata::Metadata;
|
use v1::metadata::Metadata;
|
||||||
@ -40,7 +40,7 @@ use v1::types::{
|
|||||||
TransactionStats, LocalTransactionStatus,
|
TransactionStats, LocalTransactionStatus,
|
||||||
LightBlockNumber, ChainStatus, Receipt,
|
LightBlockNumber, ChainStatus, Receipt,
|
||||||
BlockNumber, ConsensusCapability, VersionInfo,
|
BlockNumber, ConsensusCapability, VersionInfo,
|
||||||
OperationsInfo, AccountInfo, HwAccountInfo, Header, RichHeader, RecoveredAccount,
|
OperationsInfo, Header, RichHeader, RecoveredAccount,
|
||||||
Log, Filter,
|
Log, Filter,
|
||||||
};
|
};
|
||||||
use Host;
|
use Host;
|
||||||
@ -48,7 +48,6 @@ use Host;
|
|||||||
/// Parity implementation for light client.
|
/// Parity implementation for light client.
|
||||||
pub struct ParityClient {
|
pub struct ParityClient {
|
||||||
light_dispatch: Arc<LightDispatcher>,
|
light_dispatch: Arc<LightDispatcher>,
|
||||||
accounts: Arc<AccountProvider>,
|
|
||||||
logger: Arc<RotatingLogger>,
|
logger: Arc<RotatingLogger>,
|
||||||
settings: Arc<NetworkSettings>,
|
settings: Arc<NetworkSettings>,
|
||||||
signer: Option<Arc<SignerService>>,
|
signer: Option<Arc<SignerService>>,
|
||||||
@ -60,7 +59,6 @@ impl ParityClient {
|
|||||||
/// Creates new `ParityClient`.
|
/// Creates new `ParityClient`.
|
||||||
pub fn new(
|
pub fn new(
|
||||||
light_dispatch: Arc<LightDispatcher>,
|
light_dispatch: Arc<LightDispatcher>,
|
||||||
accounts: Arc<AccountProvider>,
|
|
||||||
logger: Arc<RotatingLogger>,
|
logger: Arc<RotatingLogger>,
|
||||||
settings: Arc<NetworkSettings>,
|
settings: Arc<NetworkSettings>,
|
||||||
signer: Option<Arc<SignerService>>,
|
signer: Option<Arc<SignerService>>,
|
||||||
@ -69,7 +67,6 @@ impl ParityClient {
|
|||||||
) -> Self {
|
) -> Self {
|
||||||
ParityClient {
|
ParityClient {
|
||||||
light_dispatch,
|
light_dispatch,
|
||||||
accounts,
|
|
||||||
logger,
|
logger,
|
||||||
settings,
|
settings,
|
||||||
signer,
|
signer,
|
||||||
@ -93,49 +90,6 @@ impl ParityClient {
|
|||||||
impl Parity for ParityClient {
|
impl Parity for ParityClient {
|
||||||
type Metadata = Metadata;
|
type Metadata = Metadata;
|
||||||
|
|
||||||
fn accounts_info(&self) -> Result<BTreeMap<H160, AccountInfo>> {
|
|
||||||
let store = &self.accounts;
|
|
||||||
let dapp_accounts = store
|
|
||||||
.accounts()
|
|
||||||
.map_err(|e| errors::account("Could not fetch accounts.", e))?
|
|
||||||
.into_iter().collect::<HashSet<_>>();
|
|
||||||
|
|
||||||
let info = store.accounts_info().map_err(|e| errors::account("Could not fetch account info.", e))?;
|
|
||||||
let other = store.addresses_info();
|
|
||||||
|
|
||||||
Ok(info
|
|
||||||
.into_iter()
|
|
||||||
.chain(other.into_iter())
|
|
||||||
.filter(|&(ref a, _)| dapp_accounts.contains(a))
|
|
||||||
.map(|(a, v)| (H160::from(a), AccountInfo { name: v.name }))
|
|
||||||
.collect()
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn hardware_accounts_info(&self) -> Result<BTreeMap<H160, HwAccountInfo>> {
|
|
||||||
let store = &self.accounts;
|
|
||||||
let info = store.hardware_accounts_info().map_err(|e| errors::account("Could not fetch account info.", e))?;
|
|
||||||
Ok(info
|
|
||||||
.into_iter()
|
|
||||||
.map(|(a, v)| (H160::from(a), HwAccountInfo { name: v.name, manufacturer: v.meta }))
|
|
||||||
.collect()
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn locked_hardware_accounts_info(&self) -> Result<Vec<String>> {
|
|
||||||
let store = &self.accounts;
|
|
||||||
Ok(store.locked_hardware_accounts().map_err(|e| errors::account("Error communicating with hardware wallet.", e))?)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn default_account(&self) -> Result<H160> {
|
|
||||||
Ok(self.accounts
|
|
||||||
.accounts()
|
|
||||||
.ok()
|
|
||||||
.and_then(|accounts| accounts.get(0).cloned())
|
|
||||||
.map(|acc| acc.into())
|
|
||||||
.unwrap_or_default())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn transactions_limit(&self) -> Result<usize> {
|
fn transactions_limit(&self) -> Result<usize> {
|
||||||
Ok(usize::max_value())
|
Ok(usize::max_value())
|
||||||
}
|
}
|
||||||
|
@ -67,7 +67,7 @@ impl<F: Fetch> ParitySet for ParitySetClient<F> {
|
|||||||
Err(errors::light_unimplemented(None))
|
Err(errors::light_unimplemented(None))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_engine_signer(&self, _address: H160, _password: String) -> Result<bool> {
|
fn set_engine_signer_secret(&self, _secret: H256) -> Result<bool> {
|
||||||
Err(errors::light_unimplemented(None))
|
Err(errors::light_unimplemented(None))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -22,12 +22,15 @@ mod eth_filter;
|
|||||||
mod eth_pubsub;
|
mod eth_pubsub;
|
||||||
mod net;
|
mod net;
|
||||||
mod parity;
|
mod parity;
|
||||||
|
#[cfg(any(test, feature = "accounts"))]
|
||||||
mod parity_accounts;
|
mod parity_accounts;
|
||||||
mod parity_set;
|
mod parity_set;
|
||||||
|
#[cfg(any(test, feature = "accounts"))]
|
||||||
mod personal;
|
mod personal;
|
||||||
mod private;
|
mod private;
|
||||||
mod pubsub;
|
mod pubsub;
|
||||||
mod rpc;
|
mod rpc;
|
||||||
|
#[cfg(any(test, feature = "accounts"))]
|
||||||
mod secretstore;
|
mod secretstore;
|
||||||
mod signer;
|
mod signer;
|
||||||
mod signing;
|
mod signing;
|
||||||
@ -43,12 +46,17 @@ pub use self::eth_filter::EthFilterClient;
|
|||||||
pub use self::eth_pubsub::EthPubSubClient;
|
pub use self::eth_pubsub::EthPubSubClient;
|
||||||
pub use self::net::NetClient;
|
pub use self::net::NetClient;
|
||||||
pub use self::parity::ParityClient;
|
pub use self::parity::ParityClient;
|
||||||
|
#[cfg(any(test, feature = "accounts"))]
|
||||||
pub use self::parity_accounts::ParityAccountsClient;
|
pub use self::parity_accounts::ParityAccountsClient;
|
||||||
pub use self::parity_set::ParitySetClient;
|
pub use self::parity_set::ParitySetClient;
|
||||||
|
#[cfg(any(test, feature = "accounts"))]
|
||||||
|
pub use self::parity_set::accounts::ParitySetAccountsClient;
|
||||||
|
#[cfg(any(test, feature = "accounts"))]
|
||||||
pub use self::personal::PersonalClient;
|
pub use self::personal::PersonalClient;
|
||||||
pub use self::private::PrivateClient;
|
pub use self::private::PrivateClient;
|
||||||
pub use self::pubsub::PubSubClient;
|
pub use self::pubsub::PubSubClient;
|
||||||
pub use self::rpc::RpcClient;
|
pub use self::rpc::RpcClient;
|
||||||
|
#[cfg(any(test, feature = "accounts"))]
|
||||||
pub use self::secretstore::SecretStoreClient;
|
pub use self::secretstore::SecretStoreClient;
|
||||||
pub use self::signer::SignerClient;
|
pub use self::signer::SignerClient;
|
||||||
pub use self::signing::SigningQueueClient;
|
pub use self::signing::SigningQueueClient;
|
||||||
|
@ -17,18 +17,15 @@
|
|||||||
//! Parity-specific rpc implementation.
|
//! Parity-specific rpc implementation.
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
use std::collections::{BTreeMap, HashSet};
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use ethereum_types::Address;
|
|
||||||
use version::version_data;
|
|
||||||
|
|
||||||
use crypto::DEFAULT_MAC;
|
use crypto::DEFAULT_MAC;
|
||||||
use ethcore::account_provider::AccountProvider;
|
|
||||||
use ethcore::client::{BlockChainClient, StateClient, Call};
|
use ethcore::client::{BlockChainClient, StateClient, Call};
|
||||||
use ethcore::miner::{self, MinerService};
|
use ethcore::miner::{self, MinerService};
|
||||||
use ethcore::snapshot::{SnapshotService, RestorationStatus};
|
use ethcore::snapshot::{SnapshotService, RestorationStatus};
|
||||||
use ethcore::state::StateInfo;
|
use ethcore::state::StateInfo;
|
||||||
use ethcore_logger::RotatingLogger;
|
use ethcore_logger::RotatingLogger;
|
||||||
|
use ethereum_types::Address;
|
||||||
use ethkey::{crypto::ecies, Brain, Generator};
|
use ethkey::{crypto::ecies, Brain, Generator};
|
||||||
use ethstore::random_phrase;
|
use ethstore::random_phrase;
|
||||||
use jsonrpc_core::futures::future;
|
use jsonrpc_core::futures::future;
|
||||||
@ -36,9 +33,11 @@ use jsonrpc_core::{BoxFuture, Result};
|
|||||||
use sync::{SyncProvider, ManageNetwork};
|
use sync::{SyncProvider, ManageNetwork};
|
||||||
use types::ids::BlockId;
|
use types::ids::BlockId;
|
||||||
use updater::{Service as UpdateService};
|
use updater::{Service as UpdateService};
|
||||||
|
use version::version_data;
|
||||||
|
|
||||||
use v1::helpers::block_import::is_major_importing;
|
use v1::helpers::block_import::is_major_importing;
|
||||||
use v1::helpers::{self, errors, fake_sign, ipfs, SigningQueue, SignerService, NetworkSettings, verify_signature};
|
use v1::helpers::{self, errors, fake_sign, ipfs, NetworkSettings, verify_signature};
|
||||||
|
use v1::helpers::external_signer::{SigningQueue, SignerService};
|
||||||
use v1::metadata::Metadata;
|
use v1::metadata::Metadata;
|
||||||
use v1::traits::Parity;
|
use v1::traits::Parity;
|
||||||
use v1::types::{
|
use v1::types::{
|
||||||
@ -47,7 +46,7 @@ use v1::types::{
|
|||||||
TransactionStats, LocalTransactionStatus,
|
TransactionStats, LocalTransactionStatus,
|
||||||
BlockNumber, ConsensusCapability, VersionInfo,
|
BlockNumber, ConsensusCapability, VersionInfo,
|
||||||
OperationsInfo, ChainStatus, Log, Filter,
|
OperationsInfo, ChainStatus, Log, Filter,
|
||||||
AccountInfo, HwAccountInfo, RichHeader, Receipt, RecoveredAccount,
|
RichHeader, Receipt, RecoveredAccount,
|
||||||
block_number_to_id
|
block_number_to_id
|
||||||
};
|
};
|
||||||
use Host;
|
use Host;
|
||||||
@ -59,7 +58,6 @@ pub struct ParityClient<C, M, U> {
|
|||||||
updater: Arc<U>,
|
updater: Arc<U>,
|
||||||
sync: Arc<SyncProvider>,
|
sync: Arc<SyncProvider>,
|
||||||
net: Arc<ManageNetwork>,
|
net: Arc<ManageNetwork>,
|
||||||
accounts: Arc<AccountProvider>,
|
|
||||||
logger: Arc<RotatingLogger>,
|
logger: Arc<RotatingLogger>,
|
||||||
settings: Arc<NetworkSettings>,
|
settings: Arc<NetworkSettings>,
|
||||||
signer: Option<Arc<SignerService>>,
|
signer: Option<Arc<SignerService>>,
|
||||||
@ -77,7 +75,6 @@ impl<C, M, U> ParityClient<C, M, U> where
|
|||||||
sync: Arc<SyncProvider>,
|
sync: Arc<SyncProvider>,
|
||||||
updater: Arc<U>,
|
updater: Arc<U>,
|
||||||
net: Arc<ManageNetwork>,
|
net: Arc<ManageNetwork>,
|
||||||
accounts: Arc<AccountProvider>,
|
|
||||||
logger: Arc<RotatingLogger>,
|
logger: Arc<RotatingLogger>,
|
||||||
settings: Arc<NetworkSettings>,
|
settings: Arc<NetworkSettings>,
|
||||||
signer: Option<Arc<SignerService>>,
|
signer: Option<Arc<SignerService>>,
|
||||||
@ -90,7 +87,6 @@ impl<C, M, U> ParityClient<C, M, U> where
|
|||||||
sync,
|
sync,
|
||||||
updater,
|
updater,
|
||||||
net,
|
net,
|
||||||
accounts,
|
|
||||||
logger,
|
logger,
|
||||||
settings,
|
settings,
|
||||||
signer,
|
signer,
|
||||||
@ -108,43 +104,6 @@ impl<C, M, U, S> Parity for ParityClient<C, M, U> where
|
|||||||
{
|
{
|
||||||
type Metadata = Metadata;
|
type Metadata = Metadata;
|
||||||
|
|
||||||
fn accounts_info(&self) -> Result<BTreeMap<H160, AccountInfo>> {
|
|
||||||
let dapp_accounts = self.accounts.accounts()
|
|
||||||
.map_err(|e| errors::account("Could not fetch accounts.", e))?
|
|
||||||
.into_iter().collect::<HashSet<_>>();
|
|
||||||
|
|
||||||
let info = self.accounts.accounts_info().map_err(|e| errors::account("Could not fetch account info.", e))?;
|
|
||||||
let other = self.accounts.addresses_info();
|
|
||||||
|
|
||||||
Ok(info
|
|
||||||
.into_iter()
|
|
||||||
.chain(other.into_iter())
|
|
||||||
.filter(|&(ref a, _)| dapp_accounts.contains(a))
|
|
||||||
.map(|(a, v)| (H160::from(a), AccountInfo { name: v.name }))
|
|
||||||
.collect()
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn hardware_accounts_info(&self) -> Result<BTreeMap<H160, HwAccountInfo>> {
|
|
||||||
let info = self.accounts.hardware_accounts_info().map_err(|e| errors::account("Could not fetch account info.", e))?;
|
|
||||||
Ok(info
|
|
||||||
.into_iter()
|
|
||||||
.map(|(a, v)| (H160::from(a), HwAccountInfo { name: v.name, manufacturer: v.meta }))
|
|
||||||
.collect()
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn locked_hardware_accounts_info(&self) -> Result<Vec<String>> {
|
|
||||||
self.accounts.locked_hardware_accounts().map_err(|e| errors::account("Error communicating with hardware wallet.", e))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn default_account(&self) -> Result<H160> {
|
|
||||||
Ok(self.accounts.default_account()
|
|
||||||
.map(Into::into)
|
|
||||||
.ok()
|
|
||||||
.unwrap_or_default())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn transactions_limit(&self) -> Result<usize> {
|
fn transactions_limit(&self) -> Result<usize> {
|
||||||
Ok(self.miner.queue_status().limits.max_count)
|
Ok(self.miner.queue_status().limits.max_count)
|
||||||
}
|
}
|
||||||
|
@ -16,21 +16,29 @@
|
|||||||
|
|
||||||
//! Account management (personal) rpc implementation
|
//! Account management (personal) rpc implementation
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::collections::btree_map::{BTreeMap, Entry};
|
use std::collections::{
|
||||||
|
btree_map::{BTreeMap, Entry},
|
||||||
|
HashSet,
|
||||||
|
};
|
||||||
use ethereum_types::Address;
|
use ethereum_types::Address;
|
||||||
|
|
||||||
use ethkey::{Brain, Generator, Secret};
|
use ethkey::{Brain, Generator, Secret};
|
||||||
use ethstore::KeyFile;
|
use ethstore::KeyFile;
|
||||||
use ethcore::account_provider::AccountProvider;
|
use accounts::AccountProvider;
|
||||||
use jsonrpc_core::Result;
|
use jsonrpc_core::Result;
|
||||||
|
use v1::helpers::deprecated::{self, DeprecationNotice};
|
||||||
use v1::helpers::errors;
|
use v1::helpers::errors;
|
||||||
use v1::traits::ParityAccounts;
|
use v1::traits::{ParityAccounts, ParityAccountsInfo};
|
||||||
use v1::types::{H160 as RpcH160, H256 as RpcH256, H520 as RpcH520, Derive, DeriveHierarchical, DeriveHash, ExtAccountInfo};
|
use v1::types::{
|
||||||
|
H160 as RpcH160, H256 as RpcH256, H520 as RpcH520, Derive, DeriveHierarchical, DeriveHash,
|
||||||
|
ExtAccountInfo, AccountInfo, HwAccountInfo,
|
||||||
|
};
|
||||||
use ethkey::Password;
|
use ethkey::Password;
|
||||||
|
|
||||||
/// Account management (personal) rpc implementation.
|
/// Account management (personal) rpc implementation.
|
||||||
pub struct ParityAccountsClient {
|
pub struct ParityAccountsClient {
|
||||||
accounts: Arc<AccountProvider>,
|
accounts: Arc<AccountProvider>,
|
||||||
|
deprecation_notice: DeprecationNotice,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ParityAccountsClient {
|
impl ParityAccountsClient {
|
||||||
@ -38,12 +46,68 @@ impl ParityAccountsClient {
|
|||||||
pub fn new(store: &Arc<AccountProvider>) -> Self {
|
pub fn new(store: &Arc<AccountProvider>) -> Self {
|
||||||
ParityAccountsClient {
|
ParityAccountsClient {
|
||||||
accounts: store.clone(),
|
accounts: store.clone(),
|
||||||
|
deprecation_notice: Default::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl ParityAccountsClient {
|
||||||
|
fn deprecation_notice(&self, method: &'static str) {
|
||||||
|
self.deprecation_notice.print(method, deprecated::msgs::ACCOUNTS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ParityAccountsInfo for ParityAccountsClient {
|
||||||
|
fn accounts_info(&self) -> Result<BTreeMap<RpcH160, AccountInfo>> {
|
||||||
|
self.deprecation_notice("parity_accountsInfo");
|
||||||
|
|
||||||
|
let dapp_accounts = self.accounts.accounts()
|
||||||
|
.map_err(|e| errors::account("Could not fetch accounts.", e))?
|
||||||
|
.into_iter().collect::<HashSet<_>>();
|
||||||
|
|
||||||
|
let info = self.accounts.accounts_info().map_err(|e| errors::account("Could not fetch account info.", e))?;
|
||||||
|
let other = self.accounts.addresses_info();
|
||||||
|
|
||||||
|
Ok(info
|
||||||
|
.into_iter()
|
||||||
|
.chain(other.into_iter())
|
||||||
|
.filter(|&(ref a, _)| dapp_accounts.contains(a))
|
||||||
|
.map(|(a, v)| (RpcH160::from(a), AccountInfo { name: v.name }))
|
||||||
|
.collect()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hardware_accounts_info(&self) -> Result<BTreeMap<RpcH160, HwAccountInfo>> {
|
||||||
|
self.deprecation_notice("parity_hardwareAccountsInfo");
|
||||||
|
|
||||||
|
let info = self.accounts.hardware_accounts_info().map_err(|e| errors::account("Could not fetch account info.", e))?;
|
||||||
|
Ok(info
|
||||||
|
.into_iter()
|
||||||
|
.map(|(a, v)| (RpcH160::from(a), HwAccountInfo { name: v.name, manufacturer: v.meta }))
|
||||||
|
.collect()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn locked_hardware_accounts_info(&self) -> Result<Vec<String>> {
|
||||||
|
self.deprecation_notice("parity_lockedHardwareAccountsInfo");
|
||||||
|
|
||||||
|
self.accounts.locked_hardware_accounts().map_err(|e| errors::account("Error communicating with hardware wallet.", e))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_account(&self) -> Result<RpcH160> {
|
||||||
|
self.deprecation_notice("parity_defaultAccount");
|
||||||
|
|
||||||
|
Ok(self.accounts.default_account()
|
||||||
|
.map(Into::into)
|
||||||
|
.ok()
|
||||||
|
.unwrap_or_default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl ParityAccounts for ParityAccountsClient {
|
impl ParityAccounts for ParityAccountsClient {
|
||||||
fn all_accounts_info(&self) -> Result<BTreeMap<RpcH160, ExtAccountInfo>> {
|
fn all_accounts_info(&self) -> Result<BTreeMap<RpcH160, ExtAccountInfo>> {
|
||||||
|
self.deprecation_notice("parity_allAccountsInfo");
|
||||||
|
|
||||||
let info = self.accounts.accounts_info().map_err(|e| errors::account("Could not fetch account info.", e))?;
|
let info = self.accounts.accounts_info().map_err(|e| errors::account("Could not fetch account info.", e))?;
|
||||||
let other = self.accounts.addresses_info();
|
let other = self.accounts.addresses_info();
|
||||||
|
|
||||||
@ -75,6 +139,8 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn new_account_from_phrase(&self, phrase: String, pass: Password) -> Result<RpcH160> {
|
fn new_account_from_phrase(&self, phrase: String, pass: Password) -> Result<RpcH160> {
|
||||||
|
self.deprecation_notice("parity_newAccountFromPhrase");
|
||||||
|
|
||||||
let brain = Brain::new(phrase).generate().unwrap();
|
let brain = Brain::new(phrase).generate().unwrap();
|
||||||
self.accounts.insert_account(brain.secret().clone(), &pass)
|
self.accounts.insert_account(brain.secret().clone(), &pass)
|
||||||
.map(Into::into)
|
.map(Into::into)
|
||||||
@ -82,6 +148,8 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn new_account_from_wallet(&self, json: String, pass: Password) -> Result<RpcH160> {
|
fn new_account_from_wallet(&self, json: String, pass: Password) -> Result<RpcH160> {
|
||||||
|
self.deprecation_notice("parity_newAccountFromWallet");
|
||||||
|
|
||||||
self.accounts.import_presale(json.as_bytes(), &pass)
|
self.accounts.import_presale(json.as_bytes(), &pass)
|
||||||
.or_else(|_| self.accounts.import_wallet(json.as_bytes(), &pass, true))
|
.or_else(|_| self.accounts.import_wallet(json.as_bytes(), &pass, true))
|
||||||
.map(Into::into)
|
.map(Into::into)
|
||||||
@ -89,6 +157,8 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn new_account_from_secret(&self, secret: RpcH256, pass: Password) -> Result<RpcH160> {
|
fn new_account_from_secret(&self, secret: RpcH256, pass: Password) -> Result<RpcH160> {
|
||||||
|
self.deprecation_notice("parity_newAccountFromSecret");
|
||||||
|
|
||||||
let secret = Secret::from_unsafe_slice(&secret.0)
|
let secret = Secret::from_unsafe_slice(&secret.0)
|
||||||
.map_err(|e| errors::account("Could not create account.", e))?;
|
.map_err(|e| errors::account("Could not create account.", e))?;
|
||||||
self.accounts.insert_account(secret, &pass)
|
self.accounts.insert_account(secret, &pass)
|
||||||
@ -97,6 +167,8 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn test_password(&self, account: RpcH160, password: Password) -> Result<bool> {
|
fn test_password(&self, account: RpcH160, password: Password) -> Result<bool> {
|
||||||
|
self.deprecation_notice("parity_testPassword");
|
||||||
|
|
||||||
let account: Address = account.into();
|
let account: Address = account.into();
|
||||||
|
|
||||||
self.accounts
|
self.accounts
|
||||||
@ -105,6 +177,8 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn change_password(&self, account: RpcH160, password: Password, new_password: Password) -> Result<bool> {
|
fn change_password(&self, account: RpcH160, password: Password, new_password: Password) -> Result<bool> {
|
||||||
|
self.deprecation_notice("parity_changePassword");
|
||||||
|
|
||||||
let account: Address = account.into();
|
let account: Address = account.into();
|
||||||
self.accounts
|
self.accounts
|
||||||
.change_password(&account, password, new_password)
|
.change_password(&account, password, new_password)
|
||||||
@ -113,6 +187,8 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn kill_account(&self, account: RpcH160, password: Password) -> Result<bool> {
|
fn kill_account(&self, account: RpcH160, password: Password) -> Result<bool> {
|
||||||
|
self.deprecation_notice("parity_killAccount");
|
||||||
|
|
||||||
let account: Address = account.into();
|
let account: Address = account.into();
|
||||||
self.accounts
|
self.accounts
|
||||||
.kill_account(&account, &password)
|
.kill_account(&account, &password)
|
||||||
@ -121,6 +197,8 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn remove_address(&self, addr: RpcH160) -> Result<bool> {
|
fn remove_address(&self, addr: RpcH160) -> Result<bool> {
|
||||||
|
self.deprecation_notice("parity_removeAddresss");
|
||||||
|
|
||||||
let addr: Address = addr.into();
|
let addr: Address = addr.into();
|
||||||
|
|
||||||
self.accounts.remove_address(addr);
|
self.accounts.remove_address(addr);
|
||||||
@ -128,6 +206,8 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn set_account_name(&self, addr: RpcH160, name: String) -> Result<bool> {
|
fn set_account_name(&self, addr: RpcH160, name: String) -> Result<bool> {
|
||||||
|
self.deprecation_notice("parity_setAccountName");
|
||||||
|
|
||||||
let addr: Address = addr.into();
|
let addr: Address = addr.into();
|
||||||
|
|
||||||
self.accounts.set_account_name(addr.clone(), name.clone())
|
self.accounts.set_account_name(addr.clone(), name.clone())
|
||||||
@ -136,6 +216,8 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn set_account_meta(&self, addr: RpcH160, meta: String) -> Result<bool> {
|
fn set_account_meta(&self, addr: RpcH160, meta: String) -> Result<bool> {
|
||||||
|
self.deprecation_notice("parity_setAccountMeta");
|
||||||
|
|
||||||
let addr: Address = addr.into();
|
let addr: Address = addr.into();
|
||||||
|
|
||||||
self.accounts.set_account_meta(addr.clone(), meta.clone())
|
self.accounts.set_account_meta(addr.clone(), meta.clone())
|
||||||
@ -144,6 +226,8 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn import_geth_accounts(&self, addresses: Vec<RpcH160>) -> Result<Vec<RpcH160>> {
|
fn import_geth_accounts(&self, addresses: Vec<RpcH160>) -> Result<Vec<RpcH160>> {
|
||||||
|
self.deprecation_notice("parity_importGethAccounts");
|
||||||
|
|
||||||
self.accounts
|
self.accounts
|
||||||
.import_geth_accounts(into_vec(addresses), false)
|
.import_geth_accounts(into_vec(addresses), false)
|
||||||
.map(into_vec)
|
.map(into_vec)
|
||||||
@ -151,10 +235,14 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn geth_accounts(&self) -> Result<Vec<RpcH160>> {
|
fn geth_accounts(&self) -> Result<Vec<RpcH160>> {
|
||||||
|
self.deprecation_notice("parity_listGethAccounts");
|
||||||
|
|
||||||
Ok(into_vec(self.accounts.list_geth_accounts(false)))
|
Ok(into_vec(self.accounts.list_geth_accounts(false)))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_vault(&self, name: String, password: Password) -> Result<bool> {
|
fn create_vault(&self, name: String, password: Password) -> Result<bool> {
|
||||||
|
self.deprecation_notice("parity_newVault");
|
||||||
|
|
||||||
self.accounts
|
self.accounts
|
||||||
.create_vault(&name, &password)
|
.create_vault(&name, &password)
|
||||||
.map_err(|e| errors::account("Could not create vault.", e))
|
.map_err(|e| errors::account("Could not create vault.", e))
|
||||||
@ -162,6 +250,8 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn open_vault(&self, name: String, password: Password) -> Result<bool> {
|
fn open_vault(&self, name: String, password: Password) -> Result<bool> {
|
||||||
|
self.deprecation_notice("parity_openVault");
|
||||||
|
|
||||||
self.accounts
|
self.accounts
|
||||||
.open_vault(&name, &password)
|
.open_vault(&name, &password)
|
||||||
.map_err(|e| errors::account("Could not open vault.", e))
|
.map_err(|e| errors::account("Could not open vault.", e))
|
||||||
@ -169,6 +259,8 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn close_vault(&self, name: String) -> Result<bool> {
|
fn close_vault(&self, name: String) -> Result<bool> {
|
||||||
|
self.deprecation_notice("parity_closeVault");
|
||||||
|
|
||||||
self.accounts
|
self.accounts
|
||||||
.close_vault(&name)
|
.close_vault(&name)
|
||||||
.map_err(|e| errors::account("Could not close vault.", e))
|
.map_err(|e| errors::account("Could not close vault.", e))
|
||||||
@ -176,18 +268,24 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn list_vaults(&self) -> Result<Vec<String>> {
|
fn list_vaults(&self) -> Result<Vec<String>> {
|
||||||
|
self.deprecation_notice("parity_listVaults");
|
||||||
|
|
||||||
self.accounts
|
self.accounts
|
||||||
.list_vaults()
|
.list_vaults()
|
||||||
.map_err(|e| errors::account("Could not list vaults.", e))
|
.map_err(|e| errors::account("Could not list vaults.", e))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn list_opened_vaults(&self) -> Result<Vec<String>> {
|
fn list_opened_vaults(&self) -> Result<Vec<String>> {
|
||||||
|
self.deprecation_notice("parity_listOpenedVaults");
|
||||||
|
|
||||||
self.accounts
|
self.accounts
|
||||||
.list_opened_vaults()
|
.list_opened_vaults()
|
||||||
.map_err(|e| errors::account("Could not list vaults.", e))
|
.map_err(|e| errors::account("Could not list vaults.", e))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn change_vault_password(&self, name: String, new_password: Password) -> Result<bool> {
|
fn change_vault_password(&self, name: String, new_password: Password) -> Result<bool> {
|
||||||
|
self.deprecation_notice("parity_changeVaultPassword");
|
||||||
|
|
||||||
self.accounts
|
self.accounts
|
||||||
.change_vault_password(&name, &new_password)
|
.change_vault_password(&name, &new_password)
|
||||||
.map_err(|e| errors::account("Could not change vault password.", e))
|
.map_err(|e| errors::account("Could not change vault password.", e))
|
||||||
@ -195,6 +293,8 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn change_vault(&self, address: RpcH160, new_vault: String) -> Result<bool> {
|
fn change_vault(&self, address: RpcH160, new_vault: String) -> Result<bool> {
|
||||||
|
self.deprecation_notice("parity_changeVault");
|
||||||
|
|
||||||
self.accounts
|
self.accounts
|
||||||
.change_vault(address.into(), &new_vault)
|
.change_vault(address.into(), &new_vault)
|
||||||
.map_err(|e| errors::account("Could not change vault.", e))
|
.map_err(|e| errors::account("Could not change vault.", e))
|
||||||
@ -202,12 +302,16 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn get_vault_meta(&self, name: String) -> Result<String> {
|
fn get_vault_meta(&self, name: String) -> Result<String> {
|
||||||
|
self.deprecation_notice("parity_getVaultMeta");
|
||||||
|
|
||||||
self.accounts
|
self.accounts
|
||||||
.get_vault_meta(&name)
|
.get_vault_meta(&name)
|
||||||
.map_err(|e| errors::account("Could not get vault metadata.", e))
|
.map_err(|e| errors::account("Could not get vault metadata.", e))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_vault_meta(&self, name: String, meta: String) -> Result<bool> {
|
fn set_vault_meta(&self, name: String, meta: String) -> Result<bool> {
|
||||||
|
self.deprecation_notice("parity_setVaultMeta");
|
||||||
|
|
||||||
self.accounts
|
self.accounts
|
||||||
.set_vault_meta(&name, &meta)
|
.set_vault_meta(&name, &meta)
|
||||||
.map_err(|e| errors::account("Could not update vault metadata.", e))
|
.map_err(|e| errors::account("Could not update vault metadata.", e))
|
||||||
@ -215,6 +319,8 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn derive_key_index(&self, addr: RpcH160, password: Password, derivation: DeriveHierarchical, save_as_account: bool) -> Result<RpcH160> {
|
fn derive_key_index(&self, addr: RpcH160, password: Password, derivation: DeriveHierarchical, save_as_account: bool) -> Result<RpcH160> {
|
||||||
|
self.deprecation_notice("parity_deriveAddressIndex");
|
||||||
|
|
||||||
let addr: Address = addr.into();
|
let addr: Address = addr.into();
|
||||||
self.accounts
|
self.accounts
|
||||||
.derive_account(
|
.derive_account(
|
||||||
@ -228,6 +334,8 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn derive_key_hash(&self, addr: RpcH160, password: Password, derivation: DeriveHash, save_as_account: bool) -> Result<RpcH160> {
|
fn derive_key_hash(&self, addr: RpcH160, password: Password, derivation: DeriveHash, save_as_account: bool) -> Result<RpcH160> {
|
||||||
|
self.deprecation_notice("parity_deriveAddressHash");
|
||||||
|
|
||||||
let addr: Address = addr.into();
|
let addr: Address = addr.into();
|
||||||
self.accounts
|
self.accounts
|
||||||
.derive_account(
|
.derive_account(
|
||||||
@ -241,6 +349,8 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn export_account(&self, addr: RpcH160, password: Password) -> Result<KeyFile> {
|
fn export_account(&self, addr: RpcH160, password: Password) -> Result<KeyFile> {
|
||||||
|
self.deprecation_notice("parity_exportAccount");
|
||||||
|
|
||||||
let addr = addr.into();
|
let addr = addr.into();
|
||||||
self.accounts
|
self.accounts
|
||||||
.export_account(
|
.export_account(
|
||||||
@ -252,6 +362,8 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn sign_message(&self, addr: RpcH160, password: Password, message: RpcH256) -> Result<RpcH520> {
|
fn sign_message(&self, addr: RpcH160, password: Password, message: RpcH256) -> Result<RpcH520> {
|
||||||
|
self.deprecation_notice("parity_signMessage");
|
||||||
|
|
||||||
self.accounts
|
self.accounts
|
||||||
.sign(
|
.sign(
|
||||||
addr.into(),
|
addr.into(),
|
||||||
@ -263,6 +375,8 @@ impl ParityAccounts for ParityAccountsClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn hardware_pin_matrix_ack(&self, path: String, pin: String) -> Result<bool> {
|
fn hardware_pin_matrix_ack(&self, path: String, pin: String) -> Result<bool> {
|
||||||
|
self.deprecation_notice("parity_hardwarePinMatrixAck");
|
||||||
|
|
||||||
self.accounts.hardware_pin_matrix_ack(&path, &pin).map_err(|e| errors::account("Error communicating with hardware wallet.", e))
|
self.accounts.hardware_pin_matrix_ack(&path, &pin).map_err(|e| errors::account("Error communicating with hardware wallet.", e))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -20,10 +20,12 @@ use std::sync::Arc;
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use ethcore::client::{BlockChainClient, Mode};
|
use ethcore::client::{BlockChainClient, Mode};
|
||||||
use ethcore::miner::MinerService;
|
use ethcore::miner::{self, MinerService};
|
||||||
use sync::ManageNetwork;
|
use ethereum_types::H256 as EthH256;
|
||||||
|
use ethkey;
|
||||||
use fetch::{self, Fetch};
|
use fetch::{self, Fetch};
|
||||||
use hash::keccak_buffer;
|
use hash::keccak_buffer;
|
||||||
|
use sync::ManageNetwork;
|
||||||
use updater::{Service as UpdateService};
|
use updater::{Service as UpdateService};
|
||||||
|
|
||||||
use jsonrpc_core::{BoxFuture, Result};
|
use jsonrpc_core::{BoxFuture, Result};
|
||||||
@ -32,6 +34,53 @@ use v1::helpers::errors;
|
|||||||
use v1::traits::ParitySet;
|
use v1::traits::ParitySet;
|
||||||
use v1::types::{Bytes, H160, H256, U256, ReleaseInfo, Transaction};
|
use v1::types::{Bytes, H160, H256, U256, ReleaseInfo, Transaction};
|
||||||
|
|
||||||
|
#[cfg(any(test, feature = "accounts"))]
|
||||||
|
pub mod accounts {
|
||||||
|
use super::*;
|
||||||
|
use accounts::AccountProvider;
|
||||||
|
use v1::traits::ParitySetAccounts;
|
||||||
|
use v1::helpers::deprecated::DeprecationNotice;
|
||||||
|
use v1::helpers::engine_signer::EngineSigner;
|
||||||
|
|
||||||
|
/// Parity-specific account-touching RPC interfaces.
|
||||||
|
pub struct ParitySetAccountsClient<M> {
|
||||||
|
miner: Arc<M>,
|
||||||
|
accounts: Arc<AccountProvider>,
|
||||||
|
deprecation_notice: DeprecationNotice,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<M> ParitySetAccountsClient<M> {
|
||||||
|
/// Creates new ParitySetAccountsClient
|
||||||
|
pub fn new(
|
||||||
|
accounts: &Arc<AccountProvider>,
|
||||||
|
miner: &Arc<M>,
|
||||||
|
) -> Self {
|
||||||
|
ParitySetAccountsClient {
|
||||||
|
accounts: accounts.clone(),
|
||||||
|
miner: miner.clone(),
|
||||||
|
deprecation_notice: Default::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<M: MinerService + 'static> ParitySetAccounts for ParitySetAccountsClient<M> {
|
||||||
|
fn set_engine_signer(&self, address: H160, password: String) -> Result<bool> {
|
||||||
|
self.deprecation_notice.print(
|
||||||
|
"parity_setEngineSigner",
|
||||||
|
"use `parity_setEngineSignerSecret` instead. See #9997 for context."
|
||||||
|
);
|
||||||
|
|
||||||
|
let signer = Box::new(EngineSigner::new(
|
||||||
|
self.accounts.clone(),
|
||||||
|
address.clone().into(),
|
||||||
|
password.into(),
|
||||||
|
));
|
||||||
|
self.miner.set_author(miner::Author::Sealer(signer));
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Parity-specific rpc interface for operations altering the settings.
|
/// Parity-specific rpc interface for operations altering the settings.
|
||||||
pub struct ParitySetClient<C, M, U, F = fetch::Client> {
|
pub struct ParitySetClient<C, M, U, F = fetch::Client> {
|
||||||
client: Arc<C>,
|
client: Arc<C>,
|
||||||
@ -57,7 +106,7 @@ impl<C, M, U, F> ParitySetClient<C, M, U, F>
|
|||||||
miner: miner.clone(),
|
miner: miner.clone(),
|
||||||
updater: updater.clone(),
|
updater: updater.clone(),
|
||||||
net: net.clone(),
|
net: net.clone(),
|
||||||
fetch: fetch,
|
fetch,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -104,12 +153,14 @@ impl<C, M, U, F> ParitySet for ParitySetClient<C, M, U, F> where
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn set_author(&self, address: H160) -> Result<bool> {
|
fn set_author(&self, address: H160) -> Result<bool> {
|
||||||
self.miner.set_author(address.into(), None).map_err(Into::into).map_err(errors::password)?;
|
self.miner.set_author(miner::Author::External(address.into()));
|
||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_engine_signer(&self, address: H160, password: String) -> Result<bool> {
|
fn set_engine_signer_secret(&self, secret: H256) -> Result<bool> {
|
||||||
self.miner.set_author(address.into(), Some(password.into())).map_err(Into::into).map_err(errors::password)?;
|
let secret: EthH256 = secret.into();
|
||||||
|
let keypair = ethkey::KeyPair::from_secret(secret.into()).map_err(|e| errors::account("Invalid secret", e))?;
|
||||||
|
self.miner.set_author(miner::Author::Sealer(ethcore::engines::signer::from_keypair(keypair)));
|
||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -18,17 +18,20 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use accounts::AccountProvider;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use ethcore::account_provider::AccountProvider;
|
use eip_712::{EIP712, hash_structured_data};
|
||||||
|
|
||||||
use types::transaction::{PendingTransaction, SignedTransaction};
|
|
||||||
use ethereum_types::{H520, U128, Address};
|
use ethereum_types::{H520, U128, Address};
|
||||||
use ethkey::{public_to_address, recover, Signature};
|
use ethkey::{public_to_address, recover, Signature};
|
||||||
|
use types::transaction::{PendingTransaction, SignedTransaction};
|
||||||
|
|
||||||
use jsonrpc_core::{BoxFuture, Result};
|
|
||||||
use jsonrpc_core::futures::{future, Future};
|
use jsonrpc_core::futures::{future, Future};
|
||||||
use v1::helpers::{errors, eip191};
|
use jsonrpc_core::types::Value;
|
||||||
|
use jsonrpc_core::{BoxFuture, Result};
|
||||||
|
use v1::helpers::deprecated::{self, DeprecationNotice};
|
||||||
use v1::helpers::dispatch::{self, eth_data_hash, Dispatcher, SignWith, PostSign, WithToken};
|
use v1::helpers::dispatch::{self, eth_data_hash, Dispatcher, SignWith, PostSign, WithToken};
|
||||||
|
use v1::helpers::{errors, eip191};
|
||||||
|
use v1::metadata::Metadata;
|
||||||
use v1::traits::Personal;
|
use v1::traits::Personal;
|
||||||
use v1::types::{
|
use v1::types::{
|
||||||
H160 as RpcH160, H256 as RpcH256, H520 as RpcH520, U128 as RpcU128,
|
H160 as RpcH160, H256 as RpcH256, H520 as RpcH520, U128 as RpcU128,
|
||||||
@ -39,9 +42,6 @@ use v1::types::{
|
|||||||
RichRawTransaction as RpcRichRawTransaction,
|
RichRawTransaction as RpcRichRawTransaction,
|
||||||
EIP191Version,
|
EIP191Version,
|
||||||
};
|
};
|
||||||
use v1::metadata::Metadata;
|
|
||||||
use eip_712::{EIP712, hash_structured_data};
|
|
||||||
use jsonrpc_core::types::Value;
|
|
||||||
|
|
||||||
/// Account management (personal) rpc implementation.
|
/// Account management (personal) rpc implementation.
|
||||||
pub struct PersonalClient<D: Dispatcher> {
|
pub struct PersonalClient<D: Dispatcher> {
|
||||||
@ -49,6 +49,7 @@ pub struct PersonalClient<D: Dispatcher> {
|
|||||||
dispatcher: D,
|
dispatcher: D,
|
||||||
allow_perm_unlock: bool,
|
allow_perm_unlock: bool,
|
||||||
allow_experimental_rpcs: bool,
|
allow_experimental_rpcs: bool,
|
||||||
|
deprecation_notice: DeprecationNotice,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<D: Dispatcher> PersonalClient<D> {
|
impl<D: Dispatcher> PersonalClient<D> {
|
||||||
@ -64,6 +65,7 @@ impl<D: Dispatcher> PersonalClient<D> {
|
|||||||
dispatcher,
|
dispatcher,
|
||||||
allow_perm_unlock,
|
allow_perm_unlock,
|
||||||
allow_experimental_rpcs,
|
allow_experimental_rpcs,
|
||||||
|
deprecation_notice: DeprecationNotice::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -94,9 +96,10 @@ impl<D: Dispatcher + 'static> PersonalClient<D> {
|
|||||||
Err(e) => return Box::new(future::err(e)),
|
Err(e) => return Box::new(future::err(e)),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let accounts = Arc::new(dispatch::Signer::new(accounts)) as _;
|
||||||
Box::new(dispatcher.fill_optional_fields(request.into(), default, false)
|
Box::new(dispatcher.fill_optional_fields(request.into(), default, false)
|
||||||
.and_then(move |filled| {
|
.and_then(move |filled| {
|
||||||
dispatcher.sign(accounts, filled, SignWith::Password(password.into()), post_sign)
|
dispatcher.sign(filled, &accounts, SignWith::Password(password.into()), post_sign)
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -106,17 +109,23 @@ impl<D: Dispatcher + 'static> Personal for PersonalClient<D> {
|
|||||||
type Metadata = Metadata;
|
type Metadata = Metadata;
|
||||||
|
|
||||||
fn accounts(&self) -> Result<Vec<RpcH160>> {
|
fn accounts(&self) -> Result<Vec<RpcH160>> {
|
||||||
|
self.deprecation_notice.print("personal_accounts", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
let accounts = self.accounts.accounts().map_err(|e| errors::account("Could not fetch accounts.", e))?;
|
let accounts = self.accounts.accounts().map_err(|e| errors::account("Could not fetch accounts.", e))?;
|
||||||
Ok(accounts.into_iter().map(Into::into).collect::<Vec<RpcH160>>())
|
Ok(accounts.into_iter().map(Into::into).collect::<Vec<RpcH160>>())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn new_account(&self, pass: String) -> Result<RpcH160> {
|
fn new_account(&self, pass: String) -> Result<RpcH160> {
|
||||||
|
self.deprecation_notice.print("personal_newAccount", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
self.accounts.new_account(&pass.into())
|
self.accounts.new_account(&pass.into())
|
||||||
.map(Into::into)
|
.map(Into::into)
|
||||||
.map_err(|e| errors::account("Could not create account.", e))
|
.map_err(|e| errors::account("Could not create account.", e))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn unlock_account(&self, account: RpcH160, account_pass: String, duration: Option<RpcU128>) -> Result<bool> {
|
fn unlock_account(&self, account: RpcH160, account_pass: String, duration: Option<RpcU128>) -> Result<bool> {
|
||||||
|
self.deprecation_notice.print("personal_unlockAccount", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
let account: Address = account.into();
|
let account: Address = account.into();
|
||||||
let store = self.accounts.clone();
|
let store = self.accounts.clone();
|
||||||
let duration = match duration {
|
let duration = match duration {
|
||||||
@ -149,14 +158,16 @@ impl<D: Dispatcher + 'static> Personal for PersonalClient<D> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn sign(&self, data: RpcBytes, account: RpcH160, password: String) -> BoxFuture<RpcH520> {
|
fn sign(&self, data: RpcBytes, account: RpcH160, password: String) -> BoxFuture<RpcH520> {
|
||||||
|
self.deprecation_notice.print("personal_sign", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
let dispatcher = self.dispatcher.clone();
|
let dispatcher = self.dispatcher.clone();
|
||||||
let accounts = self.accounts.clone();
|
let accounts = Arc::new(dispatch::Signer::new(self.accounts.clone())) as _;
|
||||||
|
|
||||||
let payload = RpcConfirmationPayload::EthSignMessage((account.clone(), data).into());
|
let payload = RpcConfirmationPayload::EthSignMessage((account.clone(), data).into());
|
||||||
|
|
||||||
Box::new(dispatch::from_rpc(payload, account.into(), &dispatcher)
|
Box::new(dispatch::from_rpc(payload, account.into(), &dispatcher)
|
||||||
.and_then(|payload| {
|
.and_then(move |payload| {
|
||||||
dispatch::execute(dispatcher, accounts, payload, dispatch::SignWith::Password(password.into()))
|
dispatch::execute(dispatcher, &accounts, payload, dispatch::SignWith::Password(password.into()))
|
||||||
})
|
})
|
||||||
.map(|v| v.into_value())
|
.map(|v| v.into_value())
|
||||||
.then(|res| match res {
|
.then(|res| match res {
|
||||||
@ -167,17 +178,19 @@ impl<D: Dispatcher + 'static> Personal for PersonalClient<D> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn sign_191(&self, version: EIP191Version, data: Value, account: RpcH160, password: String) -> BoxFuture<RpcH520> {
|
fn sign_191(&self, version: EIP191Version, data: Value, account: RpcH160, password: String) -> BoxFuture<RpcH520> {
|
||||||
|
self.deprecation_notice.print("personal_sign191", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
try_bf!(errors::require_experimental(self.allow_experimental_rpcs, "191"));
|
try_bf!(errors::require_experimental(self.allow_experimental_rpcs, "191"));
|
||||||
|
|
||||||
let data = try_bf!(eip191::hash_message(version, data));
|
let data = try_bf!(eip191::hash_message(version, data));
|
||||||
let dispatcher = self.dispatcher.clone();
|
let dispatcher = self.dispatcher.clone();
|
||||||
let accounts = self.accounts.clone();
|
let accounts = Arc::new(dispatch::Signer::new(self.accounts.clone())) as _;
|
||||||
|
|
||||||
let payload = RpcConfirmationPayload::EIP191SignMessage((account.clone(), data.into()).into());
|
let payload = RpcConfirmationPayload::EIP191SignMessage((account.clone(), data.into()).into());
|
||||||
|
|
||||||
Box::new(dispatch::from_rpc(payload, account.into(), &dispatcher)
|
Box::new(dispatch::from_rpc(payload, account.into(), &dispatcher)
|
||||||
.and_then(|payload| {
|
.and_then(move |payload| {
|
||||||
dispatch::execute(dispatcher, accounts, payload, dispatch::SignWith::Password(password.into()))
|
dispatch::execute(dispatcher, &accounts, payload, dispatch::SignWith::Password(password.into()))
|
||||||
})
|
})
|
||||||
.map(|v| v.into_value())
|
.map(|v| v.into_value())
|
||||||
.then(|res| match res {
|
.then(|res| match res {
|
||||||
@ -189,6 +202,8 @@ impl<D: Dispatcher + 'static> Personal for PersonalClient<D> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn sign_typed_data(&self, typed_data: EIP712, account: RpcH160, password: String) -> BoxFuture<RpcH520> {
|
fn sign_typed_data(&self, typed_data: EIP712, account: RpcH160, password: String) -> BoxFuture<RpcH520> {
|
||||||
|
self.deprecation_notice.print("personal_signTypedData", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
try_bf!(errors::require_experimental(self.allow_experimental_rpcs, "712"));
|
try_bf!(errors::require_experimental(self.allow_experimental_rpcs, "712"));
|
||||||
|
|
||||||
let data = match hash_structured_data(typed_data) {
|
let data = match hash_structured_data(typed_data) {
|
||||||
@ -196,13 +211,13 @@ impl<D: Dispatcher + 'static> Personal for PersonalClient<D> {
|
|||||||
Err(err) => return Box::new(future::err(errors::invalid_call_data(err.kind()))),
|
Err(err) => return Box::new(future::err(errors::invalid_call_data(err.kind()))),
|
||||||
};
|
};
|
||||||
let dispatcher = self.dispatcher.clone();
|
let dispatcher = self.dispatcher.clone();
|
||||||
let accounts = self.accounts.clone();
|
let accounts = Arc::new(dispatch::Signer::new(self.accounts.clone())) as _;
|
||||||
|
|
||||||
let payload = RpcConfirmationPayload::EIP191SignMessage((account.clone(), data.into()).into());
|
let payload = RpcConfirmationPayload::EIP191SignMessage((account.clone(), data.into()).into());
|
||||||
|
|
||||||
Box::new(dispatch::from_rpc(payload, account.into(), &dispatcher)
|
Box::new(dispatch::from_rpc(payload, account.into(), &dispatcher)
|
||||||
.and_then(|payload| {
|
.and_then(move |payload| {
|
||||||
dispatch::execute(dispatcher, accounts, payload, dispatch::SignWith::Password(password.into()))
|
dispatch::execute(dispatcher, &accounts, payload, dispatch::SignWith::Password(password.into()))
|
||||||
})
|
})
|
||||||
.map(|v| v.into_value())
|
.map(|v| v.into_value())
|
||||||
.then(|res| match res {
|
.then(|res| match res {
|
||||||
@ -229,6 +244,8 @@ impl<D: Dispatcher + 'static> Personal for PersonalClient<D> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn sign_transaction(&self, meta: Metadata, request: TransactionRequest, password: String) -> BoxFuture<RpcRichRawTransaction> {
|
fn sign_transaction(&self, meta: Metadata, request: TransactionRequest, password: String) -> BoxFuture<RpcRichRawTransaction> {
|
||||||
|
self.deprecation_notice.print("personal_signTransaction", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
let condition = request.condition.clone().map(Into::into);
|
let condition = request.condition.clone().map(Into::into);
|
||||||
let dispatcher = self.dispatcher.clone();
|
let dispatcher = self.dispatcher.clone();
|
||||||
Box::new(self.do_sign_transaction(meta, request, password, ())
|
Box::new(self.do_sign_transaction(meta, request, password, ())
|
||||||
@ -237,24 +254,27 @@ impl<D: Dispatcher + 'static> Personal for PersonalClient<D> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn send_transaction(&self, meta: Metadata, request: TransactionRequest, password: String) -> BoxFuture<RpcH256> {
|
fn send_transaction(&self, meta: Metadata, request: TransactionRequest, password: String) -> BoxFuture<RpcH256> {
|
||||||
|
self.deprecation_notice.print("personal_sendTransaction", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
let condition = request.condition.clone().map(Into::into);
|
let condition = request.condition.clone().map(Into::into);
|
||||||
let dispatcher = self.dispatcher.clone();
|
let dispatcher = self.dispatcher.clone();
|
||||||
Box::new(self.do_sign_transaction(meta, request, password, move |signed: WithToken<SignedTransaction>| {
|
Box::new(
|
||||||
|
self.do_sign_transaction(meta, request, password, move |signed: WithToken<SignedTransaction>| {
|
||||||
dispatcher.dispatch_transaction(
|
dispatcher.dispatch_transaction(
|
||||||
PendingTransaction::new(
|
PendingTransaction::new(
|
||||||
signed.into_value(),
|
signed.into_value(),
|
||||||
condition
|
condition
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
})
|
}).and_then(|hash| {
|
||||||
.and_then(|hash| {
|
|
||||||
Ok(RpcH256::from(hash))
|
Ok(RpcH256::from(hash))
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sign_and_send_transaction(&self, meta: Metadata, request: TransactionRequest, password: String) -> BoxFuture<RpcH256> {
|
fn sign_and_send_transaction(&self, meta: Metadata, request: TransactionRequest, password: String) -> BoxFuture<RpcH256> {
|
||||||
warn!("Using deprecated personal_signAndSendTransaction, use personal_sendTransaction instead.");
|
self.deprecation_notice.print("personal_signAndSendTransaction", Some("use personal_sendTransaction instead."));
|
||||||
|
|
||||||
self.send_transaction(meta, request, password)
|
self.send_transaction(meta, request, password)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -21,7 +21,7 @@ use std::sync::Arc;
|
|||||||
|
|
||||||
use crypto::DEFAULT_MAC;
|
use crypto::DEFAULT_MAC;
|
||||||
use ethkey::Secret;
|
use ethkey::Secret;
|
||||||
use ethcore::account_provider::AccountProvider;
|
use accounts::AccountProvider;
|
||||||
|
|
||||||
use jsonrpc_core::Result;
|
use jsonrpc_core::Result;
|
||||||
use v1::helpers::errors;
|
use v1::helpers::errors;
|
||||||
|
@ -18,7 +18,6 @@
|
|||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use ethcore::account_provider::AccountProvider;
|
|
||||||
use ethkey;
|
use ethkey;
|
||||||
use parity_runtime::Executor;
|
use parity_runtime::Executor;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
@ -29,8 +28,10 @@ use jsonrpc_core::{Result, BoxFuture, Error};
|
|||||||
use jsonrpc_core::futures::{future, Future, IntoFuture};
|
use jsonrpc_core::futures::{future, Future, IntoFuture};
|
||||||
use jsonrpc_core::futures::future::Either;
|
use jsonrpc_core::futures::future::Either;
|
||||||
use jsonrpc_pubsub::{SubscriptionId, typed::{Sink, Subscriber}};
|
use jsonrpc_pubsub::{SubscriptionId, typed::{Sink, Subscriber}};
|
||||||
|
use v1::helpers::deprecated::{self, DeprecationNotice};
|
||||||
use v1::helpers::dispatch::{self, Dispatcher, WithToken, eth_data_hash};
|
use v1::helpers::dispatch::{self, Dispatcher, WithToken, eth_data_hash};
|
||||||
use v1::helpers::{errors, SignerService, SigningQueue, ConfirmationPayload, FilledTransactionRequest, Subscribers};
|
use v1::helpers::{errors, ConfirmationPayload, FilledTransactionRequest, Subscribers};
|
||||||
|
use v1::helpers::external_signer::{SigningQueue, SignerService};
|
||||||
use v1::metadata::Metadata;
|
use v1::metadata::Metadata;
|
||||||
use v1::traits::Signer;
|
use v1::traits::Signer;
|
||||||
use v1::types::{TransactionModification, ConfirmationRequest, ConfirmationResponse, ConfirmationResponseWithToken, U256, Bytes};
|
use v1::types::{TransactionModification, ConfirmationRequest, ConfirmationResponse, ConfirmationResponseWithToken, U256, Bytes};
|
||||||
@ -38,15 +39,16 @@ use v1::types::{TransactionModification, ConfirmationRequest, ConfirmationRespon
|
|||||||
/// Transactions confirmation (personal) rpc implementation.
|
/// Transactions confirmation (personal) rpc implementation.
|
||||||
pub struct SignerClient<D: Dispatcher> {
|
pub struct SignerClient<D: Dispatcher> {
|
||||||
signer: Arc<SignerService>,
|
signer: Arc<SignerService>,
|
||||||
accounts: Arc<AccountProvider>,
|
accounts: Arc<dispatch::Accounts>,
|
||||||
dispatcher: D,
|
dispatcher: D,
|
||||||
subscribers: Arc<Mutex<Subscribers<Sink<Vec<ConfirmationRequest>>>>>,
|
subscribers: Arc<Mutex<Subscribers<Sink<Vec<ConfirmationRequest>>>>>,
|
||||||
|
deprecation_notice: DeprecationNotice,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<D: Dispatcher + 'static> SignerClient<D> {
|
impl<D: Dispatcher + 'static> SignerClient<D> {
|
||||||
/// Create new instance of signer client.
|
/// Create new instance of signer client.
|
||||||
pub fn new(
|
pub fn new(
|
||||||
store: &Arc<AccountProvider>,
|
accounts: Arc<dispatch::Accounts>,
|
||||||
dispatcher: D,
|
dispatcher: D,
|
||||||
signer: &Arc<SignerService>,
|
signer: &Arc<SignerService>,
|
||||||
executor: Executor,
|
executor: Executor,
|
||||||
@ -70,14 +72,15 @@ impl<D: Dispatcher + 'static> SignerClient<D> {
|
|||||||
|
|
||||||
SignerClient {
|
SignerClient {
|
||||||
signer: signer.clone(),
|
signer: signer.clone(),
|
||||||
accounts: store.clone(),
|
accounts: accounts.clone(),
|
||||||
dispatcher,
|
dispatcher,
|
||||||
subscribers,
|
subscribers,
|
||||||
|
deprecation_notice: Default::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn confirm_internal<F, T>(&self, id: U256, modification: TransactionModification, f: F) -> BoxFuture<WithToken<ConfirmationResponse>> where
|
fn confirm_internal<F, T>(&self, id: U256, modification: TransactionModification, f: F) -> BoxFuture<WithToken<ConfirmationResponse>> where
|
||||||
F: FnOnce(D, Arc<AccountProvider>, ConfirmationPayload) -> T,
|
F: FnOnce(D, &Arc<dispatch::Accounts>, ConfirmationPayload) -> T,
|
||||||
T: IntoFuture<Item=WithToken<ConfirmationResponse>, Error=Error>,
|
T: IntoFuture<Item=WithToken<ConfirmationResponse>, Error=Error>,
|
||||||
T::Future: Send + 'static
|
T::Future: Send + 'static
|
||||||
{
|
{
|
||||||
@ -104,7 +107,7 @@ impl<D: Dispatcher + 'static> SignerClient<D> {
|
|||||||
request.condition = condition.clone().map(Into::into);
|
request.condition = condition.clone().map(Into::into);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let fut = f(dispatcher, self.accounts.clone(), payload);
|
let fut = f(dispatcher, &self.accounts, payload);
|
||||||
Either::A(fut.into_future().then(move |result| {
|
Either::A(fut.into_future().then(move |result| {
|
||||||
// Execute
|
// Execute
|
||||||
if let Ok(ref response) = result {
|
if let Ok(ref response) = result {
|
||||||
@ -155,6 +158,8 @@ impl<D: Dispatcher + 'static> Signer for SignerClient<D> {
|
|||||||
type Metadata = Metadata;
|
type Metadata = Metadata;
|
||||||
|
|
||||||
fn requests_to_confirm(&self) -> Result<Vec<ConfirmationRequest>> {
|
fn requests_to_confirm(&self) -> Result<Vec<ConfirmationRequest>> {
|
||||||
|
self.deprecation_notice.print("signer_requestsToConfirm", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
Ok(self.signer.requests()
|
Ok(self.signer.requests()
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(Into::into)
|
.map(Into::into)
|
||||||
@ -167,6 +172,8 @@ impl<D: Dispatcher + 'static> Signer for SignerClient<D> {
|
|||||||
fn confirm_request(&self, id: U256, modification: TransactionModification, pass: String)
|
fn confirm_request(&self, id: U256, modification: TransactionModification, pass: String)
|
||||||
-> BoxFuture<ConfirmationResponse>
|
-> BoxFuture<ConfirmationResponse>
|
||||||
{
|
{
|
||||||
|
self.deprecation_notice.print("signer_confirmRequest", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
Box::new(self.confirm_internal(id, modification, move |dis, accounts, payload| {
|
Box::new(self.confirm_internal(id, modification, move |dis, accounts, payload| {
|
||||||
dispatch::execute(dis, accounts, payload, dispatch::SignWith::Password(pass.into()))
|
dispatch::execute(dis, accounts, payload, dispatch::SignWith::Password(pass.into()))
|
||||||
}).map(|v| v.into_value()))
|
}).map(|v| v.into_value()))
|
||||||
@ -175,6 +182,8 @@ impl<D: Dispatcher + 'static> Signer for SignerClient<D> {
|
|||||||
fn confirm_request_with_token(&self, id: U256, modification: TransactionModification, token: String)
|
fn confirm_request_with_token(&self, id: U256, modification: TransactionModification, token: String)
|
||||||
-> BoxFuture<ConfirmationResponseWithToken>
|
-> BoxFuture<ConfirmationResponseWithToken>
|
||||||
{
|
{
|
||||||
|
self.deprecation_notice.print("signer_confirmRequestWithToken", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
Box::new(self.confirm_internal(id, modification, move |dis, accounts, payload| {
|
Box::new(self.confirm_internal(id, modification, move |dis, accounts, payload| {
|
||||||
dispatch::execute(dis, accounts, payload, dispatch::SignWith::Token(token.into()))
|
dispatch::execute(dis, accounts, payload, dispatch::SignWith::Token(token.into()))
|
||||||
}).and_then(|v| match v {
|
}).and_then(|v| match v {
|
||||||
@ -187,6 +196,8 @@ impl<D: Dispatcher + 'static> Signer for SignerClient<D> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn confirm_request_raw(&self, id: U256, bytes: Bytes) -> Result<ConfirmationResponse> {
|
fn confirm_request_raw(&self, id: U256, bytes: Bytes) -> Result<ConfirmationResponse> {
|
||||||
|
self.deprecation_notice.print("signer_confirmRequestRaw", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
let id = id.into();
|
let id = id.into();
|
||||||
|
|
||||||
self.signer.take(&id).map(|sender| {
|
self.signer.take(&id).map(|sender| {
|
||||||
@ -237,20 +248,22 @@ impl<D: Dispatcher + 'static> Signer for SignerClient<D> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn reject_request(&self, id: U256) -> Result<bool> {
|
fn reject_request(&self, id: U256) -> Result<bool> {
|
||||||
|
self.deprecation_notice.print("signer_rejectRequest", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
let res = self.signer.take(&id.into()).map(|sender| self.signer.request_rejected(sender));
|
let res = self.signer.take(&id.into()).map(|sender| self.signer.request_rejected(sender));
|
||||||
Ok(res.is_some())
|
Ok(res.is_some())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn generate_token(&self) -> Result<String> {
|
fn generate_token(&self) -> Result<String> {
|
||||||
|
self.deprecation_notice.print("signer_generateAuthorizationToken", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
self.signer.generate_token()
|
self.signer.generate_token()
|
||||||
.map_err(|e| errors::token(e))
|
.map_err(|e| errors::token(e))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn generate_web_proxy_token(&self, domain: String) -> Result<String> {
|
|
||||||
Ok(self.signer.generate_web_proxy_access_token(domain.into()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn subscribe_pending(&self, _meta: Self::Metadata, sub: Subscriber<Vec<ConfirmationRequest>>) {
|
fn subscribe_pending(&self, _meta: Self::Metadata, sub: Subscriber<Vec<ConfirmationRequest>>) {
|
||||||
|
self.deprecation_notice.print("signer_subscribePending", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
self.subscribers.lock().push(sub)
|
self.subscribers.lock().push(sub)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -21,17 +21,18 @@ use transient_hashmap::TransientHashMap;
|
|||||||
use ethereum_types::U256;
|
use ethereum_types::U256;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
|
|
||||||
use ethcore::account_provider::AccountProvider;
|
|
||||||
|
|
||||||
use jsonrpc_core::{BoxFuture, Result, Error};
|
use jsonrpc_core::{BoxFuture, Result, Error};
|
||||||
use jsonrpc_core::futures::{future, Future, Poll, Async};
|
use jsonrpc_core::futures::{future, Future, Poll, Async};
|
||||||
use jsonrpc_core::futures::future::Either;
|
use jsonrpc_core::futures::future::Either;
|
||||||
use v1::helpers::{
|
|
||||||
errors, DefaultAccount, SignerService, SigningQueue,
|
use v1::helpers::deprecated::{self, DeprecationNotice};
|
||||||
|
use v1::helpers::dispatch::{self, Dispatcher};
|
||||||
|
use v1::helpers::errors;
|
||||||
|
use v1::helpers::external_signer::{
|
||||||
|
SignerService, SigningQueue,
|
||||||
ConfirmationReceiver as RpcConfirmationReceiver,
|
ConfirmationReceiver as RpcConfirmationReceiver,
|
||||||
ConfirmationResult as RpcConfirmationResult,
|
ConfirmationResult as RpcConfirmationResult,
|
||||||
};
|
};
|
||||||
use v1::helpers::dispatch::{self, Dispatcher};
|
|
||||||
use v1::metadata::Metadata;
|
use v1::metadata::Metadata;
|
||||||
use v1::traits::{EthSigning, ParitySigning};
|
use v1::traits::{EthSigning, ParitySigning};
|
||||||
use v1::types::{
|
use v1::types::{
|
||||||
@ -89,38 +90,37 @@ fn schedule(executor: Executor,
|
|||||||
/// Implementation of functions that require signing when no trusted signer is used.
|
/// Implementation of functions that require signing when no trusted signer is used.
|
||||||
pub struct SigningQueueClient<D> {
|
pub struct SigningQueueClient<D> {
|
||||||
signer: Arc<SignerService>,
|
signer: Arc<SignerService>,
|
||||||
accounts: Arc<AccountProvider>,
|
accounts: Arc<dispatch::Accounts>,
|
||||||
dispatcher: D,
|
dispatcher: D,
|
||||||
executor: Executor,
|
executor: Executor,
|
||||||
// None here means that the request hasn't yet been confirmed
|
// None here means that the request hasn't yet been confirmed
|
||||||
confirmations: Arc<Mutex<TransientHashMap<U256, Option<RpcConfirmationResult>>>>,
|
confirmations: Arc<Mutex<TransientHashMap<U256, Option<RpcConfirmationResult>>>>,
|
||||||
|
deprecation_notice: DeprecationNotice,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<D: Dispatcher + 'static> SigningQueueClient<D> {
|
impl<D: Dispatcher + 'static> SigningQueueClient<D> {
|
||||||
/// Creates a new signing queue client given shared signing queue.
|
/// Creates a new signing queue client given shared signing queue.
|
||||||
pub fn new(signer: &Arc<SignerService>, dispatcher: D, executor: Executor, accounts: &Arc<AccountProvider>) -> Self {
|
pub fn new(signer: &Arc<SignerService>, dispatcher: D, executor: Executor, accounts: &Arc<dispatch::Accounts>) -> Self {
|
||||||
SigningQueueClient {
|
SigningQueueClient {
|
||||||
signer: signer.clone(),
|
signer: signer.clone(),
|
||||||
accounts: accounts.clone(),
|
accounts: accounts.clone(),
|
||||||
dispatcher,
|
dispatcher,
|
||||||
executor,
|
executor,
|
||||||
confirmations: Arc::new(Mutex::new(TransientHashMap::new(MAX_PENDING_DURATION_SEC))),
|
confirmations: Arc::new(Mutex::new(TransientHashMap::new(MAX_PENDING_DURATION_SEC))),
|
||||||
|
deprecation_notice: Default::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn dispatch(&self, payload: RpcConfirmationPayload, default_account: DefaultAccount, origin: Origin) -> BoxFuture<DispatchResult> {
|
fn dispatch(&self, payload: RpcConfirmationPayload, origin: Origin) -> BoxFuture<DispatchResult> {
|
||||||
|
let default_account = self.accounts.default_account();
|
||||||
let accounts = self.accounts.clone();
|
let accounts = self.accounts.clone();
|
||||||
let default_account = match default_account {
|
|
||||||
DefaultAccount::Provided(acc) => acc,
|
|
||||||
};
|
|
||||||
|
|
||||||
let dispatcher = self.dispatcher.clone();
|
let dispatcher = self.dispatcher.clone();
|
||||||
let signer = self.signer.clone();
|
let signer = self.signer.clone();
|
||||||
Box::new(dispatch::from_rpc(payload, default_account, &dispatcher)
|
Box::new(dispatch::from_rpc(payload, default_account, &dispatcher)
|
||||||
.and_then(move |payload| {
|
.and_then(move |payload| {
|
||||||
let sender = payload.sender();
|
let sender = payload.sender();
|
||||||
if accounts.is_unlocked(&sender) {
|
if accounts.is_unlocked(&sender) {
|
||||||
Either::A(dispatch::execute(dispatcher, accounts, payload, dispatch::SignWith::Nothing)
|
Either::A(dispatch::execute(dispatcher, &accounts, payload, dispatch::SignWith::Nothing)
|
||||||
.map(|v| v.into_value())
|
.map(|v| v.into_value())
|
||||||
.map(DispatchResult::Value))
|
.map(DispatchResult::Value))
|
||||||
} else {
|
} else {
|
||||||
@ -138,17 +138,18 @@ impl<D: Dispatcher + 'static> ParitySigning for SigningQueueClient<D> {
|
|||||||
type Metadata = Metadata;
|
type Metadata = Metadata;
|
||||||
|
|
||||||
fn compose_transaction(&self, _meta: Metadata, transaction: RpcTransactionRequest) -> BoxFuture<RpcTransactionRequest> {
|
fn compose_transaction(&self, _meta: Metadata, transaction: RpcTransactionRequest) -> BoxFuture<RpcTransactionRequest> {
|
||||||
let default_account = self.accounts.default_account().ok().unwrap_or_default();
|
let default_account = self.accounts.default_account();
|
||||||
Box::new(self.dispatcher.fill_optional_fields(transaction.into(), default_account, true).map(Into::into))
|
Box::new(self.dispatcher.fill_optional_fields(transaction.into(), default_account, true).map(Into::into))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn post_sign(&self, meta: Metadata, address: RpcH160, data: RpcBytes) -> BoxFuture<RpcEither<RpcU256, RpcConfirmationResponse>> {
|
fn post_sign(&self, meta: Metadata, address: RpcH160, data: RpcBytes) -> BoxFuture<RpcEither<RpcU256, RpcConfirmationResponse>> {
|
||||||
|
self.deprecation_notice.print("parity_postSign", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
let executor = self.executor.clone();
|
let executor = self.executor.clone();
|
||||||
let confirmations = self.confirmations.clone();
|
let confirmations = self.confirmations.clone();
|
||||||
|
|
||||||
Box::new(self.dispatch(
|
Box::new(self.dispatch(
|
||||||
RpcConfirmationPayload::EthSignMessage((address.clone(), data).into()),
|
RpcConfirmationPayload::EthSignMessage((address.clone(), data).into()),
|
||||||
DefaultAccount::Provided(address.into()),
|
|
||||||
meta.origin
|
meta.origin
|
||||||
).map(move |result| match result {
|
).map(move |result| match result {
|
||||||
DispatchResult::Value(v) => RpcEither::Or(v),
|
DispatchResult::Value(v) => RpcEither::Or(v),
|
||||||
@ -160,10 +161,12 @@ impl<D: Dispatcher + 'static> ParitySigning for SigningQueueClient<D> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn post_transaction(&self, meta: Metadata, request: RpcTransactionRequest) -> BoxFuture<RpcEither<RpcU256, RpcConfirmationResponse>> {
|
fn post_transaction(&self, meta: Metadata, request: RpcTransactionRequest) -> BoxFuture<RpcEither<RpcU256, RpcConfirmationResponse>> {
|
||||||
|
self.deprecation_notice.print("parity_postTransaction", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
let executor = self.executor.clone();
|
let executor = self.executor.clone();
|
||||||
let confirmations = self.confirmations.clone();
|
let confirmations = self.confirmations.clone();
|
||||||
|
|
||||||
Box::new(self.dispatch(RpcConfirmationPayload::SendTransaction(request), DefaultAccount::Provided(self.accounts.default_account().ok().unwrap_or_default()), meta.origin)
|
Box::new(self.dispatch(RpcConfirmationPayload::SendTransaction(request), meta.origin)
|
||||||
.map(|result| match result {
|
.map(|result| match result {
|
||||||
DispatchResult::Value(v) => RpcEither::Or(v),
|
DispatchResult::Value(v) => RpcEither::Or(v),
|
||||||
DispatchResult::Future(id, future) => {
|
DispatchResult::Future(id, future) => {
|
||||||
@ -174,6 +177,8 @@ impl<D: Dispatcher + 'static> ParitySigning for SigningQueueClient<D> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn check_request(&self, id: RpcU256) -> Result<Option<RpcConfirmationResponse>> {
|
fn check_request(&self, id: RpcU256) -> Result<Option<RpcConfirmationResponse>> {
|
||||||
|
self.deprecation_notice.print("parity_checkRequest", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
let id: U256 = id.into();
|
let id: U256 = id.into();
|
||||||
match self.confirmations.lock().get(&id) {
|
match self.confirmations.lock().get(&id) {
|
||||||
None => Err(errors::request_not_found()), // Request info has been dropped, or even never been there
|
None => Err(errors::request_not_found()), // Request info has been dropped, or even never been there
|
||||||
@ -183,9 +188,10 @@ impl<D: Dispatcher + 'static> ParitySigning for SigningQueueClient<D> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn decrypt_message(&self, meta: Metadata, address: RpcH160, data: RpcBytes) -> BoxFuture<RpcBytes> {
|
fn decrypt_message(&self, meta: Metadata, address: RpcH160, data: RpcBytes) -> BoxFuture<RpcBytes> {
|
||||||
|
self.deprecation_notice.print("parity_decryptMessage", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
let res = self.dispatch(
|
let res = self.dispatch(
|
||||||
RpcConfirmationPayload::Decrypt((address.clone(), data).into()),
|
RpcConfirmationPayload::Decrypt((address.clone(), data).into()),
|
||||||
address.into(),
|
|
||||||
meta.origin,
|
meta.origin,
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -203,9 +209,10 @@ impl<D: Dispatcher + 'static> EthSigning for SigningQueueClient<D> {
|
|||||||
type Metadata = Metadata;
|
type Metadata = Metadata;
|
||||||
|
|
||||||
fn sign(&self, meta: Metadata, address: RpcH160, data: RpcBytes) -> BoxFuture<RpcH520> {
|
fn sign(&self, meta: Metadata, address: RpcH160, data: RpcBytes) -> BoxFuture<RpcH520> {
|
||||||
|
self.deprecation_notice.print("eth_sign", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
let res = self.dispatch(
|
let res = self.dispatch(
|
||||||
RpcConfirmationPayload::EthSignMessage((address.clone(), data).into()),
|
RpcConfirmationPayload::EthSignMessage((address.clone(), data).into()),
|
||||||
address.into(),
|
|
||||||
meta.origin,
|
meta.origin,
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -218,9 +225,10 @@ impl<D: Dispatcher + 'static> EthSigning for SigningQueueClient<D> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn send_transaction(&self, meta: Metadata, request: RpcTransactionRequest) -> BoxFuture<RpcH256> {
|
fn send_transaction(&self, meta: Metadata, request: RpcTransactionRequest) -> BoxFuture<RpcH256> {
|
||||||
|
self.deprecation_notice.print("eth_sendTransaction", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
let res = self.dispatch(
|
let res = self.dispatch(
|
||||||
RpcConfirmationPayload::SendTransaction(request),
|
RpcConfirmationPayload::SendTransaction(request),
|
||||||
DefaultAccount::Provided(self.accounts.default_account().ok().unwrap_or_default()),
|
|
||||||
meta.origin,
|
meta.origin,
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -233,9 +241,10 @@ impl<D: Dispatcher + 'static> EthSigning for SigningQueueClient<D> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn sign_transaction(&self, meta: Metadata, request: RpcTransactionRequest) -> BoxFuture<RpcRichRawTransaction> {
|
fn sign_transaction(&self, meta: Metadata, request: RpcTransactionRequest) -> BoxFuture<RpcRichRawTransaction> {
|
||||||
|
self.deprecation_notice.print("eth_signTransaction", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
let res = self.dispatch(
|
let res = self.dispatch(
|
||||||
RpcConfirmationPayload::SignTransaction(request),
|
RpcConfirmationPayload::SignTransaction(request),
|
||||||
DefaultAccount::Provided(self.accounts.default_account().ok().unwrap_or_default()),
|
|
||||||
meta.origin,
|
meta.origin,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
@ -18,11 +18,12 @@
|
|||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use ethcore::account_provider::AccountProvider;
|
use ethereum_types::Address;
|
||||||
|
|
||||||
use jsonrpc_core::{BoxFuture, Result};
|
use jsonrpc_core::{BoxFuture, Result};
|
||||||
use jsonrpc_core::futures::{future, Future};
|
use jsonrpc_core::futures::{future, Future};
|
||||||
use v1::helpers::{errors, DefaultAccount};
|
use v1::helpers::{errors};
|
||||||
|
use v1::helpers::deprecated::{self, DeprecationNotice};
|
||||||
use v1::helpers::dispatch::{self, Dispatcher};
|
use v1::helpers::dispatch::{self, Dispatcher};
|
||||||
use v1::metadata::Metadata;
|
use v1::metadata::Metadata;
|
||||||
use v1::traits::{EthSigning, ParitySigning};
|
use v1::traits::{EthSigning, ParitySigning};
|
||||||
@ -38,29 +39,28 @@ use v1::types::{
|
|||||||
|
|
||||||
/// Implementation of functions that require signing when no trusted signer is used.
|
/// Implementation of functions that require signing when no trusted signer is used.
|
||||||
pub struct SigningUnsafeClient<D> {
|
pub struct SigningUnsafeClient<D> {
|
||||||
accounts: Arc<AccountProvider>,
|
accounts: Arc<dispatch::Accounts>,
|
||||||
dispatcher: D,
|
dispatcher: D,
|
||||||
|
deprecation_notice: DeprecationNotice,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<D: Dispatcher + 'static> SigningUnsafeClient<D> {
|
impl<D: Dispatcher + 'static> SigningUnsafeClient<D> {
|
||||||
/// Creates new SigningUnsafeClient.
|
/// Creates new SigningUnsafeClient.
|
||||||
pub fn new(accounts: &Arc<AccountProvider>, dispatcher: D) -> Self {
|
pub fn new(accounts: &Arc<dispatch::Accounts>, dispatcher: D) -> Self {
|
||||||
SigningUnsafeClient {
|
SigningUnsafeClient {
|
||||||
accounts: accounts.clone(),
|
accounts: accounts.clone(),
|
||||||
dispatcher: dispatcher,
|
dispatcher,
|
||||||
|
deprecation_notice: Default::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn handle(&self, payload: RpcConfirmationPayload, account: DefaultAccount) -> BoxFuture<RpcConfirmationResponse> {
|
fn handle(&self, payload: RpcConfirmationPayload, account: Address) -> BoxFuture<RpcConfirmationResponse> {
|
||||||
let accounts = self.accounts.clone();
|
let accounts = self.accounts.clone();
|
||||||
let default = match account {
|
|
||||||
DefaultAccount::Provided(acc) => acc,
|
|
||||||
};
|
|
||||||
|
|
||||||
let dis = self.dispatcher.clone();
|
let dis = self.dispatcher.clone();
|
||||||
Box::new(dispatch::from_rpc(payload, default, &dis)
|
Box::new(dispatch::from_rpc(payload, account, &dis)
|
||||||
.and_then(move |payload| {
|
.and_then(move |payload| {
|
||||||
dispatch::execute(dis, accounts, payload, dispatch::SignWith::Nothing)
|
dispatch::execute(dis, &accounts, payload, dispatch::SignWith::Nothing)
|
||||||
})
|
})
|
||||||
.map(|v| v.into_value()))
|
.map(|v| v.into_value()))
|
||||||
}
|
}
|
||||||
@ -71,6 +71,8 @@ impl<D: Dispatcher + 'static> EthSigning for SigningUnsafeClient<D>
|
|||||||
type Metadata = Metadata;
|
type Metadata = Metadata;
|
||||||
|
|
||||||
fn sign(&self, _: Metadata, address: RpcH160, data: RpcBytes) -> BoxFuture<RpcH520> {
|
fn sign(&self, _: Metadata, address: RpcH160, data: RpcBytes) -> BoxFuture<RpcH520> {
|
||||||
|
self.deprecation_notice.print("eth_sign", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
Box::new(self.handle(RpcConfirmationPayload::EthSignMessage((address.clone(), data).into()), address.into())
|
Box::new(self.handle(RpcConfirmationPayload::EthSignMessage((address.clone(), data).into()), address.into())
|
||||||
.then(|res| match res {
|
.then(|res| match res {
|
||||||
Ok(RpcConfirmationResponse::Signature(signature)) => Ok(signature),
|
Ok(RpcConfirmationResponse::Signature(signature)) => Ok(signature),
|
||||||
@ -80,7 +82,9 @@ impl<D: Dispatcher + 'static> EthSigning for SigningUnsafeClient<D>
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn send_transaction(&self, _meta: Metadata, request: RpcTransactionRequest) -> BoxFuture<RpcH256> {
|
fn send_transaction(&self, _meta: Metadata, request: RpcTransactionRequest) -> BoxFuture<RpcH256> {
|
||||||
Box::new(self.handle(RpcConfirmationPayload::SendTransaction(request), DefaultAccount::Provided(self.accounts.default_account().ok().unwrap_or_default()))
|
self.deprecation_notice.print("eth_sendTransaction", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
|
Box::new(self.handle(RpcConfirmationPayload::SendTransaction(request), self.accounts.default_account())
|
||||||
.then(|res| match res {
|
.then(|res| match res {
|
||||||
Ok(RpcConfirmationResponse::SendTransaction(hash)) => Ok(hash),
|
Ok(RpcConfirmationResponse::SendTransaction(hash)) => Ok(hash),
|
||||||
Err(e) => Err(e),
|
Err(e) => Err(e),
|
||||||
@ -89,7 +93,9 @@ impl<D: Dispatcher + 'static> EthSigning for SigningUnsafeClient<D>
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn sign_transaction(&self, _meta: Metadata, request: RpcTransactionRequest) -> BoxFuture<RpcRichRawTransaction> {
|
fn sign_transaction(&self, _meta: Metadata, request: RpcTransactionRequest) -> BoxFuture<RpcRichRawTransaction> {
|
||||||
Box::new(self.handle(RpcConfirmationPayload::SignTransaction(request), DefaultAccount::Provided(self.accounts.default_account().ok().unwrap_or_default()))
|
self.deprecation_notice.print("eth_signTransaction", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
|
Box::new(self.handle(RpcConfirmationPayload::SignTransaction(request), self.accounts.default_account())
|
||||||
.then(|res| match res {
|
.then(|res| match res {
|
||||||
Ok(RpcConfirmationResponse::SignTransaction(tx)) => Ok(tx),
|
Ok(RpcConfirmationResponse::SignTransaction(tx)) => Ok(tx),
|
||||||
Err(e) => Err(e),
|
Err(e) => Err(e),
|
||||||
@ -103,11 +109,13 @@ impl<D: Dispatcher + 'static> ParitySigning for SigningUnsafeClient<D> {
|
|||||||
|
|
||||||
fn compose_transaction(&self, _meta: Metadata, transaction: RpcTransactionRequest) -> BoxFuture<RpcTransactionRequest> {
|
fn compose_transaction(&self, _meta: Metadata, transaction: RpcTransactionRequest) -> BoxFuture<RpcTransactionRequest> {
|
||||||
let accounts = self.accounts.clone();
|
let accounts = self.accounts.clone();
|
||||||
let default_account = accounts.default_account().ok().unwrap_or_default();
|
let default_account = accounts.default_account();
|
||||||
Box::new(self.dispatcher.fill_optional_fields(transaction.into(), default_account, true).map(Into::into))
|
Box::new(self.dispatcher.fill_optional_fields(transaction.into(), default_account, true).map(Into::into))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn decrypt_message(&self, _: Metadata, address: RpcH160, data: RpcBytes) -> BoxFuture<RpcBytes> {
|
fn decrypt_message(&self, _: Metadata, address: RpcH160, data: RpcBytes) -> BoxFuture<RpcBytes> {
|
||||||
|
self.deprecation_notice.print("parity_decryptMessage", deprecated::msgs::ACCOUNTS);
|
||||||
|
|
||||||
Box::new(self.handle(RpcConfirmationPayload::Decrypt((address.clone(), data).into()), address.into())
|
Box::new(self.handle(RpcConfirmationPayload::Decrypt((address.clone(), data).into()), address.into())
|
||||||
.then(|res| match res {
|
.then(|res| match res {
|
||||||
Ok(RpcConfirmationResponse::Decrypt(data)) => Ok(data),
|
Ok(RpcConfirmationResponse::Decrypt(data)) => Ok(data),
|
||||||
|
@ -41,7 +41,7 @@ pub mod informant;
|
|||||||
pub mod metadata;
|
pub mod metadata;
|
||||||
pub mod traits;
|
pub mod traits;
|
||||||
|
|
||||||
pub use self::traits::{Debug, Eth, EthFilter, EthPubSub, EthSigning, Net, Parity, ParityAccounts, ParitySet, ParitySigning, Personal, PubSub, Private, Rpc, SecretStore, Signer, Traces, Web3};
|
pub use self::traits::{Debug, Eth, EthFilter, EthPubSub, EthSigning, Net, Parity, ParityAccountsInfo, ParityAccounts, ParitySet, ParitySetAccounts, ParitySigning, Personal, PubSub, Private, Rpc, SecretStore, Signer, Traces, Web3};
|
||||||
pub use self::impls::*;
|
pub use self::impls::*;
|
||||||
pub use self::helpers::{NetworkSettings, block_import, dispatch};
|
pub use self::helpers::{NetworkSettings, block_import, dispatch};
|
||||||
pub use self::metadata::Metadata;
|
pub use self::metadata::Metadata;
|
||||||
@ -50,6 +50,8 @@ pub use self::extractors::{RpcExtractor, WsExtractor, WsStats, WsDispatcher};
|
|||||||
|
|
||||||
/// Signer utilities
|
/// Signer utilities
|
||||||
pub mod signer {
|
pub mod signer {
|
||||||
pub use super::helpers::{SigningQueue, SignerService, ConfirmationsQueue};
|
#[cfg(any(test, feature = "accounts"))]
|
||||||
|
pub use super::helpers::engine_signer::EngineSigner;
|
||||||
|
pub use super::helpers::external_signer::{SignerService, ConfirmationsQueue};
|
||||||
pub use super::types::{ConfirmationRequest, TransactionModification, U256, TransactionCondition};
|
pub use super::types::{ConfirmationRequest, TransactionModification, U256, TransactionCondition};
|
||||||
}
|
}
|
||||||
|
@ -18,7 +18,7 @@
|
|||||||
use std::env;
|
use std::env;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use ethcore::account_provider::AccountProvider;
|
use accounts::AccountProvider;
|
||||||
use ethcore::client::{BlockChainClient, Client, ClientConfig, ChainInfo, ImportBlock};
|
use ethcore::client::{BlockChainClient, Client, ClientConfig, ChainInfo, ImportBlock};
|
||||||
use ethcore::ethereum;
|
use ethcore::ethereum;
|
||||||
use ethcore::miner::Miner;
|
use ethcore::miner::Miner;
|
||||||
@ -36,13 +36,12 @@ use parking_lot::Mutex;
|
|||||||
use types::ids::BlockId;
|
use types::ids::BlockId;
|
||||||
|
|
||||||
use jsonrpc_core::IoHandler;
|
use jsonrpc_core::IoHandler;
|
||||||
use v1::helpers::dispatch::FullDispatcher;
|
use v1::helpers::dispatch::{self, FullDispatcher};
|
||||||
use v1::helpers::nonce;
|
use v1::helpers::nonce;
|
||||||
use v1::impls::{EthClient, EthClientOptions, SigningUnsafeClient};
|
use v1::impls::{EthClient, EthClientOptions, SigningUnsafeClient};
|
||||||
use v1::metadata::Metadata;
|
use v1::metadata::Metadata;
|
||||||
use v1::tests::helpers::{TestSnapshotService, TestSyncProvider, Config};
|
use v1::tests::helpers::{TestSnapshotService, TestSyncProvider, Config};
|
||||||
use v1::traits::eth::Eth;
|
use v1::traits::{Eth, EthSigning};
|
||||||
use v1::traits::eth_signing::EthSigning;
|
|
||||||
use v1::types::U256 as NU256;
|
use v1::types::U256 as NU256;
|
||||||
|
|
||||||
fn account_provider() -> Arc<AccountProvider> {
|
fn account_provider() -> Arc<AccountProvider> {
|
||||||
@ -56,8 +55,8 @@ fn sync_provider() -> Arc<TestSyncProvider> {
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn miner_service(spec: &Spec, accounts: Arc<AccountProvider>) -> Arc<Miner> {
|
fn miner_service(spec: &Spec) -> Arc<Miner> {
|
||||||
Arc::new(Miner::new_for_tests(spec, Some(accounts)))
|
Arc::new(Miner::new_for_tests(spec, None))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn snapshot_service() -> Arc<TestSnapshotService> {
|
fn snapshot_service() -> Arc<TestSnapshotService> {
|
||||||
@ -75,11 +74,11 @@ fn make_spec(chain: &BlockChain) -> Spec {
|
|||||||
}
|
}
|
||||||
|
|
||||||
struct EthTester {
|
struct EthTester {
|
||||||
_runtime: Runtime,
|
|
||||||
client: Arc<Client>,
|
|
||||||
_miner: Arc<Miner>,
|
_miner: Arc<Miner>,
|
||||||
|
_runtime: Runtime,
|
||||||
_snapshot: Arc<TestSnapshotService>,
|
_snapshot: Arc<TestSnapshotService>,
|
||||||
accounts: Arc<AccountProvider>,
|
accounts: Arc<AccountProvider>,
|
||||||
|
client: Arc<Client>,
|
||||||
handler: IoHandler<Metadata>,
|
handler: IoHandler<Metadata>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -115,11 +114,11 @@ impl EthTester {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn from_spec_conf(spec: Spec, config: ClientConfig) -> Self {
|
fn from_spec_conf(spec: Spec, config: ClientConfig) -> Self {
|
||||||
|
|
||||||
let runtime = Runtime::with_thread_count(1);
|
let runtime = Runtime::with_thread_count(1);
|
||||||
let account_provider = account_provider();
|
let account_provider = account_provider();
|
||||||
let opt_account_provider = account_provider.clone();
|
let ap = account_provider.clone();
|
||||||
let miner_service = miner_service(&spec, account_provider.clone());
|
let accounts = Arc::new(move || ap.accounts().unwrap_or_default()) as _;
|
||||||
|
let miner_service = miner_service(&spec);
|
||||||
let snapshot_service = snapshot_service();
|
let snapshot_service = snapshot_service();
|
||||||
|
|
||||||
let client = Client::new(
|
let client = Client::new(
|
||||||
@ -136,7 +135,7 @@ impl EthTester {
|
|||||||
&client,
|
&client,
|
||||||
&snapshot_service,
|
&snapshot_service,
|
||||||
&sync_provider,
|
&sync_provider,
|
||||||
&opt_account_provider,
|
&accounts,
|
||||||
&miner_service,
|
&miner_service,
|
||||||
&external_miner,
|
&external_miner,
|
||||||
EthClientOptions {
|
EthClientOptions {
|
||||||
@ -152,8 +151,9 @@ impl EthTester {
|
|||||||
let reservations = Arc::new(Mutex::new(nonce::Reservations::new(runtime.executor())));
|
let reservations = Arc::new(Mutex::new(nonce::Reservations::new(runtime.executor())));
|
||||||
|
|
||||||
let dispatcher = FullDispatcher::new(client.clone(), miner_service.clone(), reservations, 50);
|
let dispatcher = FullDispatcher::new(client.clone(), miner_service.clone(), reservations, 50);
|
||||||
|
let signer = Arc::new(dispatch::Signer::new(account_provider.clone())) as _;
|
||||||
let eth_sign = SigningUnsafeClient::new(
|
let eth_sign = SigningUnsafeClient::new(
|
||||||
&opt_account_provider,
|
&signer,
|
||||||
dispatcher,
|
dispatcher,
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -162,11 +162,11 @@ impl EthTester {
|
|||||||
handler.extend_with(eth_sign.to_delegate());
|
handler.extend_with(eth_sign.to_delegate());
|
||||||
|
|
||||||
EthTester {
|
EthTester {
|
||||||
_runtime: runtime,
|
|
||||||
_miner: miner_service,
|
_miner: miner_service,
|
||||||
|
_runtime: runtime,
|
||||||
_snapshot: snapshot_service,
|
_snapshot: snapshot_service,
|
||||||
client: client,
|
|
||||||
accounts: account_provider,
|
accounts: account_provider,
|
||||||
|
client: client,
|
||||||
handler: handler,
|
handler: handler,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -20,14 +20,12 @@ use std::sync::Arc;
|
|||||||
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||||
|
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use ethcore::account_provider::SignError as AccountError;
|
|
||||||
use ethcore::block::{SealedBlock, IsBlock};
|
use ethcore::block::{SealedBlock, IsBlock};
|
||||||
use ethcore::client::{Nonce, PrepareOpenBlock, StateClient, EngineInfo};
|
use ethcore::client::{Nonce, PrepareOpenBlock, StateClient, EngineInfo};
|
||||||
use ethcore::engines::EthEngine;
|
use ethcore::engines::{EthEngine, signer::EngineSigner};
|
||||||
use ethcore::error::Error;
|
use ethcore::error::Error;
|
||||||
use ethcore::miner::{self, MinerService, AuthoringParams};
|
use ethcore::miner::{self, MinerService, AuthoringParams};
|
||||||
use ethereum_types::{H256, U256, Address};
|
use ethereum_types::{H256, U256, Address};
|
||||||
use ethkey::Password;
|
|
||||||
use miner::pool::local_transactions::Status as LocalTransactionStatus;
|
use miner::pool::local_transactions::Status as LocalTransactionStatus;
|
||||||
use miner::pool::{verifier, VerifiedTransaction, QueueStatus};
|
use miner::pool::{verifier, VerifiedTransaction, QueueStatus};
|
||||||
use parking_lot::{RwLock, Mutex};
|
use parking_lot::{RwLock, Mutex};
|
||||||
@ -51,8 +49,8 @@ pub struct TestMinerService {
|
|||||||
pub pending_receipts: Mutex<Vec<RichReceipt>>,
|
pub pending_receipts: Mutex<Vec<RichReceipt>>,
|
||||||
/// Next nonces.
|
/// Next nonces.
|
||||||
pub next_nonces: RwLock<HashMap<Address, U256>>,
|
pub next_nonces: RwLock<HashMap<Address, U256>>,
|
||||||
/// Password held by Engine.
|
/// Signer (if any)
|
||||||
pub password: RwLock<Password>,
|
pub signer: RwLock<Option<Box<EngineSigner>>>,
|
||||||
|
|
||||||
authoring_params: RwLock<AuthoringParams>,
|
authoring_params: RwLock<AuthoringParams>,
|
||||||
}
|
}
|
||||||
@ -65,12 +63,12 @@ impl Default for TestMinerService {
|
|||||||
local_transactions: Default::default(),
|
local_transactions: Default::default(),
|
||||||
pending_receipts: Default::default(),
|
pending_receipts: Default::default(),
|
||||||
next_nonces: Default::default(),
|
next_nonces: Default::default(),
|
||||||
password: RwLock::new("".into()),
|
|
||||||
authoring_params: RwLock::new(AuthoringParams {
|
authoring_params: RwLock::new(AuthoringParams {
|
||||||
author: Address::zero(),
|
author: Address::zero(),
|
||||||
gas_range_target: (12345.into(), 54321.into()),
|
gas_range_target: (12345.into(), 54321.into()),
|
||||||
extra_data: vec![1, 2, 3, 4],
|
extra_data: vec![1, 2, 3, 4],
|
||||||
}),
|
}),
|
||||||
|
signer: RwLock::new(None),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -122,12 +120,11 @@ impl MinerService for TestMinerService {
|
|||||||
self.authoring_params.read().clone()
|
self.authoring_params.read().clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_author(&self, author: Address, password: Option<Password>) -> Result<(), AccountError> {
|
fn set_author(&self, author: miner::Author) {
|
||||||
self.authoring_params.write().author = author;
|
self.authoring_params.write().author = author.address();
|
||||||
if let Some(password) = password {
|
if let miner::Author::Sealer(signer) = author {
|
||||||
*self.password.write() = password;
|
*self.signer.write() = Some(signer);
|
||||||
}
|
}
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_extra_data(&self, extra_data: Bytes) {
|
fn set_extra_data(&self, extra_data: Bytes) {
|
||||||
|
@ -19,11 +19,10 @@ use std::collections::HashMap;
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::{Instant, Duration, SystemTime, UNIX_EPOCH};
|
use std::time::{Instant, Duration, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
use ethcore::account_provider::AccountProvider;
|
use accounts::AccountProvider;
|
||||||
use ethcore::client::{BlockChainClient, BlockId, EachBlockWith, Executed, TestBlockChainClient, TransactionId};
|
use ethcore::client::{BlockChainClient, BlockId, EachBlockWith, Executed, TestBlockChainClient, TransactionId};
|
||||||
use ethcore::miner::MinerService;
|
use ethcore::miner::{self, MinerService};
|
||||||
use ethereum_types::{H160, H256, U256, Address};
|
use ethereum_types::{H160, H256, U256, Address};
|
||||||
use ethkey::Secret;
|
|
||||||
use miner::external::ExternalMiner;
|
use miner::external::ExternalMiner;
|
||||||
use parity_runtime::Runtime;
|
use parity_runtime::Runtime;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
@ -35,9 +34,7 @@ use types::log_entry::{LocalizedLogEntry, LogEntry};
|
|||||||
use types::receipt::{LocalizedReceipt, TransactionOutcome};
|
use types::receipt::{LocalizedReceipt, TransactionOutcome};
|
||||||
|
|
||||||
use jsonrpc_core::IoHandler;
|
use jsonrpc_core::IoHandler;
|
||||||
use v1::{Eth, EthClient, EthClientOptions, EthFilter, EthFilterClient, EthSigning, SigningUnsafeClient};
|
use v1::{Eth, EthClient, EthClientOptions, EthFilter, EthFilterClient};
|
||||||
use v1::helpers::nonce;
|
|
||||||
use v1::helpers::dispatch::FullDispatcher;
|
|
||||||
use v1::tests::helpers::{TestSyncProvider, Config, TestMinerService, TestSnapshotService};
|
use v1::tests::helpers::{TestSyncProvider, Config, TestMinerService, TestSnapshotService};
|
||||||
use v1::metadata::Metadata;
|
use v1::metadata::Metadata;
|
||||||
|
|
||||||
@ -88,21 +85,17 @@ impl EthTester {
|
|||||||
let client = blockchain_client();
|
let client = blockchain_client();
|
||||||
let sync = sync_provider();
|
let sync = sync_provider();
|
||||||
let ap = accounts_provider();
|
let ap = accounts_provider();
|
||||||
let opt_ap = ap.clone();
|
let ap2 = ap.clone();
|
||||||
|
let opt_ap = Arc::new(move || ap2.accounts().unwrap_or_default()) as _;
|
||||||
let miner = miner_service();
|
let miner = miner_service();
|
||||||
let snapshot = snapshot_service();
|
let snapshot = snapshot_service();
|
||||||
let hashrates = Arc::new(Mutex::new(HashMap::new()));
|
let hashrates = Arc::new(Mutex::new(HashMap::new()));
|
||||||
let external_miner = Arc::new(ExternalMiner::new(hashrates.clone()));
|
let external_miner = Arc::new(ExternalMiner::new(hashrates.clone()));
|
||||||
let gas_price_percentile = options.gas_price_percentile;
|
|
||||||
let eth = EthClient::new(&client, &snapshot, &sync, &opt_ap, &miner, &external_miner, options).to_delegate();
|
let eth = EthClient::new(&client, &snapshot, &sync, &opt_ap, &miner, &external_miner, options).to_delegate();
|
||||||
let filter = EthFilterClient::new(client.clone(), miner.clone(), 60).to_delegate();
|
let filter = EthFilterClient::new(client.clone(), miner.clone(), 60).to_delegate();
|
||||||
let reservations = Arc::new(Mutex::new(nonce::Reservations::new(runtime.executor())));
|
|
||||||
|
|
||||||
let dispatcher = FullDispatcher::new(client.clone(), miner.clone(), reservations, gas_price_percentile);
|
|
||||||
let sign = SigningUnsafeClient::new(&opt_ap, dispatcher).to_delegate();
|
|
||||||
let mut io: IoHandler<Metadata> = IoHandler::default();
|
let mut io: IoHandler<Metadata> = IoHandler::default();
|
||||||
io.extend_with(eth);
|
io.extend_with(eth);
|
||||||
io.extend_with(sign);
|
|
||||||
io.extend_with(filter);
|
io.extend_with(filter);
|
||||||
|
|
||||||
EthTester {
|
EthTester {
|
||||||
@ -360,28 +353,6 @@ fn rpc_eth_submit_hashrate() {
|
|||||||
U256::from(0x500_000));
|
U256::from(0x500_000));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rpc_eth_sign() {
|
|
||||||
let tester = EthTester::default();
|
|
||||||
|
|
||||||
let account = tester.accounts_provider.insert_account(Secret::from([69u8; 32]), &"abcd".into()).unwrap();
|
|
||||||
tester.accounts_provider.unlock_account_permanently(account, "abcd".into()).unwrap();
|
|
||||||
let _message = "0cc175b9c0f1b6a831c399e26977266192eb5ffee6ae2fec3ad71c777531578f".from_hex().unwrap();
|
|
||||||
|
|
||||||
let req = r#"{
|
|
||||||
"jsonrpc": "2.0",
|
|
||||||
"method": "eth_sign",
|
|
||||||
"params": [
|
|
||||||
""#.to_owned() + &format!("0x{:x}", account) + r#"",
|
|
||||||
"0x0cc175b9c0f1b6a831c399e26977266192eb5ffee6ae2fec3ad71c777531578f"
|
|
||||||
],
|
|
||||||
"id": 1
|
|
||||||
}"#;
|
|
||||||
let res = r#"{"jsonrpc":"2.0","result":"0xa2870db1d0c26ef93c7b72d2a0830fa6b841e0593f7186bc6c7cc317af8cf3a42fda03bd589a49949aa05db83300cdb553116274518dbe9d90c65d0213f4af491b","id":1}"#;
|
|
||||||
|
|
||||||
assert_eq!(tester.io.handle_request_sync(&req), Some(res.into()));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rpc_eth_author() {
|
fn rpc_eth_author() {
|
||||||
let make_res = |addr| r#"{"jsonrpc":"2.0","result":""#.to_owned() + &format!("0x{:x}", addr) + r#"","id":1}"#;
|
let make_res = |addr| r#"{"jsonrpc":"2.0","result":""#.to_owned() + &format!("0x{:x}", addr) + r#"","id":1}"#;
|
||||||
@ -405,7 +376,7 @@ fn rpc_eth_author() {
|
|||||||
|
|
||||||
for i in 0..20 {
|
for i in 0..20 {
|
||||||
let addr = tester.accounts_provider.new_account(&format!("{}", i).into()).unwrap();
|
let addr = tester.accounts_provider.new_account(&format!("{}", i).into()).unwrap();
|
||||||
tester.miner.set_author(addr.clone(), None).unwrap();
|
tester.miner.set_author(miner::Author::External(addr));
|
||||||
|
|
||||||
assert_eq!(tester.io.handle_request_sync(request), Some(make_res(addr)));
|
assert_eq!(tester.io.handle_request_sync(request), Some(make_res(addr)));
|
||||||
}
|
}
|
||||||
@ -414,7 +385,7 @@ fn rpc_eth_author() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn rpc_eth_mining() {
|
fn rpc_eth_mining() {
|
||||||
let tester = EthTester::default();
|
let tester = EthTester::default();
|
||||||
tester.miner.set_author(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap(), None).unwrap();
|
tester.miner.set_author(miner::Author::External(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()));
|
||||||
|
|
||||||
let request = r#"{"jsonrpc": "2.0", "method": "eth_mining", "params": [], "id": 1}"#;
|
let request = r#"{"jsonrpc": "2.0", "method": "eth_mining", "params": [], "id": 1}"#;
|
||||||
let response = r#"{"jsonrpc":"2.0","result":false,"id":1}"#;
|
let response = r#"{"jsonrpc":"2.0","result":false,"id":1}"#;
|
||||||
@ -824,157 +795,6 @@ fn rpc_eth_estimate_gas_default_block() {
|
|||||||
assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned()));
|
assert_eq!(tester.io.handle_request_sync(request), Some(response.to_owned()));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rpc_eth_send_transaction() {
|
|
||||||
let tester = EthTester::default();
|
|
||||||
let address = tester.accounts_provider.new_account(&"".into()).unwrap();
|
|
||||||
tester.accounts_provider.unlock_account_permanently(address, "".into()).unwrap();
|
|
||||||
let request = r#"{
|
|
||||||
"jsonrpc": "2.0",
|
|
||||||
"method": "eth_sendTransaction",
|
|
||||||
"params": [{
|
|
||||||
"from": ""#.to_owned() + format!("0x{:x}", address).as_ref() + r#"",
|
|
||||||
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
|
|
||||||
"gas": "0x76c0",
|
|
||||||
"gasPrice": "0x9184e72a000",
|
|
||||||
"value": "0x9184e72a"
|
|
||||||
}],
|
|
||||||
"id": 1
|
|
||||||
}"#;
|
|
||||||
|
|
||||||
let t = Transaction {
|
|
||||||
nonce: U256::zero(),
|
|
||||||
gas_price: U256::from(0x9184e72a000u64),
|
|
||||||
gas: U256::from(0x76c0),
|
|
||||||
action: Action::Call(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
|
|
||||||
value: U256::from(0x9184e72au64),
|
|
||||||
data: vec![]
|
|
||||||
};
|
|
||||||
let signature = tester.accounts_provider.sign(address, None, t.hash(None)).unwrap();
|
|
||||||
let t = t.with_signature(signature, None);
|
|
||||||
|
|
||||||
let response = r#"{"jsonrpc":"2.0","result":""#.to_owned() + format!("0x{:x}", t.hash()).as_ref() + r#"","id":1}"#;
|
|
||||||
|
|
||||||
assert_eq!(tester.io.handle_request_sync(&request), Some(response));
|
|
||||||
|
|
||||||
tester.miner.increment_nonce(&address);
|
|
||||||
|
|
||||||
let t = Transaction {
|
|
||||||
nonce: U256::one(),
|
|
||||||
gas_price: U256::from(0x9184e72a000u64),
|
|
||||||
gas: U256::from(0x76c0),
|
|
||||||
action: Action::Call(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
|
|
||||||
value: U256::from(0x9184e72au64),
|
|
||||||
data: vec![]
|
|
||||||
};
|
|
||||||
let signature = tester.accounts_provider.sign(address, None, t.hash(None)).unwrap();
|
|
||||||
let t = t.with_signature(signature, None);
|
|
||||||
|
|
||||||
let response = r#"{"jsonrpc":"2.0","result":""#.to_owned() + format!("0x{:x}", t.hash()).as_ref() + r#"","id":1}"#;
|
|
||||||
|
|
||||||
assert_eq!(tester.io.handle_request_sync(&request), Some(response));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rpc_eth_sign_transaction() {
|
|
||||||
let tester = EthTester::default();
|
|
||||||
let address = tester.accounts_provider.new_account(&"".into()).unwrap();
|
|
||||||
tester.accounts_provider.unlock_account_permanently(address, "".into()).unwrap();
|
|
||||||
let request = r#"{
|
|
||||||
"jsonrpc": "2.0",
|
|
||||||
"method": "eth_signTransaction",
|
|
||||||
"params": [{
|
|
||||||
"from": ""#.to_owned() + format!("0x{:x}", address).as_ref() + r#"",
|
|
||||||
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
|
|
||||||
"gas": "0x76c0",
|
|
||||||
"gasPrice": "0x9184e72a000",
|
|
||||||
"value": "0x9184e72a"
|
|
||||||
}],
|
|
||||||
"id": 1
|
|
||||||
}"#;
|
|
||||||
|
|
||||||
let t = Transaction {
|
|
||||||
nonce: U256::one(),
|
|
||||||
gas_price: U256::from(0x9184e72a000u64),
|
|
||||||
gas: U256::from(0x76c0),
|
|
||||||
action: Action::Call(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
|
|
||||||
value: U256::from(0x9184e72au64),
|
|
||||||
data: vec![]
|
|
||||||
};
|
|
||||||
let signature = tester.accounts_provider.sign(address, None, t.hash(None)).unwrap();
|
|
||||||
let t = t.with_signature(signature, None);
|
|
||||||
let signature = t.signature();
|
|
||||||
let rlp = rlp::encode(&t);
|
|
||||||
|
|
||||||
let response = r#"{"jsonrpc":"2.0","result":{"#.to_owned() +
|
|
||||||
r#""raw":"0x"# + &rlp.to_hex() + r#"","# +
|
|
||||||
r#""tx":{"# +
|
|
||||||
r#""blockHash":null,"blockNumber":null,"# +
|
|
||||||
&format!("\"chainId\":{},", t.chain_id().map_or("null".to_owned(), |n| format!("{}", n))) +
|
|
||||||
r#""condition":null,"creates":null,"# +
|
|
||||||
&format!("\"from\":\"0x{:x}\",", &address) +
|
|
||||||
r#""gas":"0x76c0","gasPrice":"0x9184e72a000","# +
|
|
||||||
&format!("\"hash\":\"0x{:x}\",", t.hash()) +
|
|
||||||
r#""input":"0x","# +
|
|
||||||
r#""nonce":"0x1","# +
|
|
||||||
&format!("\"publicKey\":\"0x{:x}\",", t.recover_public().unwrap()) +
|
|
||||||
&format!("\"r\":\"0x{:x}\",", U256::from(signature.r())) +
|
|
||||||
&format!("\"raw\":\"0x{}\",", rlp.to_hex()) +
|
|
||||||
&format!("\"s\":\"0x{:x}\",", U256::from(signature.s())) +
|
|
||||||
&format!("\"standardV\":\"0x{:x}\",", U256::from(t.standard_v())) +
|
|
||||||
r#""to":"0xd46e8dd67c5d32be8058bb8eb970870f07244567","transactionIndex":null,"# +
|
|
||||||
&format!("\"v\":\"0x{:x}\",", U256::from(t.original_v())) +
|
|
||||||
r#""value":"0x9184e72a""# +
|
|
||||||
r#"}},"id":1}"#;
|
|
||||||
|
|
||||||
tester.miner.increment_nonce(&address);
|
|
||||||
|
|
||||||
assert_eq!(tester.io.handle_request_sync(&request), Some(response));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rpc_eth_send_transaction_with_bad_to() {
|
|
||||||
let tester = EthTester::default();
|
|
||||||
let address = tester.accounts_provider.new_account(&"".into()).unwrap();
|
|
||||||
let request = r#"{
|
|
||||||
"jsonrpc": "2.0",
|
|
||||||
"method": "eth_sendTransaction",
|
|
||||||
"params": [{
|
|
||||||
"from": ""#.to_owned() + format!("0x{:x}", address).as_ref() + r#"",
|
|
||||||
"to": "",
|
|
||||||
"gas": "0x76c0",
|
|
||||||
"gasPrice": "0x9184e72a000",
|
|
||||||
"value": "0x9184e72a"
|
|
||||||
}],
|
|
||||||
"id": 1
|
|
||||||
}"#;
|
|
||||||
|
|
||||||
let response = r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid params: expected a hex-encoded hash with 0x prefix."},"id":1}"#;
|
|
||||||
|
|
||||||
assert_eq!(tester.io.handle_request_sync(&request), Some(response.into()));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rpc_eth_send_transaction_error() {
|
|
||||||
let tester = EthTester::default();
|
|
||||||
let address = tester.accounts_provider.new_account(&"".into()).unwrap();
|
|
||||||
let request = r#"{
|
|
||||||
"jsonrpc": "2.0",
|
|
||||||
"method": "eth_sendTransaction",
|
|
||||||
"params": [{
|
|
||||||
"from": ""#.to_owned() + format!("0x{:x}", address).as_ref() + r#"",
|
|
||||||
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
|
|
||||||
"gas": "0x76c0",
|
|
||||||
"gasPrice": "0x9184e72a000",
|
|
||||||
"value": "0x9184e72a"
|
|
||||||
}],
|
|
||||||
"id": 1
|
|
||||||
}"#;
|
|
||||||
|
|
||||||
let response = r#"{"jsonrpc":"2.0","error":{"code":-32020,"message":"Your account is locked. Unlock the account via CLI, personal_unlockAccount or use Trusted Signer.","data":"NotUnlocked"},"id":1}"#;
|
|
||||||
assert_eq!(tester.io.handle_request_sync(&request), Some(response.into()));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rpc_eth_send_raw_transaction_error() {
|
fn rpc_eth_send_raw_transaction_error() {
|
||||||
let tester = EthTester::default();
|
let tester = EthTester::default();
|
||||||
@ -1141,7 +961,7 @@ fn rpc_get_work_returns_no_work_if_cant_mine() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn rpc_get_work_returns_correct_work_package() {
|
fn rpc_get_work_returns_correct_work_package() {
|
||||||
let eth_tester = EthTester::default();
|
let eth_tester = EthTester::default();
|
||||||
eth_tester.miner.set_author(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap(), None).unwrap();
|
eth_tester.miner.set_author(miner::Author::External(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()));
|
||||||
|
|
||||||
let request = r#"{"jsonrpc": "2.0", "method": "eth_getWork", "params": [], "id": 1}"#;
|
let request = r#"{"jsonrpc": "2.0", "method": "eth_getWork", "params": [], "id": 1}"#;
|
||||||
let response = r#"{"jsonrpc":"2.0","result":["0x76c7bd86693aee93d1a80a408a09a0585b1a1292afcb56192f171d925ea18e2d","0x0000000000000000000000000000000000000000000000000000000000000000","0x0000800000000000000000000000000000000000000000000000000000000000","0x1"],"id":1}"#;
|
let response = r#"{"jsonrpc":"2.0","result":["0x76c7bd86693aee93d1a80a408a09a0585b1a1292afcb56192f171d925ea18e2d","0x0000000000000000000000000000000000000000000000000000000000000000","0x0000800000000000000000000000000000000000000000000000000000000000","0x1"],"id":1}"#;
|
||||||
@ -1154,7 +974,7 @@ fn rpc_get_work_should_not_return_block_number() {
|
|||||||
let eth_tester = EthTester::new_with_options(EthClientOptions::with(|options| {
|
let eth_tester = EthTester::new_with_options(EthClientOptions::with(|options| {
|
||||||
options.send_block_number_in_get_work = false;
|
options.send_block_number_in_get_work = false;
|
||||||
}));
|
}));
|
||||||
eth_tester.miner.set_author(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap(), None).unwrap();
|
eth_tester.miner.set_author(miner::Author::External(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()));
|
||||||
|
|
||||||
let request = r#"{"jsonrpc": "2.0", "method": "eth_getWork", "params": [], "id": 1}"#;
|
let request = r#"{"jsonrpc": "2.0", "method": "eth_getWork", "params": [], "id": 1}"#;
|
||||||
let response = r#"{"jsonrpc":"2.0","result":["0x76c7bd86693aee93d1a80a408a09a0585b1a1292afcb56192f171d925ea18e2d","0x0000000000000000000000000000000000000000000000000000000000000000","0x0000800000000000000000000000000000000000000000000000000000000000"],"id":1}"#;
|
let response = r#"{"jsonrpc":"2.0","result":["0x76c7bd86693aee93d1a80a408a09a0585b1a1292afcb56192f171d925ea18e2d","0x0000000000000000000000000000000000000000000000000000000000000000","0x0000800000000000000000000000000000000000000000000000000000000000"],"id":1}"#;
|
||||||
@ -1165,7 +985,7 @@ fn rpc_get_work_should_not_return_block_number() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn rpc_get_work_should_timeout() {
|
fn rpc_get_work_should_timeout() {
|
||||||
let eth_tester = EthTester::default();
|
let eth_tester = EthTester::default();
|
||||||
eth_tester.miner.set_author(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap(), None).unwrap();
|
eth_tester.miner.set_author(miner::Author::External(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()));
|
||||||
let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() - 1000; // Set latest block to 1000 seconds ago
|
let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() - 1000; // Set latest block to 1000 seconds ago
|
||||||
eth_tester.client.set_latest_block_timestamp(timestamp);
|
eth_tester.client.set_latest_block_timestamp(timestamp);
|
||||||
let hash = eth_tester.miner.work_package(&*eth_tester.client).unwrap().0;
|
let hash = eth_tester.miner.work_package(&*eth_tester.client).unwrap().0;
|
||||||
|
@ -23,13 +23,19 @@ mod eth_pubsub;
|
|||||||
mod manage_network;
|
mod manage_network;
|
||||||
mod net;
|
mod net;
|
||||||
mod parity;
|
mod parity;
|
||||||
|
#[cfg(any(test, feature = "accounts"))]
|
||||||
mod parity_accounts;
|
mod parity_accounts;
|
||||||
mod parity_set;
|
mod parity_set;
|
||||||
|
#[cfg(any(test, feature = "accounts"))]
|
||||||
mod personal;
|
mod personal;
|
||||||
mod pubsub;
|
mod pubsub;
|
||||||
mod rpc;
|
mod rpc;
|
||||||
|
#[cfg(any(test, feature = "accounts"))]
|
||||||
mod secretstore;
|
mod secretstore;
|
||||||
mod signer;
|
mod signer;
|
||||||
|
#[cfg(any(test, feature = "accounts"))]
|
||||||
mod signing;
|
mod signing;
|
||||||
|
#[cfg(any(test, feature = "accounts"))]
|
||||||
|
mod signing_unsafe;
|
||||||
mod traces;
|
mod traces;
|
||||||
mod web3;
|
mod web3;
|
||||||
|
@ -15,7 +15,6 @@
|
|||||||
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use ethcore::account_provider::AccountProvider;
|
|
||||||
use ethcore::client::{TestBlockChainClient, Executed, TransactionId};
|
use ethcore::client::{TestBlockChainClient, Executed, TransactionId};
|
||||||
use ethcore_logger::RotatingLogger;
|
use ethcore_logger::RotatingLogger;
|
||||||
use ethereum_types::{Address, U256, H256};
|
use ethereum_types::{Address, U256, H256};
|
||||||
@ -27,7 +26,8 @@ use types::receipt::{LocalizedReceipt, TransactionOutcome};
|
|||||||
use jsonrpc_core::IoHandler;
|
use jsonrpc_core::IoHandler;
|
||||||
use v1::{Parity, ParityClient};
|
use v1::{Parity, ParityClient};
|
||||||
use v1::metadata::Metadata;
|
use v1::metadata::Metadata;
|
||||||
use v1::helpers::{SignerService, NetworkSettings};
|
use v1::helpers::NetworkSettings;
|
||||||
|
use v1::helpers::external_signer::SignerService;
|
||||||
use v1::tests::helpers::{TestSyncProvider, Config, TestMinerService, TestUpdater};
|
use v1::tests::helpers::{TestSyncProvider, Config, TestMinerService, TestUpdater};
|
||||||
use super::manage_network::TestManageNetwork;
|
use super::manage_network::TestManageNetwork;
|
||||||
use Host;
|
use Host;
|
||||||
@ -42,7 +42,6 @@ pub struct Dependencies {
|
|||||||
pub logger: Arc<RotatingLogger>,
|
pub logger: Arc<RotatingLogger>,
|
||||||
pub settings: Arc<NetworkSettings>,
|
pub settings: Arc<NetworkSettings>,
|
||||||
pub network: Arc<ManageNetwork>,
|
pub network: Arc<ManageNetwork>,
|
||||||
pub accounts: Arc<AccountProvider>,
|
|
||||||
pub ws_address: Option<Host>,
|
pub ws_address: Option<Host>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -67,7 +66,6 @@ impl Dependencies {
|
|||||||
rpc_port: 8545,
|
rpc_port: 8545,
|
||||||
}),
|
}),
|
||||||
network: Arc::new(TestManageNetwork),
|
network: Arc::new(TestManageNetwork),
|
||||||
accounts: Arc::new(AccountProvider::transient_provider()),
|
|
||||||
ws_address: Some("127.0.0.1:18546".into()),
|
ws_address: Some("127.0.0.1:18546".into()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -79,7 +77,6 @@ impl Dependencies {
|
|||||||
self.sync.clone(),
|
self.sync.clone(),
|
||||||
self.updater.clone(),
|
self.updater.clone(),
|
||||||
self.network.clone(),
|
self.network.clone(),
|
||||||
self.accounts.clone(),
|
|
||||||
self.logger.clone(),
|
self.logger.clone(),
|
||||||
self.settings.clone(),
|
self.settings.clone(),
|
||||||
signer,
|
signer,
|
||||||
@ -101,47 +98,6 @@ impl Dependencies {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rpc_parity_accounts_info() {
|
|
||||||
let deps = Dependencies::new();
|
|
||||||
let io = deps.default_client();
|
|
||||||
|
|
||||||
deps.accounts.new_account(&"".into()).unwrap();
|
|
||||||
let accounts = deps.accounts.accounts().unwrap();
|
|
||||||
assert_eq!(accounts.len(), 1);
|
|
||||||
let address = accounts[0];
|
|
||||||
|
|
||||||
deps.accounts.set_address_name(1.into(), "XX".into());
|
|
||||||
deps.accounts.set_account_name(address.clone(), "Test".into()).unwrap();
|
|
||||||
deps.accounts.set_account_meta(address.clone(), "{foo: 69}".into()).unwrap();
|
|
||||||
|
|
||||||
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));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rpc_parity_default_account() {
|
|
||||||
let deps = Dependencies::new();
|
|
||||||
let io = deps.default_client();
|
|
||||||
|
|
||||||
// Check empty
|
|
||||||
let address = Address::default();
|
|
||||||
let request = r#"{"jsonrpc": "2.0", "method": "parity_defaultAccount", "params": [], "id": 1}"#;
|
|
||||||
let response = format!("{{\"jsonrpc\":\"2.0\",\"result\":\"0x{:x}\",\"id\":1}}", address);
|
|
||||||
assert_eq!(io.handle_request_sync(request), Some(response));
|
|
||||||
|
|
||||||
// With account
|
|
||||||
deps.accounts.new_account(&"".into()).unwrap();
|
|
||||||
let accounts = deps.accounts.accounts().unwrap();
|
|
||||||
assert_eq!(accounts.len(), 1);
|
|
||||||
let address = accounts[0];
|
|
||||||
|
|
||||||
let request = r#"{"jsonrpc": "2.0", "method": "parity_defaultAccount", "params": [], "id": 1}"#;
|
|
||||||
let response = format!("{{\"jsonrpc\":\"2.0\",\"result\":\"0x{:x}\",\"id\":1}}", address);
|
|
||||||
assert_eq!(io.handle_request_sync(request), Some(response));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rpc_parity_consensus_capability() {
|
fn rpc_parity_consensus_capability() {
|
||||||
let deps = Dependencies::new();
|
let deps = Dependencies::new();
|
||||||
|
@ -16,13 +16,14 @@
|
|||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use ethcore::account_provider::{AccountProvider, AccountProviderSettings};
|
use accounts::{AccountProvider, AccountProviderSettings};
|
||||||
|
use ethereum_types::Address;
|
||||||
use ethstore::EthStore;
|
use ethstore::EthStore;
|
||||||
use ethstore::accounts_dir::RootDiskDirectory;
|
use ethstore::accounts_dir::RootDiskDirectory;
|
||||||
use tempdir::TempDir;
|
use tempdir::TempDir;
|
||||||
|
|
||||||
use jsonrpc_core::IoHandler;
|
use jsonrpc_core::IoHandler;
|
||||||
use v1::{ParityAccounts, ParityAccountsClient};
|
use v1::{ParityAccounts, ParityAccountsInfo, ParityAccountsClient};
|
||||||
|
|
||||||
struct ParityAccountsTester {
|
struct ParityAccountsTester {
|
||||||
accounts: Arc<AccountProvider>,
|
accounts: Arc<AccountProvider>,
|
||||||
@ -42,8 +43,10 @@ fn accounts_provider_with_vaults_support(temp_path: &str) -> Arc<AccountProvider
|
|||||||
fn setup_with_accounts_provider(accounts_provider: Arc<AccountProvider>) -> ParityAccountsTester {
|
fn setup_with_accounts_provider(accounts_provider: Arc<AccountProvider>) -> ParityAccountsTester {
|
||||||
let opt_ap = accounts_provider.clone();
|
let opt_ap = accounts_provider.clone();
|
||||||
let parity_accounts = ParityAccountsClient::new(&opt_ap);
|
let parity_accounts = ParityAccountsClient::new(&opt_ap);
|
||||||
|
let parity_accounts2 = ParityAccountsClient::new(&opt_ap);
|
||||||
let mut io = IoHandler::default();
|
let mut io = IoHandler::default();
|
||||||
io.extend_with(parity_accounts.to_delegate());
|
io.extend_with(ParityAccounts::to_delegate(parity_accounts));
|
||||||
|
io.extend_with(ParityAccountsInfo::to_delegate(parity_accounts2));
|
||||||
|
|
||||||
let tester = ParityAccountsTester {
|
let tester = ParityAccountsTester {
|
||||||
accounts: accounts_provider,
|
accounts: accounts_provider,
|
||||||
@ -61,6 +64,47 @@ fn setup_with_vaults_support(temp_path: &str) -> ParityAccountsTester {
|
|||||||
setup_with_accounts_provider(accounts_provider_with_vaults_support(temp_path))
|
setup_with_accounts_provider(accounts_provider_with_vaults_support(temp_path))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rpc_parity_accounts_info() {
|
||||||
|
let tester = setup();
|
||||||
|
let io = tester.io;
|
||||||
|
|
||||||
|
tester.accounts.new_account(&"".into()).unwrap();
|
||||||
|
let accounts = tester.accounts.accounts().unwrap();
|
||||||
|
assert_eq!(accounts.len(), 1);
|
||||||
|
let address = accounts[0];
|
||||||
|
|
||||||
|
tester.accounts.set_address_name(1.into(), "XX".into());
|
||||||
|
tester.accounts.set_account_name(address.clone(), "Test".into()).unwrap();
|
||||||
|
tester.accounts.set_account_meta(address.clone(), "{foo: 69}".into()).unwrap();
|
||||||
|
|
||||||
|
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));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rpc_parity_default_account() {
|
||||||
|
let tester = setup();
|
||||||
|
let io = tester.io;
|
||||||
|
|
||||||
|
// Check empty
|
||||||
|
let address = Address::default();
|
||||||
|
let request = r#"{"jsonrpc": "2.0", "method": "parity_defaultAccount", "params": [], "id": 1}"#;
|
||||||
|
let response = format!("{{\"jsonrpc\":\"2.0\",\"result\":\"0x{:x}\",\"id\":1}}", address);
|
||||||
|
assert_eq!(io.handle_request_sync(request), Some(response));
|
||||||
|
|
||||||
|
// With account
|
||||||
|
tester.accounts.new_account(&"".into()).unwrap();
|
||||||
|
let accounts = tester.accounts.accounts().unwrap();
|
||||||
|
assert_eq!(accounts.len(), 1);
|
||||||
|
let address = accounts[0];
|
||||||
|
|
||||||
|
let request = r#"{"jsonrpc": "2.0", "method": "parity_defaultAccount", "params": [], "id": 1}"#;
|
||||||
|
let response = format!("{{\"jsonrpc\":\"2.0\",\"result\":\"0x{:x}\",\"id\":1}}", address);
|
||||||
|
assert_eq!(io.handle_request_sync(request), Some(response));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn should_be_able_to_get_account_info() {
|
fn should_be_able_to_get_account_info() {
|
||||||
let tester = setup();
|
let tester = setup();
|
||||||
|
@ -54,7 +54,13 @@ fn parity_set_client(
|
|||||||
updater: &Arc<TestUpdater>,
|
updater: &Arc<TestUpdater>,
|
||||||
net: &Arc<TestManageNetwork>,
|
net: &Arc<TestManageNetwork>,
|
||||||
) -> TestParitySetClient {
|
) -> TestParitySetClient {
|
||||||
ParitySetClient::new(client, miner, updater, &(net.clone() as Arc<ManageNetwork>), FakeFetch::new(Some(1)))
|
ParitySetClient::new(
|
||||||
|
client,
|
||||||
|
miner,
|
||||||
|
updater,
|
||||||
|
&(net.clone() as Arc<ManageNetwork>),
|
||||||
|
FakeFetch::new(Some(1)),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@ -161,23 +167,6 @@ fn rpc_parity_set_author() {
|
|||||||
assert_eq!(miner.authoring_params().author, Address::from_str("cd1722f3947def4cf144679da39c4c32bdc35681").unwrap());
|
assert_eq!(miner.authoring_params().author, Address::from_str("cd1722f3947def4cf144679da39c4c32bdc35681").unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rpc_parity_set_engine_signer() {
|
|
||||||
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_setEngineSigner", "params":["0xcd1722f3947def4cf144679da39c4c32bdc35681", "password"], "id": 1}"#;
|
|
||||||
let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#;
|
|
||||||
|
|
||||||
assert_eq!(io.handle_request_sync(request), Some(response.to_owned()));
|
|
||||||
assert_eq!(miner.authoring_params().author, Address::from_str("cd1722f3947def4cf144679da39c4c32bdc35681").unwrap());
|
|
||||||
assert_eq!(*miner.password.read(), "password".into());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn rpc_parity_set_transactions_limit() {
|
fn rpc_parity_set_transactions_limit() {
|
||||||
let miner = miner_service();
|
let miner = miner_service();
|
||||||
@ -236,3 +225,29 @@ fn rpc_parity_remove_transaction() {
|
|||||||
miner.pending_transactions.lock().insert(hash, signed);
|
miner.pending_transactions.lock().insert(hash, signed);
|
||||||
assert_eq!(io.handle_request_sync(&request), Some(response.to_owned()));
|
assert_eq!(io.handle_request_sync(&request), Some(response.to_owned()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rpc_parity_set_engine_signer() {
|
||||||
|
use accounts::AccountProvider;
|
||||||
|
use bytes::ToPretty;
|
||||||
|
use v1::impls::ParitySetAccountsClient;
|
||||||
|
use v1::traits::ParitySetAccounts;
|
||||||
|
|
||||||
|
let account_provider = Arc::new(AccountProvider::transient_provider());
|
||||||
|
account_provider.insert_account(::hash::keccak("cow").into(), &"password".into()).unwrap();
|
||||||
|
|
||||||
|
let miner = miner_service();
|
||||||
|
let mut io = IoHandler::new();
|
||||||
|
io.extend_with(
|
||||||
|
ParitySetAccountsClient::new(&account_provider, &miner).to_delegate()
|
||||||
|
);
|
||||||
|
|
||||||
|
let request = r#"{"jsonrpc": "2.0", "method": "parity_setEngineSigner", "params":["0xcd2a3d9f938e13cd947ec05abc7fe734df8dd826", "password"], "id": 1}"#;
|
||||||
|
let response = r#"{"jsonrpc":"2.0","result":true,"id":1}"#;
|
||||||
|
|
||||||
|
assert_eq!(io.handle_request_sync(request), Some(response.to_owned()));
|
||||||
|
assert_eq!(miner.authoring_params().author, Address::from_str("cd2a3d9f938e13cd947ec05abc7fe734df8dd826").unwrap());
|
||||||
|
let signature = miner.signer.read().as_ref().unwrap().sign(::hash::keccak("x")).unwrap().to_vec();
|
||||||
|
assert_eq!(&format!("{}", signature.pretty()), "6f46069ded2154af6e806706e4f7f6fd310ac45f3c6dccb85f11c0059ee20a09245df0a0008bb84a10882b1298284bc93058e7bc5938ea728e77620061687a6401");
|
||||||
|
}
|
||||||
|
|
||||||
|
@ -19,7 +19,7 @@ use std::str::FromStr;
|
|||||||
|
|
||||||
use bytes::ToPretty;
|
use bytes::ToPretty;
|
||||||
use ethereum_types::{U256, Address};
|
use ethereum_types::{U256, Address};
|
||||||
use ethcore::account_provider::AccountProvider;
|
use accounts::AccountProvider;
|
||||||
use ethcore::client::TestBlockChainClient;
|
use ethcore::client::TestBlockChainClient;
|
||||||
use jsonrpc_core::IoHandler;
|
use jsonrpc_core::IoHandler;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
|
@ -17,7 +17,7 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use crypto::DEFAULT_MAC;
|
use crypto::DEFAULT_MAC;
|
||||||
use ethcore::account_provider::AccountProvider;
|
use accounts::AccountProvider;
|
||||||
use ethkey::{KeyPair, Signature, verify_public};
|
use ethkey::{KeyPair, Signature, verify_public};
|
||||||
|
|
||||||
use serde_json;
|
use serde_json;
|
||||||
|
@ -19,7 +19,7 @@ use std::str::FromStr;
|
|||||||
use ethereum_types::{U256, Address};
|
use ethereum_types::{U256, Address};
|
||||||
use bytes::ToPretty;
|
use bytes::ToPretty;
|
||||||
|
|
||||||
use ethcore::account_provider::AccountProvider;
|
use accounts::AccountProvider;
|
||||||
use ethcore::client::TestBlockChainClient;
|
use ethcore::client::TestBlockChainClient;
|
||||||
use parity_runtime::Runtime;
|
use parity_runtime::Runtime;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
@ -32,8 +32,9 @@ use v1::{SignerClient, Signer, Origin};
|
|||||||
use v1::metadata::Metadata;
|
use v1::metadata::Metadata;
|
||||||
use v1::tests::helpers::TestMinerService;
|
use v1::tests::helpers::TestMinerService;
|
||||||
use v1::types::{Bytes as RpcBytes, H520};
|
use v1::types::{Bytes as RpcBytes, H520};
|
||||||
use v1::helpers::{nonce, SigningQueue, SignerService, FilledTransactionRequest, ConfirmationPayload};
|
use v1::helpers::{nonce, FilledTransactionRequest, ConfirmationPayload};
|
||||||
use v1::helpers::dispatch::{FullDispatcher, eth_data_hash};
|
use v1::helpers::external_signer::{SigningQueue, SignerService};
|
||||||
|
use v1::helpers::dispatch::{self, FullDispatcher, eth_data_hash};
|
||||||
|
|
||||||
struct SignerTester {
|
struct SignerTester {
|
||||||
_runtime: Runtime,
|
_runtime: Runtime,
|
||||||
@ -60,13 +61,14 @@ fn signer_tester() -> SignerTester {
|
|||||||
let runtime = Runtime::with_thread_count(1);
|
let runtime = Runtime::with_thread_count(1);
|
||||||
let signer = Arc::new(SignerService::new_test(false));
|
let signer = Arc::new(SignerService::new_test(false));
|
||||||
let accounts = accounts_provider();
|
let accounts = accounts_provider();
|
||||||
|
let account_signer = Arc::new(dispatch::Signer::new(accounts.clone()));
|
||||||
let client = blockchain_client();
|
let client = blockchain_client();
|
||||||
let miner = miner_service();
|
let miner = miner_service();
|
||||||
let reservations = Arc::new(Mutex::new(nonce::Reservations::new(runtime.executor())));
|
let reservations = Arc::new(Mutex::new(nonce::Reservations::new(runtime.executor())));
|
||||||
|
|
||||||
let dispatcher = FullDispatcher::new(client, miner.clone(), reservations, 50);
|
let dispatcher = FullDispatcher::new(client, miner.clone(), reservations, 50);
|
||||||
let mut io = IoHandler::default();
|
let mut io = IoHandler::default();
|
||||||
io.extend_with(SignerClient::new(&accounts, dispatcher, &signer, runtime.executor()).to_delegate());
|
io.extend_with(SignerClient::new(account_signer, dispatcher, &signer, runtime.executor()).to_delegate());
|
||||||
|
|
||||||
SignerTester {
|
SignerTester {
|
||||||
_runtime: runtime,
|
_runtime: runtime,
|
||||||
@ -555,29 +557,3 @@ fn should_generate_new_token() {
|
|||||||
// then
|
// then
|
||||||
assert_eq!(tester.io.handle_request_sync(&request), Some(response.to_owned()));
|
assert_eq!(tester.io.handle_request_sync(&request), Some(response.to_owned()));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn should_generate_new_web_proxy_token() {
|
|
||||||
use jsonrpc_core::{Response, Output, Value};
|
|
||||||
// given
|
|
||||||
let tester = signer_tester();
|
|
||||||
|
|
||||||
// when
|
|
||||||
let request = r#"{
|
|
||||||
"jsonrpc":"2.0",
|
|
||||||
"method":"signer_generateWebProxyAccessToken",
|
|
||||||
"params":["https://parity.io"],
|
|
||||||
"id":1
|
|
||||||
}"#;
|
|
||||||
let response = tester.io.handle_request_sync(&request).unwrap();
|
|
||||||
let result = serde_json::from_str(&response).unwrap();
|
|
||||||
|
|
||||||
if let Response::Single(Output::Success(ref success)) = result {
|
|
||||||
if let Value::String(ref token) = success.result {
|
|
||||||
assert_eq!(tester.signer.web_proxy_access_token_domain(&token), Some("https://parity.io".into()));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
assert!(false, "Expected successful response, got: {:?}", result);
|
|
||||||
}
|
|
||||||
|
@ -25,14 +25,15 @@ use jsonrpc_core::futures::Future;
|
|||||||
use v1::impls::SigningQueueClient;
|
use v1::impls::SigningQueueClient;
|
||||||
use v1::metadata::Metadata;
|
use v1::metadata::Metadata;
|
||||||
use v1::traits::{EthSigning, ParitySigning, Parity};
|
use v1::traits::{EthSigning, ParitySigning, Parity};
|
||||||
use v1::helpers::{nonce, SignerService, SigningQueue, FullDispatcher};
|
use v1::helpers::{nonce, dispatch, FullDispatcher};
|
||||||
|
use v1::helpers::external_signer::{SignerService, SigningQueue};
|
||||||
use v1::types::{ConfirmationResponse, RichRawTransaction};
|
use v1::types::{ConfirmationResponse, RichRawTransaction};
|
||||||
use v1::tests::helpers::TestMinerService;
|
use v1::tests::helpers::TestMinerService;
|
||||||
use v1::tests::mocked::parity;
|
use v1::tests::mocked::parity;
|
||||||
|
|
||||||
use ethereum_types::{U256, Address};
|
use accounts::AccountProvider;
|
||||||
use bytes::ToPretty;
|
use bytes::ToPretty;
|
||||||
use ethcore::account_provider::AccountProvider;
|
use ethereum_types::{U256, Address};
|
||||||
use ethcore::client::TestBlockChainClient;
|
use ethcore::client::TestBlockChainClient;
|
||||||
use ethkey::Secret;
|
use ethkey::Secret;
|
||||||
use ethstore::ethkey::{Generator, Random};
|
use ethstore::ethkey::{Generator, Random};
|
||||||
@ -57,6 +58,7 @@ impl Default for SigningTester {
|
|||||||
let client = Arc::new(TestBlockChainClient::default());
|
let client = Arc::new(TestBlockChainClient::default());
|
||||||
let miner = Arc::new(TestMinerService::default());
|
let miner = Arc::new(TestMinerService::default());
|
||||||
let accounts = Arc::new(AccountProvider::transient_provider());
|
let accounts = Arc::new(AccountProvider::transient_provider());
|
||||||
|
let account_signer = Arc::new(dispatch::Signer::new(accounts.clone())) as _;
|
||||||
let reservations = Arc::new(Mutex::new(nonce::Reservations::new(runtime.executor())));
|
let reservations = Arc::new(Mutex::new(nonce::Reservations::new(runtime.executor())));
|
||||||
let mut io = IoHandler::default();
|
let mut io = IoHandler::default();
|
||||||
|
|
||||||
@ -64,9 +66,9 @@ impl Default for SigningTester {
|
|||||||
|
|
||||||
let executor = Executor::new_thread_per_future();
|
let executor = Executor::new_thread_per_future();
|
||||||
|
|
||||||
let rpc = SigningQueueClient::new(&signer, dispatcher.clone(), executor.clone(), &accounts);
|
let rpc = SigningQueueClient::new(&signer, dispatcher.clone(), executor.clone(), &account_signer);
|
||||||
io.extend_with(EthSigning::to_delegate(rpc));
|
io.extend_with(EthSigning::to_delegate(rpc));
|
||||||
let rpc = SigningQueueClient::new(&signer, dispatcher, executor, &accounts);
|
let rpc = SigningQueueClient::new(&signer, dispatcher, executor, &account_signer);
|
||||||
io.extend_with(ParitySigning::to_delegate(rpc));
|
io.extend_with(ParitySigning::to_delegate(rpc));
|
||||||
|
|
||||||
SigningTester {
|
SigningTester {
|
||||||
@ -84,6 +86,30 @@ fn eth_signing() -> SigningTester {
|
|||||||
SigningTester::default()
|
SigningTester::default()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rpc_eth_sign() {
|
||||||
|
use rustc_hex::FromHex;
|
||||||
|
|
||||||
|
let tester = eth_signing();
|
||||||
|
|
||||||
|
let account = tester.accounts.insert_account(Secret::from([69u8; 32]), &"abcd".into()).unwrap();
|
||||||
|
tester.accounts.unlock_account_permanently(account, "abcd".into()).unwrap();
|
||||||
|
let _message = "0cc175b9c0f1b6a831c399e26977266192eb5ffee6ae2fec3ad71c777531578f".from_hex().unwrap();
|
||||||
|
|
||||||
|
let req = r#"{
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"method": "eth_sign",
|
||||||
|
"params": [
|
||||||
|
""#.to_owned() + &format!("0x{:x}", account) + r#"",
|
||||||
|
"0x0cc175b9c0f1b6a831c399e26977266192eb5ffee6ae2fec3ad71c777531578f"
|
||||||
|
],
|
||||||
|
"id": 1
|
||||||
|
}"#;
|
||||||
|
let res = r#"{"jsonrpc":"2.0","result":"0xa2870db1d0c26ef93c7b72d2a0830fa6b841e0593f7186bc6c7cc317af8cf3a42fda03bd589a49949aa05db83300cdb553116274518dbe9d90c65d0213f4af491b","id":1}"#;
|
||||||
|
|
||||||
|
assert_eq!(tester.io.handle_request_sync(&req), Some(res.into()));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn should_add_sign_to_queue() {
|
fn should_add_sign_to_queue() {
|
||||||
// given
|
// given
|
||||||
|
237
rpc/src/v1/tests/mocked/signing_unsafe.rs
Normal file
237
rpc/src/v1/tests/mocked/signing_unsafe.rs
Normal file
@ -0,0 +1,237 @@
|
|||||||
|
// 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 <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
use std::str::FromStr;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use accounts::AccountProvider;
|
||||||
|
use ethcore::client::TestBlockChainClient;
|
||||||
|
use ethereum_types::{U256, Address};
|
||||||
|
use parity_runtime::Runtime;
|
||||||
|
use parking_lot::Mutex;
|
||||||
|
use rlp;
|
||||||
|
use rustc_hex::ToHex;
|
||||||
|
use types::transaction::{Transaction, Action};
|
||||||
|
|
||||||
|
use jsonrpc_core::IoHandler;
|
||||||
|
use v1::{EthClientOptions, EthSigning, SigningUnsafeClient};
|
||||||
|
use v1::helpers::nonce;
|
||||||
|
use v1::helpers::dispatch::{self, FullDispatcher};
|
||||||
|
use v1::tests::helpers::{TestMinerService};
|
||||||
|
use v1::metadata::Metadata;
|
||||||
|
|
||||||
|
fn blockchain_client() -> Arc<TestBlockChainClient> {
|
||||||
|
let client = TestBlockChainClient::new();
|
||||||
|
Arc::new(client)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn accounts_provider() -> Arc<AccountProvider> {
|
||||||
|
Arc::new(AccountProvider::transient_provider())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn miner_service() -> Arc<TestMinerService> {
|
||||||
|
Arc::new(TestMinerService::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
struct EthTester {
|
||||||
|
pub runtime: Runtime,
|
||||||
|
pub client: Arc<TestBlockChainClient>,
|
||||||
|
pub accounts_provider: Arc<AccountProvider>,
|
||||||
|
pub miner: Arc<TestMinerService>,
|
||||||
|
pub io: IoHandler<Metadata>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for EthTester {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::new_with_options(Default::default())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl EthTester {
|
||||||
|
pub fn new_with_options(options: EthClientOptions) -> Self {
|
||||||
|
let runtime = Runtime::with_thread_count(1);
|
||||||
|
let client = blockchain_client();
|
||||||
|
let accounts_provider = accounts_provider();
|
||||||
|
let ap = Arc::new(dispatch::Signer::new(accounts_provider.clone())) as _;
|
||||||
|
let miner = miner_service();
|
||||||
|
let gas_price_percentile = options.gas_price_percentile;
|
||||||
|
let reservations = Arc::new(Mutex::new(nonce::Reservations::new(runtime.executor())));
|
||||||
|
|
||||||
|
let dispatcher = FullDispatcher::new(client.clone(), miner.clone(), reservations, gas_price_percentile);
|
||||||
|
let sign = SigningUnsafeClient::new(&ap, dispatcher).to_delegate();
|
||||||
|
let mut io: IoHandler<Metadata> = IoHandler::default();
|
||||||
|
io.extend_with(sign);
|
||||||
|
|
||||||
|
EthTester {
|
||||||
|
runtime,
|
||||||
|
client,
|
||||||
|
miner,
|
||||||
|
io,
|
||||||
|
accounts_provider,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rpc_eth_send_transaction() {
|
||||||
|
let tester = EthTester::default();
|
||||||
|
let address = tester.accounts_provider.new_account(&"".into()).unwrap();
|
||||||
|
tester.accounts_provider.unlock_account_permanently(address, "".into()).unwrap();
|
||||||
|
let request = r#"{
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"method": "eth_sendTransaction",
|
||||||
|
"params": [{
|
||||||
|
"from": ""#.to_owned() + format!("0x{:x}", address).as_ref() + r#"",
|
||||||
|
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
|
||||||
|
"gas": "0x76c0",
|
||||||
|
"gasPrice": "0x9184e72a000",
|
||||||
|
"value": "0x9184e72a"
|
||||||
|
}],
|
||||||
|
"id": 1
|
||||||
|
}"#;
|
||||||
|
|
||||||
|
let t = Transaction {
|
||||||
|
nonce: U256::zero(),
|
||||||
|
gas_price: U256::from(0x9184e72a000u64),
|
||||||
|
gas: U256::from(0x76c0),
|
||||||
|
action: Action::Call(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
|
||||||
|
value: U256::from(0x9184e72au64),
|
||||||
|
data: vec![]
|
||||||
|
};
|
||||||
|
let signature = tester.accounts_provider.sign(address, None, t.hash(None)).unwrap();
|
||||||
|
let t = t.with_signature(signature, None);
|
||||||
|
|
||||||
|
let response = r#"{"jsonrpc":"2.0","result":""#.to_owned() + format!("0x{:x}", t.hash()).as_ref() + r#"","id":1}"#;
|
||||||
|
|
||||||
|
assert_eq!(tester.io.handle_request_sync(&request), Some(response));
|
||||||
|
|
||||||
|
tester.miner.increment_nonce(&address);
|
||||||
|
|
||||||
|
let t = Transaction {
|
||||||
|
nonce: U256::one(),
|
||||||
|
gas_price: U256::from(0x9184e72a000u64),
|
||||||
|
gas: U256::from(0x76c0),
|
||||||
|
action: Action::Call(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
|
||||||
|
value: U256::from(0x9184e72au64),
|
||||||
|
data: vec![]
|
||||||
|
};
|
||||||
|
let signature = tester.accounts_provider.sign(address, None, t.hash(None)).unwrap();
|
||||||
|
let t = t.with_signature(signature, None);
|
||||||
|
|
||||||
|
let response = r#"{"jsonrpc":"2.0","result":""#.to_owned() + format!("0x{:x}", t.hash()).as_ref() + r#"","id":1}"#;
|
||||||
|
|
||||||
|
assert_eq!(tester.io.handle_request_sync(&request), Some(response));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rpc_eth_sign_transaction() {
|
||||||
|
let tester = EthTester::default();
|
||||||
|
let address = tester.accounts_provider.new_account(&"".into()).unwrap();
|
||||||
|
tester.accounts_provider.unlock_account_permanently(address, "".into()).unwrap();
|
||||||
|
let request = r#"{
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"method": "eth_signTransaction",
|
||||||
|
"params": [{
|
||||||
|
"from": ""#.to_owned() + format!("0x{:x}", address).as_ref() + r#"",
|
||||||
|
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
|
||||||
|
"gas": "0x76c0",
|
||||||
|
"gasPrice": "0x9184e72a000",
|
||||||
|
"value": "0x9184e72a"
|
||||||
|
}],
|
||||||
|
"id": 1
|
||||||
|
}"#;
|
||||||
|
|
||||||
|
let t = Transaction {
|
||||||
|
nonce: U256::one(),
|
||||||
|
gas_price: U256::from(0x9184e72a000u64),
|
||||||
|
gas: U256::from(0x76c0),
|
||||||
|
action: Action::Call(Address::from_str("d46e8dd67c5d32be8058bb8eb970870f07244567").unwrap()),
|
||||||
|
value: U256::from(0x9184e72au64),
|
||||||
|
data: vec![]
|
||||||
|
};
|
||||||
|
let signature = tester.accounts_provider.sign(address, None, t.hash(None)).unwrap();
|
||||||
|
let t = t.with_signature(signature, None);
|
||||||
|
let signature = t.signature();
|
||||||
|
let rlp = rlp::encode(&t);
|
||||||
|
|
||||||
|
let response = r#"{"jsonrpc":"2.0","result":{"#.to_owned() +
|
||||||
|
r#""raw":"0x"# + &rlp.to_hex() + r#"","# +
|
||||||
|
r#""tx":{"# +
|
||||||
|
r#""blockHash":null,"blockNumber":null,"# +
|
||||||
|
&format!("\"chainId\":{},", t.chain_id().map_or("null".to_owned(), |n| format!("{}", n))) +
|
||||||
|
r#""condition":null,"creates":null,"# +
|
||||||
|
&format!("\"from\":\"0x{:x}\",", &address) +
|
||||||
|
r#""gas":"0x76c0","gasPrice":"0x9184e72a000","# +
|
||||||
|
&format!("\"hash\":\"0x{:x}\",", t.hash()) +
|
||||||
|
r#""input":"0x","# +
|
||||||
|
r#""nonce":"0x1","# +
|
||||||
|
&format!("\"publicKey\":\"0x{:x}\",", t.recover_public().unwrap()) +
|
||||||
|
&format!("\"r\":\"0x{:x}\",", U256::from(signature.r())) +
|
||||||
|
&format!("\"raw\":\"0x{}\",", rlp.to_hex()) +
|
||||||
|
&format!("\"s\":\"0x{:x}\",", U256::from(signature.s())) +
|
||||||
|
&format!("\"standardV\":\"0x{:x}\",", U256::from(t.standard_v())) +
|
||||||
|
r#""to":"0xd46e8dd67c5d32be8058bb8eb970870f07244567","transactionIndex":null,"# +
|
||||||
|
&format!("\"v\":\"0x{:x}\",", U256::from(t.original_v())) +
|
||||||
|
r#""value":"0x9184e72a""# +
|
||||||
|
r#"}},"id":1}"#;
|
||||||
|
|
||||||
|
tester.miner.increment_nonce(&address);
|
||||||
|
|
||||||
|
assert_eq!(tester.io.handle_request_sync(&request), Some(response));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rpc_eth_send_transaction_with_bad_to() {
|
||||||
|
let tester = EthTester::default();
|
||||||
|
let address = tester.accounts_provider.new_account(&"".into()).unwrap();
|
||||||
|
let request = r#"{
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"method": "eth_sendTransaction",
|
||||||
|
"params": [{
|
||||||
|
"from": ""#.to_owned() + format!("0x{:x}", address).as_ref() + r#"",
|
||||||
|
"to": "",
|
||||||
|
"gas": "0x76c0",
|
||||||
|
"gasPrice": "0x9184e72a000",
|
||||||
|
"value": "0x9184e72a"
|
||||||
|
}],
|
||||||
|
"id": 1
|
||||||
|
}"#;
|
||||||
|
|
||||||
|
let response = r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid params: expected a hex-encoded hash with 0x prefix."},"id":1}"#;
|
||||||
|
|
||||||
|
assert_eq!(tester.io.handle_request_sync(&request), Some(response.into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rpc_eth_send_transaction_error() {
|
||||||
|
let tester = EthTester::default();
|
||||||
|
let address = tester.accounts_provider.new_account(&"".into()).unwrap();
|
||||||
|
let request = r#"{
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"method": "eth_sendTransaction",
|
||||||
|
"params": [{
|
||||||
|
"from": ""#.to_owned() + format!("0x{:x}", address).as_ref() + r#"",
|
||||||
|
"to": "0xd46e8dd67c5d32be8058bb8eb970870f07244567",
|
||||||
|
"gas": "0x76c0",
|
||||||
|
"gasPrice": "0x9184e72a000",
|
||||||
|
"value": "0x9184e72a"
|
||||||
|
}],
|
||||||
|
"id": 1
|
||||||
|
}"#;
|
||||||
|
|
||||||
|
let response = r#"{"jsonrpc":"2.0","error":{"code":-32020,"message":"Your account is locked. Unlock the account via CLI, personal_unlockAccount or use Trusted Signer.","data":"NotUnlocked"},"id":1}"#;
|
||||||
|
assert_eq!(tester.io.handle_request_sync(&request), Some(response.into()));
|
||||||
|
}
|
@ -40,8 +40,8 @@ pub use self::eth_pubsub::EthPubSub;
|
|||||||
pub use self::eth_signing::EthSigning;
|
pub use self::eth_signing::EthSigning;
|
||||||
pub use self::net::Net;
|
pub use self::net::Net;
|
||||||
pub use self::parity::Parity;
|
pub use self::parity::Parity;
|
||||||
pub use self::parity_accounts::ParityAccounts;
|
pub use self::parity_accounts::{ParityAccounts, ParityAccountsInfo};
|
||||||
pub use self::parity_set::ParitySet;
|
pub use self::parity_set::{ParitySet, ParitySetAccounts};
|
||||||
pub use self::parity_signing::ParitySigning;
|
pub use self::parity_signing::ParitySigning;
|
||||||
pub use self::personal::Personal;
|
pub use self::personal::Personal;
|
||||||
pub use self::private::Private;
|
pub use self::private::Private;
|
||||||
|
@ -26,7 +26,7 @@ use v1::types::{
|
|||||||
TransactionStats, LocalTransactionStatus,
|
TransactionStats, LocalTransactionStatus,
|
||||||
BlockNumber, ConsensusCapability, VersionInfo,
|
BlockNumber, ConsensusCapability, VersionInfo,
|
||||||
OperationsInfo, ChainStatus, Log, Filter,
|
OperationsInfo, ChainStatus, Log, Filter,
|
||||||
AccountInfo, HwAccountInfo, RichHeader, Receipt,
|
RichHeader, Receipt,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Parity-specific rpc interface.
|
/// Parity-specific rpc interface.
|
||||||
@ -35,22 +35,6 @@ pub trait Parity {
|
|||||||
/// RPC Metadata
|
/// RPC Metadata
|
||||||
type Metadata;
|
type Metadata;
|
||||||
|
|
||||||
/// Returns accounts information.
|
|
||||||
#[rpc(name = "parity_accountsInfo")]
|
|
||||||
fn accounts_info(&self) -> Result<BTreeMap<H160, AccountInfo>>;
|
|
||||||
|
|
||||||
/// Returns hardware accounts information.
|
|
||||||
#[rpc(name = "parity_hardwareAccountsInfo")]
|
|
||||||
fn hardware_accounts_info(&self) -> Result<BTreeMap<H160, HwAccountInfo>>;
|
|
||||||
|
|
||||||
/// Get a list of paths to locked hardware wallets
|
|
||||||
#[rpc(name = "parity_lockedHardwareAccountsInfo")]
|
|
||||||
fn locked_hardware_accounts_info(&self) -> Result<Vec<String>>;
|
|
||||||
|
|
||||||
/// Returns default account for dapp.
|
|
||||||
#[rpc(name = "parity_defaultAccount")]
|
|
||||||
fn default_account(&self) -> Result<H160>;
|
|
||||||
|
|
||||||
/// Returns current transactions limit.
|
/// Returns current transactions limit.
|
||||||
#[rpc(name = "parity_transactionsLimit")]
|
#[rpc(name = "parity_transactionsLimit")]
|
||||||
fn transactions_limit(&self) -> Result<usize>;
|
fn transactions_limit(&self) -> Result<usize>;
|
||||||
|
@ -22,6 +22,27 @@ use jsonrpc_derive::rpc;
|
|||||||
use ethkey::Password;
|
use ethkey::Password;
|
||||||
use ethstore::KeyFile;
|
use ethstore::KeyFile;
|
||||||
use v1::types::{H160, H256, H520, DeriveHash, DeriveHierarchical, ExtAccountInfo};
|
use v1::types::{H160, H256, H520, DeriveHash, DeriveHierarchical, ExtAccountInfo};
|
||||||
|
use v1::types::{AccountInfo, HwAccountInfo};
|
||||||
|
|
||||||
|
/// Parity-specific read-only accounts rpc interface.
|
||||||
|
#[rpc]
|
||||||
|
pub trait ParityAccountsInfo {
|
||||||
|
/// Returns accounts information.
|
||||||
|
#[rpc(name = "parity_accountsInfo")]
|
||||||
|
fn accounts_info(&self) -> Result<BTreeMap<H160, AccountInfo>>;
|
||||||
|
|
||||||
|
/// Returns hardware accounts information.
|
||||||
|
#[rpc(name = "parity_hardwareAccountsInfo")]
|
||||||
|
fn hardware_accounts_info(&self) -> Result<BTreeMap<H160, HwAccountInfo>>;
|
||||||
|
|
||||||
|
/// Get a list of paths to locked hardware wallets
|
||||||
|
#[rpc(name = "parity_lockedHardwareAccountsInfo")]
|
||||||
|
fn locked_hardware_accounts_info(&self) -> Result<Vec<String>>;
|
||||||
|
|
||||||
|
/// Returns default account for dapp.
|
||||||
|
#[rpc(name = "parity_defaultAccount")]
|
||||||
|
fn default_account(&self) -> Result<H160>;
|
||||||
|
}
|
||||||
|
|
||||||
/// Personal Parity rpc interface.
|
/// Personal Parity rpc interface.
|
||||||
#[rpc]
|
#[rpc]
|
||||||
|
@ -21,6 +21,14 @@ use jsonrpc_derive::rpc;
|
|||||||
|
|
||||||
use v1::types::{Bytes, H160, H256, U256, ReleaseInfo, Transaction};
|
use v1::types::{Bytes, H160, H256, U256, ReleaseInfo, Transaction};
|
||||||
|
|
||||||
|
/// Parity-specific rpc interface for operations altering the account-related settings.
|
||||||
|
#[rpc]
|
||||||
|
pub trait ParitySetAccounts {
|
||||||
|
/// Sets account for signing consensus messages.
|
||||||
|
#[rpc(name = "parity_setEngineSigner")]
|
||||||
|
fn set_engine_signer(&self, H160, String) -> Result<bool>;
|
||||||
|
}
|
||||||
|
|
||||||
/// Parity-specific rpc interface for operations altering the settings.
|
/// Parity-specific rpc interface for operations altering the settings.
|
||||||
#[rpc]
|
#[rpc]
|
||||||
pub trait ParitySet {
|
pub trait ParitySet {
|
||||||
@ -44,9 +52,9 @@ pub trait ParitySet {
|
|||||||
#[rpc(name = "parity_setAuthor")]
|
#[rpc(name = "parity_setAuthor")]
|
||||||
fn set_author(&self, H160) -> Result<bool>;
|
fn set_author(&self, H160) -> Result<bool>;
|
||||||
|
|
||||||
/// Sets account for signing consensus messages.
|
/// Sets the secret of engine signer account.
|
||||||
#[rpc(name = "parity_setEngineSigner")]
|
#[rpc(name = "parity_setEngineSignerSecret")]
|
||||||
fn set_engine_signer(&self, H160, String) -> Result<bool>;
|
fn set_engine_signer_secret(&self, H256) -> Result<bool>;
|
||||||
|
|
||||||
/// Sets the limits for transaction queue.
|
/// Sets the limits for transaction queue.
|
||||||
#[rpc(name = "parity_setTransactionsLimit")]
|
#[rpc(name = "parity_setTransactionsLimit")]
|
||||||
|
@ -51,10 +51,6 @@ pub trait Signer {
|
|||||||
#[rpc(name = "signer_generateAuthorizationToken")]
|
#[rpc(name = "signer_generateAuthorizationToken")]
|
||||||
fn generate_token(&self) -> Result<String>;
|
fn generate_token(&self) -> Result<String>;
|
||||||
|
|
||||||
/// Generates new web proxy access token for particular domain.
|
|
||||||
#[rpc(name = "signer_generateWebProxyAccessToken")]
|
|
||||||
fn generate_web_proxy_token(&self, String) -> Result<String>;
|
|
||||||
|
|
||||||
/// Subscribe to new pending requests on signer interface.
|
/// Subscribe to new pending requests on signer interface.
|
||||||
#[pubsub(subscription = "signer_pending", subscribe, name = "signer_subscribePending")]
|
#[pubsub(subscription = "signer_pending", subscribe, name = "signer_subscribePending")]
|
||||||
fn subscribe_pending(&self, Self::Metadata, Subscriber<Vec<ConfirmationRequest>>);
|
fn subscribe_pending(&self, Self::Metadata, Subscriber<Vec<ConfirmationRequest>>);
|
||||||
|
@ -8,36 +8,40 @@ authors = ["Parity Technologies <admin@parity.io>"]
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
byteorder = "1.0"
|
byteorder = "1.0"
|
||||||
common-types = { path = "../ethcore/types" }
|
common-types = { path = "../ethcore/types" }
|
||||||
|
ethabi = "6.0"
|
||||||
|
ethabi-contract = "6.0"
|
||||||
|
ethabi-derive = "6.0"
|
||||||
|
ethcore = { path = "../ethcore" }
|
||||||
|
ethcore-accounts = { path = "../accounts", optional = true}
|
||||||
ethcore-call-contract = { path = "../ethcore/call-contract" }
|
ethcore-call-contract = { path = "../ethcore/call-contract" }
|
||||||
log = "0.4"
|
ethcore-sync = { path = "../ethcore/sync" }
|
||||||
parking_lot = "0.7"
|
ethereum-types = "0.4"
|
||||||
hyper = { version = "0.12", default-features = false }
|
ethkey = { path = "../accounts/ethkey" }
|
||||||
serde = "1.0"
|
|
||||||
serde_json = "1.0"
|
|
||||||
serde_derive = "1.0"
|
|
||||||
futures = "0.1"
|
futures = "0.1"
|
||||||
|
hyper = { version = "0.12", default-features = false }
|
||||||
|
keccak-hash = "0.1"
|
||||||
|
kvdb = "0.1"
|
||||||
|
lazy_static = "1.0"
|
||||||
|
log = "0.4"
|
||||||
|
parity-bytes = "0.1"
|
||||||
|
parity-crypto = "0.3"
|
||||||
|
parity-runtime = { path = "../util/runtime" }
|
||||||
|
parking_lot = "0.7"
|
||||||
rustc-hex = "1.0"
|
rustc-hex = "1.0"
|
||||||
|
serde = "1.0"
|
||||||
|
serde_derive = "1.0"
|
||||||
|
serde_json = "1.0"
|
||||||
tiny-keccak = "1.4"
|
tiny-keccak = "1.4"
|
||||||
tokio = "~0.1.11"
|
tokio = "~0.1.11"
|
||||||
parity-runtime = { path = "../util/runtime" }
|
|
||||||
tokio-io = "0.1"
|
tokio-io = "0.1"
|
||||||
tokio-service = "0.1"
|
tokio-service = "0.1"
|
||||||
url = "1.0"
|
url = "1.0"
|
||||||
ethcore = { path = "../ethcore" }
|
|
||||||
parity-bytes = "0.1"
|
|
||||||
parity-crypto = "0.3.0"
|
|
||||||
ethcore-sync = { path = "../ethcore/sync" }
|
|
||||||
ethereum-types = "0.4"
|
|
||||||
kvdb = "0.1"
|
|
||||||
keccak-hash = "0.1"
|
|
||||||
ethkey = { path = "../accounts/ethkey" }
|
|
||||||
lazy_static = "1.0"
|
|
||||||
ethabi = "6.0"
|
|
||||||
ethabi-derive = "6.0"
|
|
||||||
ethabi-contract = "6.0"
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
env_logger = "0.5"
|
env_logger = "0.5"
|
||||||
ethcore = { path = "../ethcore", features = ["test-helpers"] }
|
ethcore = { path = "../ethcore", features = ["test-helpers"] }
|
||||||
tempdir = "0.3"
|
tempdir = "0.3"
|
||||||
kvdb-rocksdb = "0.1.3"
|
kvdb-rocksdb = "0.1.3"
|
||||||
|
|
||||||
|
[features]
|
||||||
|
accounts = ["ethcore-accounts"]
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user