Skip to content
This repository has been archived by the owner on Nov 6, 2020. It is now read-only.

Commit

Permalink
private-tx: replace error_chain (#10510)
Browse files Browse the repository at this point in the history
* Update to vanilla tx pool error

* private-tx: remove error-chain, implement Error, derive Display

* private-tx: replace ErrorKind and bail!

* private-tx: add missing From impls and other compiler errors

* private-tx: use original tx-pool error

* Don't be silly cargo
  • Loading branch information
ascjones committed Apr 1, 2019
1 parent d700988 commit b63599e
Show file tree
Hide file tree
Showing 6 changed files with 57 additions and 49 deletions.
14 changes: 13 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion ethcore/private-tx/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ authors = ["Parity Technologies <admin@parity.io>"]

[dependencies]
common-types = { path = "../types" }
error-chain = { version = "0.12", default-features = false }
derive_more = "0.14.0"
ethabi = "6.0"
ethabi-contract = "6.0"
ethabi-derive = "6.0"
Expand Down
26 changes: 13 additions & 13 deletions ethcore/private-tx/src/encryptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use crypto;
use futures::Future;
use fetch::{Fetch, Client as FetchClient, Method, BodyReader, Request};
use bytes::{Bytes, ToPretty};
use error::{Error, ErrorKind};
use error::Error;
use url::Url;
use super::Signer;
use super::key_server_keys::address_to_key;
Expand Down Expand Up @@ -111,11 +111,11 @@ impl SecretStoreEncryptor {
return Ok(key);
}
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(|| Error::KeyServerAccountNotSet)?;

// key id in SS is H256 && we have H160 here => expand with assitional zeros
let contract_address_extended: H256 = contract_address.into();
let base_url = self.config.base_url.clone().ok_or_else(|| ErrorKind::KeyServerNotSet)?;
let base_url = self.config.base_url.clone().ok_or_else(|| Error::KeyServerNotSet)?;

// prepare request url
let url = format!("{}/{}/{}{}",
Expand All @@ -132,24 +132,24 @@ impl SecretStoreEncryptor {
Method::GET
};

let url = Url::from_str(&url).map_err(|e| ErrorKind::Encrypt(e.to_string()))?;
let url = Url::from_str(&url).map_err(|e| Error::Encrypt(e.to_string()))?;
let response = self.client.fetch(Request::new(url, method), Default::default()).wait()
.map_err(|e| ErrorKind::Encrypt(e.to_string()))?;
.map_err(|e| Error::Encrypt(e.to_string()))?;

if response.is_not_found() {
bail!(ErrorKind::EncryptionKeyNotFound(*contract_address));
return Err(Error::EncryptionKeyNotFound(*contract_address));
}

if !response.is_success() {
bail!(ErrorKind::Encrypt(response.status().canonical_reason().unwrap_or("unknown").into()));
return Err(Error::Encrypt(response.status().canonical_reason().unwrap_or("unknown").into()));
}

// read HTTP response
let mut result = String::new();
BodyReader::new(response).read_to_string(&mut result)?;

// 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| Error::Encrypt(e))?;

// decrypt Public
let decrypted_bytes = self.signer.decrypt(requester, &crypto::DEFAULT_MAC, &encrypted_bytes)?;
Expand Down Expand Up @@ -189,7 +189,7 @@ impl SecretStoreEncryptor {
}

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(|| Error::KeyServerAccountNotSet)?;
Ok(self.signer.sign(key_server_account, address_to_key(contract_address))?)
}
}
Expand All @@ -204,7 +204,7 @@ impl Encryptor for SecretStoreEncryptor {
// retrieve the key, try to generate it if it doesn't exist yet
let key = match self.retrieve_key("", false, contract_address) {
Ok(key) => Ok(key),
Err(Error(ErrorKind::EncryptionKeyNotFound(_), _)) => {
Err(Error::EncryptionKeyNotFound(_)) => {
trace!(target: "privatetx", "Key for account wasnt found in sstore. Creating. Address: {:?}", contract_address);
self.retrieve_key(&format!("/{}", self.config.threshold), true, contract_address)
}
Expand All @@ -215,7 +215,7 @@ impl Encryptor for SecretStoreEncryptor {
let mut cypher = Vec::with_capacity(plain_data.len() + initialisation_vector.len());
cypher.extend(repeat(0).take(plain_data.len()));
crypto::aes::encrypt_128_ctr(&key, initialisation_vector, plain_data, &mut cypher)
.map_err(|e| ErrorKind::Encrypt(e.to_string()))?;
.map_err(|e| Error::Encrypt(e.to_string()))?;
cypher.extend_from_slice(&initialisation_vector);

Ok(cypher)
Expand All @@ -230,7 +230,7 @@ impl Encryptor for SecretStoreEncryptor {
// initialization vector takes INIT_VEC_LEN bytes
let cypher_len = cypher.len();
if cypher_len < INIT_VEC_LEN {
bail!(ErrorKind::Decrypt("Invalid cypher".into()));
return Err(Error::Decrypt("Invalid cypher".into()));
}

// retrieve existing key
Expand All @@ -241,7 +241,7 @@ impl Encryptor for SecretStoreEncryptor {
let mut plain_data = Vec::with_capacity(cypher_len - INIT_VEC_LEN);
plain_data.extend(repeat(0).take(cypher_len - INIT_VEC_LEN));
crypto::aes::decrypt_128_ctr(&key, &iv, cypher, &mut plain_data)
.map_err(|e| ErrorKind::Decrypt(e.to_string()))?;
.map_err(|e| Error::Decrypt(e.to_string()))?;
Ok(plain_data)
}
}
Expand Down
53 changes: 26 additions & 27 deletions ethcore/private-tx/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,7 @@ extern crate log;
extern crate ethabi_derive;
#[macro_use]
extern crate ethabi_contract;
#[macro_use]
extern crate error_chain;
extern crate derive_more;
#[macro_use]
extern crate rlp_derive;

Expand All @@ -68,7 +67,7 @@ pub use encryptor::{Encryptor, SecretStoreEncryptor, EncryptorConfig, NoopEncryp
pub use key_server_keys::{KeyProvider, SecretStoreKeys, StoringKeyProvider};
pub use private_transactions::{VerifiedPrivateTransaction, VerificationStore, PrivateTransactionSigningDesc, SigningStore};
pub use messages::{PrivateTransaction, SignedPrivateTransaction};
pub use error::{Error, ErrorKind};
pub use error::Error;

use std::sync::{Arc, Weak};
use std::collections::{HashMap, HashSet, BTreeMap};
Expand Down Expand Up @@ -238,10 +237,10 @@ impl Provider {
trace!(target: "privatetx", "Creating private transaction from regular transaction: {:?}", signed_transaction);
if self.signer_account.is_none() {
warn!(target: "privatetx", "Signing account not set");
bail!(ErrorKind::SignerAccountNotSet);
return Err(Error::SignerAccountNotSet);
}
let tx_hash = signed_transaction.hash();
let contract = Self::contract_address_from_transaction(&signed_transaction).map_err(|_| ErrorKind::BadTransactionType)?;
let contract = Self::contract_address_from_transaction(&signed_transaction).map_err(|_| Error::BadTransactionType)?;
let data = signed_transaction.rlp_bytes();
let encrypted_transaction = self.encrypt(&contract, &Self::iv_from_transaction(&signed_transaction), &data)?;
let private = PrivateTransaction::new(encrypted_transaction, contract);
Expand Down Expand Up @@ -309,19 +308,19 @@ impl Provider {
// TODO #9825 [ToDr] Usage of BlockId::Latest
let contract_nonce = self.get_contract_nonce(&contract, BlockId::Latest);
if let Err(e) = contract_nonce {
bail!("Cannot retrieve contract nonce: {:?}", e);
return Err(format!("Cannot retrieve contract nonce: {:?}", e).into());
}
let contract_nonce = contract_nonce.expect("Error was checked before");
let private_state = self.execute_private_transaction(BlockId::Latest, &transaction.transaction);
if let Err(e) = private_state {
bail!("Cannot retrieve private state: {:?}", e);
return Err(format!("Cannot retrieve private state: {:?}", e).into());
}
let private_state = private_state.expect("Error was checked before");
let private_state_hash = self.calculate_state_hash(&private_state, contract_nonce);
trace!(target: "privatetx", "Hashed effective private state for validator: {:?}", private_state_hash);
let signed_state = self.accounts.sign(validator_account, private_state_hash);
if let Err(e) = signed_state {
bail!("Cannot sign the state: {:?}", e);
return Err(format!("Cannot sign the state: {:?}", e).into());
}
let signed_state = signed_state.expect("Error was checked before");
let signed_private_transaction = SignedPrivateTransaction::new(private_hash, signed_state, None);
Expand Down Expand Up @@ -362,8 +361,8 @@ impl Provider {
signatures.push(signed_tx.signature());
let rsv: Vec<Signature> = signatures.into_iter().map(|sign| sign.into_electrum().into()).collect();
// Create public transaction
let signer_account = self.signer_account.ok_or_else(|| ErrorKind::SignerAccountNotSet)?;
let state = self.client.state_at(BlockId::Latest).ok_or(ErrorKind::StatePruned)?;
let signer_account = self.signer_account.ok_or_else(|| Error::SignerAccountNotSet)?;
let state = self.client.state_at(BlockId::Latest).ok_or(Error::StatePruned)?;
let nonce = state.nonce(&signer_account)?;
let public_tx = self.public_transaction(
desc.state.clone(),
Expand All @@ -382,7 +381,7 @@ impl Provider {
Ok(_) => trace!(target: "privatetx", "Public transaction added to queue"),
Err(err) => {
warn!(target: "privatetx", "Failed to add transaction to queue, error: {:?}", err);
bail!(err);
return Err(err.into());
}
}
// Notify about state changes
Expand All @@ -397,15 +396,15 @@ impl Provider {
// Remove from store for signing
if let Err(err) = self.transactions_for_signing.write().remove(&private_hash) {
warn!(target: "privatetx", "Failed to remove transaction from signing store, error: {:?}", err);
bail!(err);
return Err(err);
}
} else {
// Add signature to the store
match self.transactions_for_signing.write().add_signature(&private_hash, signed_tx.signature()) {
Ok(_) => trace!(target: "privatetx", "Signature stored for private transaction"),
Err(err) => {
warn!(target: "privatetx", "Failed to add signature to signing store, error: {:?}", err);
bail!(err);
return Err(err);
}
}
}
Expand All @@ -417,7 +416,7 @@ impl Provider {
Action::Call(contract) => Ok(contract),
_ => {
warn!(target: "privatetx", "Incorrect type of action for the transaction");
bail!(ErrorKind::BadTransactionType);
return Err(Error::BadTransactionType);
}
}
}
Expand All @@ -436,13 +435,13 @@ impl Provider {
}
false => {
warn!(target: "privatetx", "Sender's state doesn't correspond to validator's");
bail!(ErrorKind::StateIncorrect);
return Err(Error::StateIncorrect);
}
}
}
Err(err) => {
warn!(target: "privatetx", "Sender's state doesn't correspond to validator's, error {:?}", err);
bail!(err);
return Err(err.into());
}
}
}
Expand Down Expand Up @@ -482,21 +481,21 @@ impl Provider {
fn get_decrypted_state(&self, address: &Address, block: BlockId) -> Result<Bytes, Error> {
let (data, decoder) = private_contract::functions::state::call();
let value = self.client.call_contract(block, *address, data)?;
let state = decoder.decode(&value).map_err(|e| ErrorKind::Call(format!("Contract call failed {:?}", e)))?;
let state = decoder.decode(&value).map_err(|e| Error::Call(format!("Contract call failed {:?}", e)))?;
self.decrypt(address, &state)
}

fn get_decrypted_code(&self, address: &Address, block: BlockId) -> Result<Bytes, Error> {
let (data, decoder) = private_contract::functions::code::call();
let value = self.client.call_contract(block, *address, data)?;
let state = decoder.decode(&value).map_err(|e| ErrorKind::Call(format!("Contract call failed {:?}", e)))?;
let state = decoder.decode(&value).map_err(|e| Error::Call(format!("Contract call failed {:?}", e)))?;
self.decrypt(address, &state)
}

pub fn get_contract_nonce(&self, address: &Address, block: BlockId) -> Result<U256, Error> {
let (data, decoder) = private_contract::functions::nonce::call();
let value = self.client.call_contract(block, *address, data)?;
decoder.decode(&value).map_err(|e| ErrorKind::Call(format!("Contract call failed {:?}", e)).into())
decoder.decode(&value).map_err(|e| Error::Call(format!("Contract call failed {:?}", e)).into())
}

fn snapshot_to_storage(raw: Bytes) -> HashMap<H256, H256> {
Expand Down Expand Up @@ -533,10 +532,10 @@ impl Provider {
T: Tracer,
V: VMTracer,
{
let mut env_info = self.client.env_info(block).ok_or(ErrorKind::StatePruned)?;
let mut env_info = self.client.env_info(block).ok_or(Error::StatePruned)?;
env_info.gas_limit = transaction.gas;

let mut state = self.client.state_at(block).ok_or(ErrorKind::StatePruned)?;
let mut state = self.client.state_at(block).ok_or(Error::StatePruned)?;
// TODO #9825 in case of BlockId::Latest these need to operate on the same state
let contract_address = match transaction.action {
Action::Call(ref contract_address) => {
Expand Down Expand Up @@ -612,15 +611,15 @@ impl Provider {
/// Create encrypted public contract deployment transaction.
pub fn public_creation_transaction(&self, block: BlockId, source: &SignedTransaction, validators: &[Address], gas_price: U256) -> Result<(Transaction, Address), Error> {
if let Action::Call(_) = source.action {
bail!(ErrorKind::BadTransactionType);
return Err(Error::BadTransactionType);
}
let sender = source.sender();
let state = self.client.state_at(block).ok_or(ErrorKind::StatePruned)?;
let state = self.client.state_at(block).ok_or(Error::StatePruned)?;
let nonce = state.nonce(&sender)?;
let executed = self.execute_private(source, TransactOptions::with_no_tracing(), block)?;
let header = self.client.block_header(block)
.ok_or(ErrorKind::StatePruned)
.and_then(|h| h.decode().map_err(|_| ErrorKind::StateIncorrect).into())?;
.ok_or(Error::StatePruned)
.and_then(|h| h.decode().map_err(|_| Error::StateIncorrect).into())?;
let (executed_code, executed_state) = (executed.code.unwrap_or_default(), executed.state);
let tx_data = Self::generate_constructor(validators, executed_code.clone(), executed_state.clone());
let mut tx = Transaction {
Expand Down Expand Up @@ -651,7 +650,7 @@ impl Provider {
/// Create encrypted public contract deployment transaction. Returns updated encrypted state.
pub fn execute_private_transaction(&self, block: BlockId, source: &SignedTransaction) -> Result<Bytes, Error> {
if let Action::Create = source.action {
bail!(ErrorKind::BadTransactionType);
return Err(Error::BadTransactionType);
}
let result = self.execute_private(source, TransactOptions::with_no_tracing(), block)?;
Ok(result.state)
Expand Down Expand Up @@ -680,7 +679,7 @@ impl Provider {
pub fn get_validators(&self, block: BlockId, address: &Address) -> Result<Vec<Address>, Error> {
let (data, decoder) = private_contract::functions::get_validators::call();
let value = self.client.call_contract(block, *address, data)?;
decoder.decode(&value).map_err(|e| ErrorKind::Call(format!("Contract call failed {:?}", e)).into())
decoder.decode(&value).map_err(|e| Error::Call(format!("Contract call failed {:?}", e)).into())
}

fn get_contract_version(&self, block: BlockId, address: &Address) -> usize {
Expand Down
6 changes: 3 additions & 3 deletions ethcore/private-tx/src/private_transactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use parking_lot::RwLock;
use types::transaction::{UnverifiedTransaction, SignedTransaction};
use txpool;
use txpool::{VerifiedTransaction, Verifier};
use error::{Error, ErrorKind};
use error::Error;

type Pool = txpool::Pool<VerifiedPrivateTransaction, pool::scoring::NonceAndGasPrice>;

Expand Down Expand Up @@ -229,7 +229,7 @@ impl SigningStore {
contract_nonce: U256,
) -> Result<(), Error> {
if self.transactions.len() > MAX_QUEUE_LEN {
bail!(ErrorKind::QueueIsFull);
return Err(Error::QueueIsFull);
}

self.transactions.insert(private_hash, PrivateTransactionSigningDesc {
Expand All @@ -255,7 +255,7 @@ impl SigningStore {

/// Adds received signature for the stored private transaction
pub fn add_signature(&mut self, private_hash: &H256, signature: Signature) -> Result<(), Error> {
let desc = self.transactions.get_mut(private_hash).ok_or_else(|| ErrorKind::PrivateTransactionNotFound)?;
let desc = self.transactions.get_mut(private_hash).ok_or_else(|| Error::PrivateTransactionNotFound)?;
if !desc.received_signatures.contains(&signature) {
desc.received_signatures.push(signature);
}
Expand Down
5 changes: 1 addition & 4 deletions ethcore/service/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,9 @@ use io;
use ethcore_private_tx;

error_chain! {
links {
PrivateTransactions(ethcore_private_tx::Error, ethcore_private_tx::ErrorKind);
}

foreign_links {
Ethcore(ethcore::error::Error);
IoError(io::IoError);
PrivateTransactions(ethcore_private_tx::Error);
}
}

0 comments on commit b63599e

Please sign in to comment.