Private transactions integration pr (#6422)

* Private transaction message added

* Empty line removed

* Private transactions logic removed from client into the separate module

* Fixed compilation after merge with head

* Signed private transaction message added as well

* Comments after the review fixed

* Private tx execution

* Test update

* Renamed some methods

* Fixed some tests

* Reverted submodules

* Fixed build

* Private transaction message added

* Empty line removed

* Private transactions logic removed from client into the separate module

* Fixed compilation after merge with head

* Signed private transaction message added as well

* Comments after the review fixed

* Encrypted private transaction message and signed reply added

* Private tx execution

* Test update

* Main scenario completed

* Merged with the latest head

* Private transactions API

* Comments after review fixed

* Parameters for private transactions added to parity arguments

* New files added

* New API methods added

* Do not process packets from unconfirmed peers

* Merge with ptm_ss branch

* Encryption and permissioning with key server added

* Fixed compilation after merge

* Version of Parity protocol incremented in order to support private transactions

* Doc strings for constants added

* Proper format for doc string added

* fixed some encryptor.rs grumbles

* Private transactions functionality moved to the separate crate

* Refactoring in order to remove late initialisation

* Tests fixed after moving to the separate crate

* Fetch method removed

* Sync test helpers refactored

* Interaction with encryptor refactored

* Contract address retrieving via substate removed

* Sensible gas limit for private transactions implemented

* New private contract with nonces added

* Parsing of the response from key server fixed

* Build fixed after the merge, native contracts removed

* Crate renamed

* Tests moved to the separate directory

* Handling of errors reworked in order to use error chain

* Encodable macro added, new constructor replaced with default

* Native ethabi usage removed

* Couple conversions optimized

* Interactions with client reworked

* Errors omitting removed

* Fix after merge

* Fix after the merge

* private transactions improvements in progress

* private_transactions -> ethcore/private-tx

* making private transactions more idiomatic

* private-tx encryptor uses shared FetchClient and is more idiomatic

* removed redundant tests, moved integration tests to tests/ dir

* fixed failing service test

* reenable add_notify on private tx provider

* removed private_tx tests from sync module

* removed commented out code

* Use plain password instead of unlocking account manager

* remove dead code

* Link to the contract changed

* Transaction signature chain replay protection module created

* Redundant type conversion removed

* Contract address returned by private provider

* Test fixed

* Addressing grumbles in PrivateTransactions (#8249)

* Tiny fixes part 1.

* A bunch of additional comments and todos.

* Fix ethsync tests.

* resolved merge conflicts

* final private tx pr (#8318)

* added cli option that enables private transactions

* fixed failing test

* fixed failing test

* fixed failing test

* fixed failing test
This commit is contained in:
Anton Gavrilov
2018-04-09 16:14:33 +02:00
committed by Marek Kotewicz
parent c039ab79b5
commit e6f75bccfe
90 changed files with 2745 additions and 192 deletions

View File

@@ -16,6 +16,7 @@ crossbeam = "0.3"
ethash = { path = "../ethash" }
ethcore-bloom-journal = { path = "../util/bloom" }
ethcore-bytes = { path = "../util/bytes" }
fetch = { path = "../util/fetch" }
hashdb = { path = "../util/hashdb" }
memorydb = { path = "../util/memorydb" }
patricia-trie = { path = "../util/patricia_trie" }
@@ -52,6 +53,7 @@ rlp_compress = { path = "../util/rlp_compress" }
rlp_derive = { path = "../util/rlp_derive" }
kvdb = { path = "../util/kvdb" }
kvdb-memorydb = { path = "../util/kvdb-memorydb" }
kvdb-rocksdb = { path = "../util/kvdb-rocksdb" }
util-error = { path = "../util/error" }
snappy = { git = "https://github.com/paritytech/rust-snappy" }
stop-guard = { path = "../util/stop-guard" }
@@ -72,7 +74,6 @@ journaldb = { path = "../util/journaldb" }
[dev-dependencies]
tempdir = "0.3"
trie-standardmap = { path = "../util/trie-standardmap" }
kvdb-rocksdb = { path = "../util/kvdb-rocksdb" }
[features]
evm-debug = ["slow-blocks"]

View File

@@ -0,0 +1,36 @@
[package]
description = "Parity Private Transactions"
name = "ethcore-private-tx"
version = "1.0.0"
license = "GPL-3.0"
authors = ["Parity Technologies <admin@parity.io>"]
[dependencies]
error-chain = { version = "0.11", default-features = false }
ethabi = "5.1"
ethabi-contract = "5.0"
ethabi-derive = "5.0"
ethcore = { path = ".." }
ethcore-bytes = { path = "../../util/bytes" }
ethcore-io = { path = "../../util/io" }
ethcore-logger = { path = "../../logger" }
ethcore-miner = { path = "../../miner" }
ethcore-transaction = { path = "../transaction" }
ethcrypto = { path = "../../ethcrypto" }
ethereum-types = "0.3"
ethjson = { path = "../../json" }
ethkey = { path = "../../ethkey" }
fetch = { path = "../../util/fetch" }
futures = "0.1"
keccak-hash = { path = "../../util/hash" }
log = "0.3"
parking_lot = "0.5"
patricia-trie = { path = "../../util/patricia_trie" }
rand = "0.3"
rlp = { path = "../../util/rlp" }
rlp_derive = { path = "../../util/rlp_derive" }
rustc-hex = "1.0"
serde = "1.0"
serde_derive = "1.0"
serde_json = "1.0"
tiny-keccak = "1.3"

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
[{"constant": false,"inputs": [{"name": "newState","type": "bytes"},{"name": "v","type": "uint8[]"},{"name": "r","type": "bytes32[]"},{"name": "s","type": "bytes32[]"}],"name": "setState","outputs": [],"payable": false,"stateMutability": "nonpayable","type": "function"},{"constant": true,"inputs": [],"name": "code","outputs": [{"name": "","type": "bytes"}],"payable": false,"stateMutability": "view","type": "function"},{"constant": true,"inputs": [{"name": "","type": "uint256"}],"name": "validators","outputs": [{"name": "","type": "address"}],"payable": false,"stateMutability": "view","type": "function"},{"constant": true,"inputs": [],"name": "nonce","outputs": [{"name": "","type": "uint256"}],"payable": false,"stateMutability": "view","type": "function"},{"constant": true,"inputs": [],"name": "getValidators","outputs": [{"name": "","type": "address[]"}],"payable": false,"stateMutability": "view","type": "function"},{"constant": true,"inputs": [],"name": "state","outputs": [{"name": "","type": "bytes"}],"payable": false,"stateMutability": "view","type": "function"},{"inputs": [{"name": "initialValidators","type": "address[]"},{"name": "initialCode","type": "bytes"},{"name": "initialState","type": "bytes"}],"payable": false,"stateMutability": "nonpayable","type": "constructor"}]

View File

@@ -0,0 +1,272 @@
// Copyright 2015-2017 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/>.
//! Encryption providers.
use std::io::Read;
use std::iter::repeat;
use std::time::{Instant, Duration};
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use parking_lot::Mutex;
use ethcore::account_provider::AccountProvider;
use ethereum_types::{H128, H256, Address};
use ethjson;
use ethkey::{Signature, Public};
use ethcrypto;
use futures::Future;
use fetch::{Fetch, Client as FetchClient, Method, BodyReader};
use bytes::{Bytes, ToPretty};
use error::{Error, ErrorKind};
use super::find_account_password;
/// Initialization vector length.
const INIT_VEC_LEN: usize = 16;
/// Duration of storing retrieved keys (in ms)
const ENCRYPTION_SESSION_DURATION: u64 = 30 * 1000;
/// Trait for encryption/decryption operations.
pub trait Encryptor: Send + Sync + 'static {
/// Generate unique contract key && encrypt passed data. Encryption can only be performed once.
fn encrypt(
&self,
contract_address: &Address,
accounts: &AccountProvider,
initialisation_vector: &H128,
plain_data: &[u8],
) -> Result<Bytes, Error>;
/// Decrypt data using previously generated contract key.
fn decrypt(
&self,
contract_address: &Address,
accounts: &AccountProvider,
cypher: &[u8],
) -> Result<Bytes, Error>;
}
/// Configurtion for key server encryptor
#[derive(Default, PartialEq, Debug, Clone)]
pub struct EncryptorConfig {
/// URL to key server
pub base_url: Option<String>,
/// Key server's threshold
pub threshold: u32,
/// Account used for signing requests to key server
pub key_server_account: Option<Address>,
/// Passwords used to unlock accounts
pub passwords: Vec<String>,
}
struct EncryptionSession {
key: Bytes,
end_time: Instant,
}
/// SecretStore-based encryption/decryption operations.
pub struct SecretStoreEncryptor {
config: EncryptorConfig,
client: FetchClient,
sessions: Mutex<HashMap<Address, EncryptionSession>>,
}
impl SecretStoreEncryptor {
/// Create new encryptor
pub fn new(config: EncryptorConfig, client: FetchClient) -> Result<Self, Error> {
Ok(SecretStoreEncryptor {
config,
client,
sessions: Mutex::default(),
})
}
/// Ask secret store for key && decrypt the key.
fn retrieve_key(
&self,
url_suffix: &str,
use_post: bool,
contract_address: &Address,
accounts: &AccountProvider,
) -> Result<Bytes, Error> {
// check if the key was already cached
if let Some(key) = self.obtained_key(contract_address) {
return Ok(key);
}
let contract_address_signature = self.sign_contract_address(contract_address, accounts)?;
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
let contract_address_extended: H256 = contract_address.into();
let base_url = self.config.base_url.clone().ok_or_else(|| ErrorKind::KeyServerNotSet)?;
// prepare request url
let url = format!("{}/{}/{}{}",
base_url,
contract_address_extended.to_hex(),
contract_address_signature,
url_suffix,
);
// send HTTP request
let method = if use_post {
Method::Post
} else {
Method::Get
};
let response = self.client.fetch(&url, method, Default::default()).wait()
.map_err(|e| ErrorKind::Encrypt(e.to_string()))?;
if response.is_not_found() {
bail!(ErrorKind::EncryptionKeyNotFound(*contract_address));
}
if !response.is_success() {
bail!(ErrorKind::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 password = find_account_password(&self.config.passwords, &*accounts, &requester);
// decrypt Public
let decrypted_bytes = accounts.decrypt(requester, password, &ethcrypto::DEFAULT_MAC, &encrypted_bytes)?;
let decrypted_key = Public::from_slice(&decrypted_bytes);
// and now take x coordinate of Public as a key
let key: Bytes = (*decrypted_key)[..INIT_VEC_LEN].into();
// cache the key in the session and clear expired sessions
self.sessions.lock().insert(*contract_address, EncryptionSession{
key: key.clone(),
end_time: Instant::now() + Duration::from_millis(ENCRYPTION_SESSION_DURATION),
});
self.clean_expired_sessions();
Ok(key)
}
fn clean_expired_sessions(&self) {
let mut sessions = self.sessions.lock();
sessions.retain(|_, session| session.end_time < Instant::now());
}
fn obtained_key(&self, contract_address: &Address) -> Option<Bytes> {
let mut sessions = self.sessions.lock();
let stored_session = sessions.entry(*contract_address);
match stored_session {
Entry::Occupied(session) => {
if Instant::now() > session.get().end_time {
session.remove_entry();
None
} else {
Some(session.get().key.clone())
}
}
Entry::Vacant(_) => None,
}
}
fn sign_contract_address(&self, contract_address: &Address, accounts: &AccountProvider) -> Result<Signature, Error> {
// key id in SS is H256 && we have H160 here => expand with assitional zeros
let contract_address_extended: H256 = contract_address.into();
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(accounts.sign(key_server_account, password, H256::from_slice(&contract_address_extended))?)
}
}
impl Encryptor for SecretStoreEncryptor {
fn encrypt(
&self,
contract_address: &Address,
accounts: &AccountProvider,
initialisation_vector: &H128,
plain_data: &[u8],
) -> Result<Bytes, Error> {
// retrieve the key, try to generate it if it doesn't exist yet
let key = match self.retrieve_key("", false, contract_address, &*accounts) {
Ok(key) => Ok(key),
Err(Error(ErrorKind::EncryptionKeyNotFound(_), _)) => {
trace!("Key for account wasnt found in sstore. Creating. Address: {:?}", contract_address);
self.retrieve_key(&format!("/{}", self.config.threshold), true, contract_address, &*accounts)
}
Err(err) => Err(err),
}?;
// encrypt data
let mut cypher = Vec::with_capacity(plain_data.len() + initialisation_vector.len());
cypher.extend(repeat(0).take(plain_data.len()));
ethcrypto::aes::encrypt(&key, initialisation_vector, plain_data, &mut cypher);
cypher.extend_from_slice(&initialisation_vector);
Ok(cypher)
}
/// Decrypt data using previously generated contract key.
fn decrypt(
&self,
contract_address: &Address,
accounts: &AccountProvider,
cypher: &[u8],
) -> Result<Bytes, Error> {
// initialization vector takes INIT_VEC_LEN bytes
let cypher_len = cypher.len();
if cypher_len < INIT_VEC_LEN {
bail!(ErrorKind::Decrypt("Invalid cypher".into()));
}
// retrieve existing key
let key = self.retrieve_key("", false, contract_address, accounts)?;
// use symmetric decryption to decrypt document
let (cypher, iv) = cypher.split_at(cypher_len - INIT_VEC_LEN);
let mut plain_data = Vec::with_capacity(cypher_len - INIT_VEC_LEN);
plain_data.extend(repeat(0).take(cypher_len - INIT_VEC_LEN));
ethcrypto::aes::decrypt(&key, &iv, cypher, &mut plain_data);
Ok(plain_data)
}
}
/// Dummy encryptor.
#[derive(Default)]
pub struct NoopEncryptor;
impl Encryptor for NoopEncryptor {
fn encrypt(
&self,
_contract_address: &Address,
_accounts: &AccountProvider,
_initialisation_vector: &H128,
data: &[u8],
) -> Result<Bytes, Error> {
Ok(data.to_vec())
}
fn decrypt(
&self,
_contract_address: &Address,
_accounts: &AccountProvider,
data: &[u8],
) -> Result<Bytes, Error> {
Ok(data.to_vec())
}
}

View File

@@ -0,0 +1,208 @@
// Copyright 2015-2017 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 ethereum_types::Address;
use rlp::DecoderError;
use trie::TrieError;
use ethcore::account_provider::SignError;
use ethcore::error::{Error as EthcoreError, ExecutionError};
use transaction::Error as TransactionError;
use ethkey::Error as KeyError;
error_chain! {
foreign_links {
Io(::std::io::Error) #[doc = "Error concerning the Rust standard library's IO subsystem."];
Decoder(DecoderError) #[doc = "RLP decoding error."];
Trie(TrieError) #[doc = "Error concerning TrieDBs."];
}
errors {
#[doc = "Encryption error."]
Encrypt(err: String) {
description("Encryption error"),
display("Encryption error. ({})", err),
}
#[doc = "Decryption error."]
Decrypt(err: String) {
description("Decryption error"),
display("Decryption error. ({})", err),
}
#[doc = "Address not authorized."]
NotAuthorised(address: Address) {
description("Address not authorized"),
display("Private transaction execution is not authorised for {}", address),
}
#[doc = "Transaction creates more than one contract."]
TooManyContracts {
description("Transaction creates more than one contract."),
display("Private transaction created too many contracts"),
}
#[doc = "Contract call error."]
Call(err: String) {
description("Contract call error."),
display("Contract call error. ({})", err),
}
#[doc = "State is not available."]
StatePruned {
description("State is not available."),
display("State is not available"),
}
#[doc = "State is incorrect."]
StateIncorrect {
description("State is incorrect."),
display("State is incorrect"),
}
#[doc = "Wrong private transaction type."]
BadTransactonType {
description("Wrong private transaction type."),
display("Wrong private transaction type"),
}
#[doc = "Contract does not exist or was not created."]
ContractDoesNotExist {
description("Contract does not exist or was not created."),
display("Contract does not exist or was not created"),
}
#[doc = "Reference to the client is corrupted."]
ClientIsMalformed {
description("Reference to the client is corrupted."),
display("Reference to the client is corrupted"),
}
#[doc = "Queue of private transactions for verification is full."]
QueueIsFull {
description("Queue of private transactions for verification is full."),
display("Queue of private transactions for verification is full"),
}
#[doc = "The transaction already exists in queue of private transactions."]
PrivateTransactionAlreadyImported {
description("The transaction already exists in queue of private transactions."),
display("The transaction already exists in queue of private transactions."),
}
#[doc = "The information about private transaction is not found in the store."]
PrivateTransactionNotFound {
description("The information about private transaction is not found in the store."),
display("The information about private transaction is not found in the store."),
}
#[doc = "Account for signing public transactions not set."]
SignerAccountNotSet {
description("Account for signing public transactions not set."),
display("Account for signing public transactions not set."),
}
#[doc = "Account for validating private transactions not set."]
ValidatorAccountNotSet {
description("Account for validating private transactions not set."),
display("Account for validating private transactions not set."),
}
#[doc = "Account for signing requests to key server not set."]
KeyServerAccountNotSet {
description("Account for signing requests to key server not set."),
display("Account for signing requests to key server not set."),
}
#[doc = "Encryption key is not found on key server."]
EncryptionKeyNotFound(address: Address) {
description("Encryption key is not found on key server"),
display("Encryption key is not found on key server for {}", address),
}
#[doc = "Key server URL is not set."]
KeyServerNotSet {
description("Key server URL is not set."),
display("Key server URL is not set."),
}
#[doc = "VM execution error."]
Execution(err: ExecutionError) {
description("VM execution error."),
display("VM execution error {}", err),
}
#[doc = "General signing error."]
Key(err: KeyError) {
description("General signing error."),
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."]
Transaction(err: TransactionError) {
description("Error of transactions processing."),
display("Error of transactions processing {}", err),
}
#[doc = "General ethcore error."]
Ethcore(err: EthcoreError) {
description("General ethcore error."),
display("General ethcore error {}", err),
}
}
}
impl From<SignError> for Error {
fn from(err: SignError) -> Self {
ErrorKind::Sign(err).into()
}
}
impl From<KeyError> for Error {
fn from(err: KeyError) -> Self {
ErrorKind::Key(err).into()
}
}
impl From<ExecutionError> for Error {
fn from(err: ExecutionError) -> Self {
ErrorKind::Execution(err).into()
}
}
impl From<TransactionError> for Error {
fn from(err: TransactionError) -> Self {
ErrorKind::Transaction(err).into()
}
}
impl From<EthcoreError> for Error {
fn from(err: EthcoreError) -> Self {
ErrorKind::Ethcore(err).into()
}
}
impl<E> From<Box<E>> for Error where Error: From<E> {
fn from(err: Box<E>) -> Error {
Error::from(*err)
}
}

View File

@@ -0,0 +1,676 @@
// Copyright 2015-2017 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/>.
//! Private transactions module.
// Recursion limit required because of
// error_chain foreign_links.
#![recursion_limit="256"]
mod encryptor;
mod private_transactions;
mod messages;
mod error;
extern crate ethcore;
extern crate ethcore_io as io;
extern crate ethcore_bytes as bytes;
extern crate ethcore_transaction as transaction;
extern crate ethcore_miner;
extern crate ethcrypto;
extern crate ethabi;
extern crate ethereum_types;
extern crate ethkey;
extern crate ethjson;
extern crate fetch;
extern crate futures;
extern crate keccak_hash as hash;
extern crate parking_lot;
extern crate patricia_trie as trie;
extern crate rlp;
extern crate rustc_hex;
#[macro_use]
extern crate log;
#[macro_use]
extern crate ethabi_derive;
#[macro_use]
extern crate ethabi_contract;
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate rlp_derive;
#[cfg(test)]
extern crate rand;
#[cfg(test)]
extern crate ethcore_logger;
pub use encryptor::{Encryptor, SecretStoreEncryptor, EncryptorConfig, NoopEncryptor};
pub use private_transactions::{PrivateTransactionDesc, VerificationStore, PrivateTransactionSigningDesc, SigningStore};
pub use messages::{PrivateTransaction, SignedPrivateTransaction};
pub use error::{Error, ErrorKind};
use std::sync::{Arc, Weak};
use std::collections::{HashMap, HashSet};
use ethereum_types::{H128, H256, U256, Address};
use hash::keccak;
use rlp::*;
use parking_lot::{Mutex, RwLock};
use bytes::Bytes;
use ethkey::{Signature, recover, public_to_address};
use io::IoChannel;
use ethcore::executive::{Executive, TransactOptions};
use ethcore::executed::{Executed};
use transaction::{SignedTransaction, Transaction, Action, UnverifiedTransaction};
use ethcore::{contract_address as ethcore_contract_address};
use ethcore::client::{
Client, ChainNotify, ChainMessageType, ClientIoMessage, BlockId,
MiningBlockChainClient, ChainInfo, Nonce, CallContract
};
use ethcore::account_provider::AccountProvider;
use ethcore_miner::transaction_queue::{TransactionDetailsProvider as TransactionQueueDetailsProvider, AccountDetails};
use ethcore::miner::MinerService;
use ethcore::trace::{Tracer, VMTracer};
use rustc_hex::FromHex;
// Source avaiable at https://github.com/parity-contracts/private-tx/blob/master/contracts/PrivateContract.sol
const DEFAULT_STUB_CONTRACT: &'static str = include_str!("../res/private.evm");
use_contract!(private, "PrivateContract", "res/private.json");
/// Initialization vector length.
const INIT_VEC_LEN: usize = 16;
struct TransactionDetailsProvider<'a> {
client: &'a MiningBlockChainClient,
}
impl<'a> TransactionDetailsProvider<'a> {
pub fn new(client: &'a MiningBlockChainClient) -> Self {
TransactionDetailsProvider {
client: client,
}
}
}
impl<'a> TransactionQueueDetailsProvider for TransactionDetailsProvider<'a> {
fn fetch_account(&self, address: &Address) -> AccountDetails {
AccountDetails {
nonce: self.client.latest_nonce(address),
balance: self.client.latest_balance(address),
}
}
fn estimate_gas_required(&self, tx: &SignedTransaction) -> U256 {
tx.gas_required(&self.client.latest_schedule()).into()
}
fn is_service_transaction_acceptable(&self, _tx: &SignedTransaction) -> Result<bool, String> {
Ok(false)
}
}
/// Configurtion for private transaction provider
#[derive(Default, PartialEq, Debug, Clone)]
pub struct ProviderConfig {
/// Accounts that can be used for validation
pub validator_accounts: Vec<Address>,
/// Account used for signing public transactions created from private transactions
pub signer_account: Option<Address>,
/// Passwords used to unlock accounts
pub passwords: Vec<String>,
}
#[derive(Debug)]
/// Private transaction execution receipt.
pub struct Receipt {
/// Private transaction hash.
pub hash: H256,
/// Created contract address if any.
pub contract_address: Option<Address>,
/// Execution status.
pub status_code: u8,
}
/// Manager of private transactions
pub struct Provider {
encryptor: Box<Encryptor>,
validator_accounts: HashSet<Address>,
signer_account: Option<Address>,
passwords: Vec<String>,
notify: RwLock<Vec<Weak<ChainNotify>>>,
transactions_for_signing: Mutex<SigningStore>,
transactions_for_verification: Mutex<VerificationStore>,
client: Arc<Client>,
accounts: Arc<AccountProvider>,
channel: IoChannel<ClientIoMessage>,
}
#[derive(Debug)]
pub struct PrivateExecutionResult<T, V> where T: Tracer, V: VMTracer {
code: Option<Bytes>,
state: Bytes,
contract_address: Option<Address>,
result: Executed<T::Output, V::Output>,
}
impl Provider where {
/// Create a new provider.
pub fn new(
client: Arc<Client>,
accounts: Arc<AccountProvider>,
encryptor: Box<Encryptor>,
config: ProviderConfig,
channel: IoChannel<ClientIoMessage>,
) -> Result<Self, Error> {
Ok(Provider {
encryptor,
validator_accounts: config.validator_accounts.into_iter().collect(),
signer_account: config.signer_account,
passwords: config.passwords,
notify: RwLock::default(),
transactions_for_signing: Mutex::default(),
transactions_for_verification: Mutex::default(),
client,
accounts,
channel,
})
}
// TODO [ToDr] Don't use `ChainNotify` here!
// Better to create a separate notification type for this.
/// Adds an actor to be notified on certain events
pub fn add_notify(&self, target: Arc<ChainNotify>) {
self.notify.write().push(Arc::downgrade(&target));
}
fn notify<F>(&self, f: F) where F: Fn(&ChainNotify) {
for np in self.notify.read().iter() {
if let Some(n) = np.upgrade() {
f(&*n);
}
}
}
/// 1. Create private transaction from the signed transaction
/// 2. Executes private transaction
/// 3. Save it with state returned on prev step to the queue for signing
/// 4. Broadcast corresponding message to the chain
pub fn create_private_transaction(&self, signed_transaction: SignedTransaction) -> Result<Receipt, Error> {
trace!("Creating private transaction from regular transaction: {:?}", signed_transaction);
if self.signer_account.is_none() {
trace!("Signing account not set");
bail!(ErrorKind::SignerAccountNotSet);
}
let tx_hash = signed_transaction.hash();
match signed_transaction.action {
Action::Create => {
bail!(ErrorKind::BadTransactonType);
}
Action::Call(contract) => {
let data = signed_transaction.rlp_bytes();
let encrypted_transaction = self.encrypt(&contract, &Self::iv_from_transaction(&signed_transaction), &data)?;
let private = PrivateTransaction {
encrypted: encrypted_transaction,
contract,
};
// TODO [ToDr] Using BlockId::Latest is bad here,
// the block may change in the middle of execution
// causing really weird stuff to happen.
// We should retrieve hash and stick to that. IMHO
// best would be to change the API and only allow H256 instead of BlockID
// in private-tx to avoid such mistakes.
let contract_nonce = self.get_contract_nonce(&contract, BlockId::Latest)?;
let private_state = self.execute_private_transaction(BlockId::Latest, &signed_transaction)?;
trace!("Private transaction created, encrypted transaction: {:?}, private state: {:?}", private, private_state);
let contract_validators = self.get_validators(BlockId::Latest, &contract)?;
trace!("Required validators: {:?}", contract_validators);
let private_state_hash = self.calculate_state_hash(&private_state, contract_nonce);
trace!("Hashed effective private state for sender: {:?}", private_state_hash);
self.transactions_for_signing.lock().add_transaction(private.hash(), signed_transaction, contract_validators, private_state, contract_nonce)?;
self.broadcast_private_transaction(private.rlp_bytes().into_vec());
Ok(Receipt {
hash: tx_hash,
contract_address: None,
status_code: 0,
})
}
}
}
/// Calculate hash from united private state and contract nonce
pub fn calculate_state_hash(&self, state: &Bytes, nonce: U256) -> H256 {
let state_hash = keccak(state);
let mut state_buf = [0u8; 64];
state_buf[..32].clone_from_slice(&state_hash);
state_buf[32..].clone_from_slice(&H256::from(nonce));
keccak(&state_buf.as_ref())
}
/// Extract signed transaction from private transaction
fn extract_original_transaction(&self, private: PrivateTransaction, contract: &Address) -> Result<UnverifiedTransaction, Error> {
let encrypted_transaction = private.encrypted;
let transaction_bytes = self.decrypt(contract, &encrypted_transaction)?;
let original_transaction: UnverifiedTransaction = UntrustedRlp::new(&transaction_bytes).as_val()?;
Ok(original_transaction)
}
/// Process received private transaction
pub fn import_private_transaction(&self, rlp: &[u8]) -> Result<(), Error> {
trace!("Private transaction received");
let private_tx: PrivateTransaction = UntrustedRlp::new(rlp).as_val()?;
let contract = private_tx.contract;
let contract_validators = self.get_validators(BlockId::Latest, &contract)?;
let validation_account = contract_validators
.iter()
.find(|address| self.validator_accounts.contains(address));
match validation_account {
None => {
// Not for verification, broadcast further to peers
self.broadcast_private_transaction(rlp.into());
return Ok(());
},
Some(&validation_account) => {
let hash = private_tx.hash();
trace!("Private transaction taken for verification");
let original_tx = self.extract_original_transaction(private_tx, &contract)?;
trace!("Validating transaction: {:?}", original_tx);
let details_provider = TransactionDetailsProvider::new(&*self.client as &MiningBlockChainClient);
let insertion_time = self.client.chain_info().best_block_number;
// Verify with the first account available
trace!("The following account will be used for verification: {:?}", validation_account);
self.transactions_for_verification.lock()
.add_transaction(original_tx, contract, validation_account, hash, &details_provider, insertion_time)?;
self.channel.send(ClientIoMessage::NewPrivateTransaction).map_err(|_| ErrorKind::ClientIsMalformed.into())
}
}
}
/// Private transaction for validation added into queue
pub fn on_private_transaction_queued(&self) -> Result<(), Error> {
self.process_queue()
}
/// Retrieve and verify the first available private transaction for every sender
fn process_queue(&self) -> Result<(), Error> {
let mut verification_queue = self.transactions_for_verification.lock();
let ready_transactions = verification_queue.ready_transactions();
let fetch_nonce = |a: &Address| self.client.latest_nonce(a);
for transaction in ready_transactions {
let transaction_hash = transaction.hash();
match verification_queue.private_transaction_descriptor(&transaction_hash) {
Ok(desc) => {
if !self.validator_accounts.contains(&desc.validator_account) {
trace!("Cannot find validator account in config");
bail!(ErrorKind::ValidatorAccountNotSet);
}
let account = desc.validator_account;
if let Action::Call(contract) = transaction.action {
let contract_nonce = self.get_contract_nonce(&contract, BlockId::Latest)?;
let private_state = self.execute_private_transaction(BlockId::Latest, &transaction)?;
let private_state_hash = self.calculate_state_hash(&private_state, contract_nonce);
trace!("Hashed effective private state for validator: {:?}", private_state_hash);
let password = find_account_password(&self.passwords, &*self.accounts, &account);
let signed_state = self.accounts.sign(account, password, private_state_hash)?;
let signed_private_transaction = SignedPrivateTransaction::new(desc.private_hash, signed_state, None);
trace!("Sending signature for private transaction: {:?}", signed_private_transaction);
self.broadcast_signed_private_transaction(signed_private_transaction.rlp_bytes().into_vec());
} else {
trace!("Incorrect type of action for the transaction");
bail!(ErrorKind::BadTransactonType);
}
},
Err(e) => {
trace!("Cannot retrieve descriptor for transaction with error {:?}", e);
bail!(e);
}
}
verification_queue.remove_private_transaction(&transaction_hash, &fetch_nonce);
}
Ok(())
}
/// Add signed private transaction into the store
/// Creates corresponding public transaction if last required singature collected and sends it to the chain
pub fn import_signed_private_transaction(&self, rlp: &[u8]) -> Result<(), Error> {
let tx: SignedPrivateTransaction = UntrustedRlp::new(rlp).as_val()?;
trace!("Signature for private transaction received: {:?}", tx);
let private_hash = tx.private_transaction_hash();
let desc = match self.transactions_for_signing.lock().get(&private_hash) {
None => {
// Not our transaction, broadcast further to peers
self.broadcast_signed_private_transaction(rlp.into());
return Ok(());
},
Some(desc) => desc,
};
let last = self.last_required_signature(&desc, tx.signature())?;
if last {
let mut signatures = desc.received_signatures.clone();
signatures.push(tx.signature());
let rsv: Vec<Signature> = signatures.into_iter().map(|sign| sign.into_electrum().into()).collect();
//Create public transaction
let public_tx = self.public_transaction(
desc.state.clone(),
&desc.original_transaction,
&rsv,
desc.original_transaction.nonce,
desc.original_transaction.gas_price
)?;
trace!("Last required signature received, public transaction created: {:?}", public_tx);
//Sign and add it to the queue
let chain_id = desc.original_transaction.chain_id();
let hash = public_tx.hash(chain_id);
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, password, hash)?;
let signed = SignedTransaction::new(public_tx.with_signature(signature, chain_id))?;
match self.client.miner().import_own_transaction(&*self.client, signed.into()) {
Ok(_) => trace!("Public transaction added to queue"),
Err(err) => {
trace!("Failed to add transaction to queue, error: {:?}", err);
bail!(err);
}
}
//Remove from store for signing
match self.transactions_for_signing.lock().remove(&private_hash) {
Ok(_) => {}
Err(err) => {
trace!("Failed to remove transaction from signing store, error: {:?}", err);
bail!(err);
}
}
} else {
//Add signature to the store
match self.transactions_for_signing.lock().add_signature(&private_hash, tx.signature()) {
Ok(_) => trace!("Signature stored for private transaction"),
Err(err) => {
trace!("Failed to add signature to signing store, error: {:?}", err);
bail!(err);
}
}
}
Ok(())
}
fn last_required_signature(&self, desc: &PrivateTransactionSigningDesc, sign: Signature) -> Result<bool, Error> {
if desc.received_signatures.contains(&sign) {
return Ok(false);
}
let state_hash = self.calculate_state_hash(&desc.state, desc.contract_nonce);
match recover(&sign, &state_hash) {
Ok(public) => {
let sender = public_to_address(&public);
match desc.validators.contains(&sender) {
true => {
Ok(desc.received_signatures.len() + 1 == desc.validators.len())
}
false => {
trace!("Sender's state doesn't correspond to validator's");
bail!(ErrorKind::StateIncorrect);
}
}
}
Err(err) => {
trace!("Sender's state doesn't correspond to validator's, error {:?}", err);
bail!(err);
}
}
}
/// Broadcast the private transaction message to the chain
fn broadcast_private_transaction(&self, message: Bytes) {
self.notify(|notify| notify.broadcast(ChainMessageType::PrivateTransaction(message.clone())));
}
/// Broadcast signed private transaction message to the chain
fn broadcast_signed_private_transaction(&self, message: Bytes) {
self.notify(|notify| notify.broadcast(ChainMessageType::SignedPrivateTransaction(message.clone())));
}
fn iv_from_transaction(transaction: &SignedTransaction) -> H128 {
let nonce = keccak(&transaction.nonce.rlp_bytes());
let (iv, _) = nonce.split_at(INIT_VEC_LEN);
H128::from_slice(iv)
}
fn iv_from_address(contract_address: &Address) -> H128 {
let address = keccak(&contract_address.rlp_bytes());
let (iv, _) = address.split_at(INIT_VEC_LEN);
H128::from_slice(iv)
}
fn encrypt(&self, contract_address: &Address, initialisation_vector: &H128, data: &[u8]) -> Result<Bytes, Error> {
trace!("Encrypt data using key(address): {:?}", contract_address);
Ok(self.encryptor.encrypt(contract_address, &*self.accounts, initialisation_vector, data)?)
}
fn decrypt(&self, contract_address: &Address, data: &[u8]) -> Result<Bytes, Error> {
trace!("Decrypt data using key(address): {:?}", contract_address);
Ok(self.encryptor.decrypt(contract_address, &*self.accounts, data)?)
}
fn get_decrypted_state(&self, address: &Address, block: BlockId) -> Result<Bytes, Error> {
let contract = private::PrivateContract::default();
let state = contract.functions()
.state()
.call(&|data| self.client.call_contract(block, *address, data))
.map_err(|e| ErrorKind::Call(format!("Contract call failed {:?}", e)))?;
self.decrypt(address, &state)
}
fn get_decrypted_code(&self, address: &Address, block: BlockId) -> Result<Bytes, Error> {
let contract = private::PrivateContract::default();
let code = contract.functions()
.code()
.call(&|data| self.client.call_contract(block, *address, data))
.map_err(|e| ErrorKind::Call(format!("Contract call failed {:?}", e)))?;
self.decrypt(address, &code)
}
pub fn get_contract_nonce(&self, address: &Address, block: BlockId) -> Result<U256, Error> {
let contract = private::PrivateContract::default();
Ok(contract.functions()
.nonce()
.call(&|data| self.client.call_contract(block, *address, data))
.map_err(|e| ErrorKind::Call(format!("Contract call failed {:?}", e)))?)
}
fn snapshot_to_storage(raw: Bytes) -> HashMap<H256, H256> {
let items = raw.len() / 64;
(0..items).map(|i| {
let offset = i * 64;
let key = H256::from_slice(&raw[offset..(offset + 32)]);
let value = H256::from_slice(&raw[(offset + 32)..(offset + 64)]);
(key, value)
}).collect()
}
fn snapshot_from_storage(storage: &HashMap<H256, H256>) -> Bytes {
let mut raw = Vec::with_capacity(storage.len() * 64);
for (key, value) in storage {
raw.extend_from_slice(key);
raw.extend_from_slice(value);
};
raw
}
pub fn execute_private<T, V>(&self, transaction: &SignedTransaction, options: TransactOptions<T, V>, block: BlockId) -> Result<PrivateExecutionResult<T, V>, Error>
where
T: Tracer,
V: VMTracer,
{
let mut env_info = self.client.env_info(block).ok_or(ErrorKind::StatePruned)?;
env_info.gas_limit = transaction.gas;
let mut state = self.client.state_at(block).ok_or(ErrorKind::StatePruned)?;
// TODO: in case of BlockId::Latest these need to operate on the same state
let contract_address = match transaction.action {
Action::Call(ref contract_address) => {
let contract_code = Arc::new(self.get_decrypted_code(contract_address, block)?);
let contract_state = self.get_decrypted_state(contract_address, block)?;
trace!("Patching contract at {:?}, code: {:?}, state: {:?}", contract_address, contract_code, contract_state);
state.patch_account(contract_address, contract_code, Self::snapshot_to_storage(contract_state))?;
Some(*contract_address)
},
Action::Create => None,
};
let engine = self.client.engine();
let contract_address = contract_address.or({
let sender = transaction.sender();
let nonce = state.nonce(&sender)?;
let (new_address, _) = ethcore_contract_address(engine.create_address_scheme(env_info.number), &sender, &nonce, &transaction.data);
Some(new_address)
});
let result = Executive::new(&mut state, &env_info, engine.machine()).transact_virtual(transaction, options)?;
let (encrypted_code, encrypted_storage) = match contract_address {
None => bail!(ErrorKind::ContractDoesNotExist),
Some(address) => {
let (code, storage) = state.into_account(&address)?;
let enc_code = match code {
Some(c) => Some(self.encrypt(&address, &Self::iv_from_address(&address), &c)?),
None => None,
};
(enc_code, self.encrypt(&address, &Self::iv_from_transaction(transaction), &Self::snapshot_from_storage(&storage))?)
},
};
trace!("Private contract executed. code: {:?}, state: {:?}, result: {:?}", encrypted_code, encrypted_storage, result.output);
Ok(PrivateExecutionResult {
code: encrypted_code,
state: encrypted_storage,
contract_address,
result,
})
}
fn generate_constructor(validators: &[Address], code: Bytes, storage: Bytes) -> Bytes {
let constructor_code = DEFAULT_STUB_CONTRACT.from_hex().expect("Default contract code is valid");
let private = private::PrivateContract::default();
private.constructor(constructor_code, validators.iter().map(|a| *a).collect::<Vec<Address>>(), code, storage)
}
fn generate_set_state_call(signatures: &[Signature], storage: Bytes) -> Bytes {
let private = private::PrivateContract::default();
private.functions().set_state().input(
storage,
signatures.iter().map(|s| {
let mut v: [u8; 32] = [0; 32];
v[31] = s.v();
v
}).collect::<Vec<[u8; 32]>>(),
signatures.iter().map(|s| s.r()).collect::<Vec<&[u8]>>(),
signatures.iter().map(|s| s.s()).collect::<Vec<&[u8]>>()
)
}
/// Returns the key from the key server associated with the contract
pub fn contract_key_id(&self, contract_address: &Address) -> Result<H256, Error> {
//current solution uses contract address extended with 0 as id
let contract_address_extended: H256 = contract_address.into();
Ok(H256::from_slice(&contract_address_extended))
}
/// Create encrypted public contract deployment transaction.
pub fn public_creation_transaction(&self, block: BlockId, source: &SignedTransaction, validators: &[Address], gas_price: U256) -> Result<(Transaction, Option<Address>), Error> {
if let Action::Call(_) = source.action {
bail!(ErrorKind::BadTransactonType);
}
let sender = source.sender();
let state = self.client.state_at(block).ok_or(ErrorKind::StatePruned)?;
let nonce = state.nonce(&sender)?;
let executed = self.execute_private(source, TransactOptions::with_no_tracing(), block)?;
let gas: u64 = 650000 +
validators.len() as u64 * 30000 +
executed.code.as_ref().map_or(0, |c| c.len() as u64) * 8000 +
executed.state.len() as u64 * 8000;
Ok((Transaction {
nonce: nonce,
action: Action::Create,
gas: gas.into(),
gas_price: gas_price,
value: source.value,
data: Self::generate_constructor(validators, executed.code.unwrap_or_default(), executed.state)
},
executed.contract_address))
}
/// 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::BadTransactonType);
}
let result = self.execute_private(source, TransactOptions::with_no_tracing(), block)?;
Ok(result.state)
}
/// Create encrypted public transaction from private transaction.
pub fn public_transaction(&self, state: Bytes, source: &SignedTransaction, signatures: &[Signature], nonce: U256, gas_price: U256) -> Result<Transaction, Error> {
let gas: u64 = 650000 + state.len() as u64 * 8000 + signatures.len() as u64 * 50000;
Ok(Transaction {
nonce: nonce,
action: source.action.clone(),
gas: gas.into(),
gas_price: gas_price,
value: 0.into(),
data: Self::generate_set_state_call(signatures, state)
})
}
/// Call into private contract.
pub fn private_call(&self, block: BlockId, transaction: &SignedTransaction) -> Result<Executed, Error> {
let result = self.execute_private(transaction, TransactOptions::with_no_tracing(), block)?;
Ok(result.result)
}
/// Returns private validators for a contract.
pub fn get_validators(&self, block: BlockId, address: &Address) -> Result<Vec<Address>, Error> {
let contract = private::PrivateContract::default();
Ok(contract.functions()
.get_validators()
.call(&|data| self.client.call_contract(block, *address, data))
.map_err(|e| ErrorKind::Call(format!("Contract call failed {:?}", e)))?)
}
}
/// Try to unlock account using stored password, return found password if any
fn find_account_password(passwords: &Vec<String>, account_provider: &AccountProvider, account: &Address) -> Option<String> {
for password in passwords {
if let Ok(true) = account_provider.test_password(account, password) {
return Some(password.clone());
}
}
None
}
impl ChainNotify for Provider {
fn new_blocks(&self, imported: Vec<H256>, _invalid: Vec<H256>, _enacted: Vec<H256>, _retracted: Vec<H256>, _sealed: Vec<H256>, _proposed: Vec<Bytes>, _duration: u64) {
if !imported.is_empty() {
trace!("New blocks imported, try to prune the queue");
if let Err(err) = self.process_queue() {
trace!("Cannot prune private transactions queue. error: {:?}", err);
}
}
}
}

View File

@@ -0,0 +1,76 @@
// Copyright 2015-2017 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 ethereum_types::{H256, U256, Address};
use bytes::Bytes;
use hash::keccak;
use rlp::Encodable;
use ethkey::Signature;
use transaction::signature::{add_chain_replay_protection, check_replay_protection};
/// Message with private transaction encrypted
#[derive(Default, Debug, Clone, PartialEq, RlpEncodable, RlpDecodable, Eq)]
pub struct PrivateTransaction {
/// Encrypted data
pub encrypted: Bytes,
/// Address of the contract
pub contract: Address,
}
impl PrivateTransaction {
/// Compute hash on private transaction
pub fn hash(&self) -> H256 {
keccak(&*self.rlp_bytes())
}
}
/// Message about private transaction's signing
#[derive(Default, Debug, Clone, PartialEq, RlpEncodable, RlpDecodable, Eq)]
pub struct SignedPrivateTransaction {
/// Hash of the corresponding private transaction
private_transaction_hash: H256,
/// Signature of the validator
/// The V field of the signature
v: u64,
/// The R field of the signature
r: U256,
/// The S field of the signature
s: U256,
}
impl SignedPrivateTransaction {
/// Construct a signed private transaction message
pub fn new(private_transaction_hash: H256, sig: Signature, chain_id: Option<u64>) -> Self {
SignedPrivateTransaction {
private_transaction_hash: private_transaction_hash,
r: sig.r().into(),
s: sig.s().into(),
v: add_chain_replay_protection(sig.v() as u64, chain_id),
}
}
pub fn standard_v(&self) -> u8 { check_replay_protection(self.v) }
/// Construct a signature object from the sig.
pub fn signature(&self) -> Signature {
Signature::from_rsv(&self.r.into(), &self.s.into(), self.standard_v())
}
/// Get the hash of of the original transaction.
pub fn private_transaction_hash(&self) -> H256 {
self.private_transaction_hash
}
}

View File

@@ -0,0 +1,173 @@
// Copyright 2015-2017 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 ethkey::Signature;
use bytes::Bytes;
use std::collections::HashMap;
use ethereum_types::{H256, U256, Address};
use transaction::{UnverifiedTransaction, SignedTransaction};
use ethcore_miner::transaction_queue::{TransactionQueue, RemovalReason,
TransactionDetailsProvider as TransactionQueueDetailsProvider, TransactionOrigin};
use error::{Error, ErrorKind};
use ethcore::header::BlockNumber;
/// Maximum length for private transactions queues.
const MAX_QUEUE_LEN: usize = 8312;
/// Desriptor for private transaction stored in queue for verification
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct PrivateTransactionDesc {
/// Hash of the private transaction
pub private_hash: H256,
/// Contract's address used in private transaction
pub contract: Address,
/// Address that should be used for verification
pub validator_account: Address,
}
/// Storage for private transactions for verification
#[derive(Default)]
pub struct VerificationStore {
/// Descriptors for private transactions in queue for verification with key - hash of the original transaction
descriptors: HashMap<H256, PrivateTransactionDesc>,
/// Queue with transactions for verification
transactions: TransactionQueue,
}
impl VerificationStore {
/// Adds private transaction for verification into the store
pub fn add_transaction(
&mut self,
transaction: UnverifiedTransaction,
contract: Address,
validator_account: Address,
private_hash: H256,
details_provider: &TransactionQueueDetailsProvider,
insertion_time: BlockNumber,
) -> Result<(), Error> {
if self.descriptors.len() > MAX_QUEUE_LEN {
bail!(ErrorKind::QueueIsFull);
}
if self.descriptors.get(&transaction.hash()).is_some() {
bail!(ErrorKind::PrivateTransactionAlreadyImported);
}
let transaction_hash = transaction.hash();
let signed_transaction = SignedTransaction::new(transaction)?;
self.transactions
.add(signed_transaction, TransactionOrigin::External, insertion_time, None, details_provider)
.and_then(|_| {
self.descriptors.insert(transaction_hash, PrivateTransactionDesc{
private_hash,
contract,
validator_account,
});
Ok(())
})
.map_err(Into::into)
}
/// Returns transactions ready for verification
/// Returns only one transaction per sender because several cannot be verified in a row without verification from other peers
pub fn ready_transactions(&self) -> Vec<SignedTransaction> {
// TODO [ToDr] Performance killer, re-work with new transaction queue.
let mut transactions = self.transactions.top_transactions();
// TODO [ToDr] Potential issue (create low address to have your transactions processed first)
transactions.sort_by(|a, b| a.sender().cmp(&b.sender()));
transactions.dedup_by(|a, b| a.sender().eq(&b.sender()));
transactions
}
/// Returns descriptor of the corresponding private transaction
pub fn private_transaction_descriptor(&self, transaction_hash: &H256) -> Result<&PrivateTransactionDesc, Error> {
self.descriptors.get(transaction_hash).ok_or(ErrorKind::PrivateTransactionNotFound.into())
}
/// Remove transaction from the queue for verification
pub fn remove_private_transaction<F>(&mut self, transaction_hash: &H256, fetch_nonce: &F)
where F: Fn(&Address) -> U256 {
self.descriptors.remove(transaction_hash);
self.transactions.remove(transaction_hash, fetch_nonce, RemovalReason::Invalid);
}
}
/// Desriptor for private transaction stored in queue for signing
#[derive(Debug, Clone)]
pub struct PrivateTransactionSigningDesc {
/// Original unsigned transaction
pub original_transaction: SignedTransaction,
/// Supposed validators from the contract
pub validators: Vec<Address>,
/// Already obtained signatures
pub received_signatures: Vec<Signature>,
/// State after transaction execution to compare further with received from validators
pub state: Bytes,
/// Build-in nonce of the contract
pub contract_nonce: U256,
}
/// Storage for private transactions for signing
#[derive(Default)]
pub struct SigningStore {
/// Transactions and descriptors for signing
transactions: HashMap<H256, PrivateTransactionSigningDesc>,
}
impl SigningStore {
/// Adds new private transaction into the store for signing
pub fn add_transaction(
&mut self,
private_hash: H256,
transaction: SignedTransaction,
validators: Vec<Address>,
state: Bytes,
contract_nonce: U256,
) -> Result<(), Error> {
if self.transactions.len() > MAX_QUEUE_LEN {
bail!(ErrorKind::QueueIsFull);
}
self.transactions.insert(private_hash, PrivateTransactionSigningDesc {
original_transaction: transaction.clone(),
validators: validators.clone(),
received_signatures: Vec::new(),
state,
contract_nonce,
});
Ok(())
}
/// Get copy of private transaction's description from the storage
pub fn get(&self, private_hash: &H256) -> Option<PrivateTransactionSigningDesc> {
self.transactions.get(private_hash).cloned()
}
/// Removes desc from the store (after verification is completed)
pub fn remove(&mut self, private_hash: &H256) -> Result<(), Error> {
self.transactions.remove(private_hash);
Ok(())
}
/// 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)?;
if !desc.received_signatures.contains(&signature) {
desc.received_signatures.push(signature);
}
Ok(())
}
}

View File

@@ -0,0 +1,137 @@
// Copyright 2015-2017 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/>.
//! Contract for private transactions tests.
extern crate rustc_hex;
extern crate ethcore;
extern crate ethkey;
extern crate keccak_hash as hash;
extern crate ethcore_io;
extern crate ethcore_logger;
extern crate ethcore_private_tx;
extern crate ethcore_transaction;
#[macro_use]
extern crate log;
use std::sync::Arc;
use rustc_hex::FromHex;
use ethcore::CreateContractAddress;
use ethcore::account_provider::AccountProvider;
use ethcore::client::BlockChainClient;
use ethcore::client::BlockId;
use ethcore::executive::{contract_address};
use ethcore::test_helpers::{generate_dummy_client, push_block_with_transactions};
use ethcore_transaction::{Transaction, Action};
use ethkey::{Secret, KeyPair, Signature};
use hash::keccak;
use ethcore_private_tx::{NoopEncryptor, Provider, ProviderConfig};
#[test]
fn private_contract() {
// This uses a simple private contract: contract Test1 { bytes32 public x; function setX(bytes32 _x) { x = _x; } }
ethcore_logger::init_log();
let client = generate_dummy_client(0);
let chain_id = client.signing_chain_id();
let key1 = KeyPair::from_secret(Secret::from("0000000000000000000000000000000000000000000000000000000000000011")).unwrap();
let _key2 = KeyPair::from_secret(Secret::from("0000000000000000000000000000000000000000000000000000000000000012")).unwrap();
let key3 = KeyPair::from_secret(Secret::from("0000000000000000000000000000000000000000000000000000000000000013")).unwrap();
let key4 = KeyPair::from_secret(Secret::from("0000000000000000000000000000000000000000000000000000000000000014")).unwrap();
let ap = Arc::new(AccountProvider::transient_provider());
ap.insert_account(key1.secret().clone(), "").unwrap();
ap.insert_account(key3.secret().clone(), "").unwrap();
ap.insert_account(key4.secret().clone(), "").unwrap();
let config = ProviderConfig{
validator_accounts: vec![key3.address(), key4.address()],
signer_account: None,
passwords: vec!["".into()],
};
let io = ethcore_io::IoChannel::disconnected();
let pm = Arc::new(Provider::new(client.clone(), ap.clone(), Box::new(NoopEncryptor::default()), config, io).unwrap());
let (address, _) = contract_address(CreateContractAddress::FromSenderAndNonce, &key1.address(), &0.into(), &[]);
trace!("Creating private contract");
let private_contract_test = "6060604052341561000f57600080fd5b60d88061001d6000396000f30060606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630c55699c146046578063bc64b76d14607457600080fd5b3415605057600080fd5b60566098565b60405180826000191660001916815260200191505060405180910390f35b3415607e57600080fd5b6096600480803560001916906020019091905050609e565b005b60005481565b8060008160001916905550505600a165627a7a723058206acbdf4b15ca4c2d43e1b1879b830451a34f1e9d02ff1f2f394d8d857e79d2080029".from_hex().unwrap();
let mut private_create_tx = Transaction::default();
private_create_tx.action = Action::Create;
private_create_tx.data = private_contract_test;
private_create_tx.gas = 200000.into();
let private_create_tx_signed = private_create_tx.sign(&key1.secret(), None);
let validators = vec![key3.address(), key4.address()];
let (public_tx, _) = pm.public_creation_transaction(BlockId::Latest, &private_create_tx_signed, &validators, 0.into()).unwrap();
let public_tx = public_tx.sign(&key1.secret(), chain_id);
trace!("Transaction created. Pushing block");
push_block_with_transactions(&client, &[public_tx]);
trace!("Modifying private state");
let mut private_tx = Transaction::default();
private_tx.action = Action::Call(address.clone());
private_tx.data = "bc64b76d2a00000000000000000000000000000000000000000000000000000000000000".from_hex().unwrap(); //setX(42)
private_tx.gas = 120000.into();
private_tx.nonce = 1.into();
let private_tx = private_tx.sign(&key1.secret(), None);
let private_contract_nonce = pm.get_contract_nonce(&address, BlockId::Latest).unwrap();
let private_state = pm.execute_private_transaction(BlockId::Latest, &private_tx).unwrap();
let nonced_state_hash = pm.calculate_state_hash(&private_state, private_contract_nonce);
let signatures: Vec<_> = [&key3, &key4].iter().map(|k|
Signature::from(::ethkey::sign(&k.secret(), &nonced_state_hash).unwrap().into_electrum())).collect();
let public_tx = pm.public_transaction(private_state, &private_tx, &signatures, 1.into(), 0.into()).unwrap();
let public_tx = public_tx.sign(&key1.secret(), chain_id);
push_block_with_transactions(&client, &[public_tx]);
trace!("Querying private state");
let mut query_tx = Transaction::default();
query_tx.action = Action::Call(address.clone());
query_tx.data = "0c55699c".from_hex().unwrap(); // getX
query_tx.gas = 50000.into();
query_tx.nonce = 2.into();
let query_tx = query_tx.sign(&key1.secret(), chain_id);
let result = pm.private_call(BlockId::Latest, &query_tx).unwrap();
assert_eq!(&result.output[..], &("2a00000000000000000000000000000000000000000000000000000000000000".from_hex().unwrap()[..]));
assert_eq!(pm.get_validators(BlockId::Latest, &address).unwrap(), validators);
// Now try modification with just one signature
trace!("Modifying private state");
let mut private_tx = Transaction::default();
private_tx.action = Action::Call(address.clone());
private_tx.data = "bc64b76d2b00000000000000000000000000000000000000000000000000000000000000".from_hex().unwrap(); //setX(43)
private_tx.gas = 120000.into();
private_tx.nonce = 2.into();
let private_tx = private_tx.sign(&key1.secret(), None);
let private_state = pm.execute_private_transaction(BlockId::Latest, &private_tx).unwrap();
let private_state_hash = keccak(&private_state);
let signatures: Vec<_> = [&key4].iter().map(|k|
Signature::from(::ethkey::sign(&k.secret(), &private_state_hash).unwrap().into_electrum())).collect();
let public_tx = pm.public_transaction(private_state, &private_tx, &signatures, 2.into(), 0.into()).unwrap();
let public_tx = public_tx.sign(&key1.secret(), chain_id);
push_block_with_transactions(&client, &[public_tx]);
trace!("Querying private state");
let mut query_tx = Transaction::default();
query_tx.action = Action::Call(address.clone());
query_tx.data = "0c55699c".from_hex().unwrap(); // getX
query_tx.gas = 50000.into();
query_tx.nonce = 3.into();
let query_tx = query_tx.sign(&key1.secret(), chain_id);
let result = pm.private_call(BlockId::Latest, &query_tx).unwrap();
assert_eq!(result.output, "2a00000000000000000000000000000000000000000000000000000000000000".from_hex().unwrap());
}

View File

@@ -5,8 +5,11 @@ authors = ["Parity Technologies <admin@parity.io>"]
[dependencies]
ansi_term = "0.10"
error-chain = { version = "0.11", default-features = false }
ethcore = { path = ".." }
ethcore-io = { path = "../../util/io" }
ethcore-private-tx = { path = "../private-tx" }
ethsync = { path = "../../sync" }
kvdb = { path = "../../util/kvdb" }
log = "0.3"
stop-guard = { path = "../../util/stop-guard" }

View File

@@ -0,0 +1,30 @@
// 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 ethcore;
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);
}
}

View File

@@ -17,18 +17,25 @@
extern crate ansi_term;
extern crate ethcore;
extern crate ethcore_io as io;
extern crate ethsync;
extern crate kvdb;
extern crate ethcore_private_tx;
extern crate stop_guard;
#[macro_use]
extern crate error_chain;
#[macro_use]
extern crate log;
#[cfg(test)]
extern crate tempdir;
mod error;
mod service;
#[cfg(test)]
extern crate kvdb_rocksdb;
mod service;
pub use service::ClientService;
pub use error::{Error, ErrorKind};
pub use service::{ClientService, PrivateTxService};

View File

@@ -24,18 +24,50 @@ use io::{IoContext, TimerToken, IoHandler, IoService, IoError};
use kvdb::{KeyValueDB, KeyValueDBHandler};
use stop_guard::StopGuard;
use ethsync::PrivateTxHandler;
use ethcore::client::{Client, ClientConfig, ChainNotify, ClientIoMessage};
use ethcore::error::Error;
use ethcore::miner::Miner;
use ethcore::snapshot::service::{Service as SnapshotService, ServiceParams as SnapServiceParams};
use ethcore::snapshot::{RestorationStatus};
use ethcore::spec::Spec;
use ethcore::account_provider::AccountProvider;
use ethcore_private_tx;
use Error;
pub struct PrivateTxService {
provider: Arc<ethcore_private_tx::Provider>,
}
impl PrivateTxService {
fn new(provider: Arc<ethcore_private_tx::Provider>) -> Self {
PrivateTxService {
provider,
}
}
/// Returns underlying provider.
pub fn provider(&self) -> Arc<ethcore_private_tx::Provider> {
self.provider.clone()
}
}
impl PrivateTxHandler for PrivateTxService {
fn import_private_transaction(&self, rlp: &[u8]) -> Result<(), String> {
self.provider.import_private_transaction(rlp).map_err(|e| e.to_string())
}
fn import_signed_private_transaction(&self, rlp: &[u8]) -> Result<(), String> {
self.provider.import_signed_private_transaction(rlp).map_err(|e| e.to_string())
}
}
/// Client service setup. Creates and registers client and network services with the IO subsystem.
pub struct ClientService {
io_service: Arc<IoService<ClientIoMessage>>,
client: Arc<Client>,
snapshot: Arc<SnapshotService>,
private_tx: Arc<PrivateTxService>,
database: Arc<KeyValueDB>,
_stop_guard: StopGuard,
}
@@ -50,6 +82,9 @@ impl ClientService {
restoration_db_handler: Box<KeyValueDBHandler>,
_ipc_path: &Path,
miner: Arc<Miner>,
account_provider: Arc<AccountProvider>,
encryptor: Box<ethcore_private_tx::Encryptor>,
private_tx_conf: ethcore_private_tx::ProviderConfig,
) -> Result<ClientService, Error>
{
let io_service = IoService::<ClientIoMessage>::start()?;
@@ -70,9 +105,13 @@ impl ClientService {
};
let snapshot = Arc::new(SnapshotService::new(snapshot_params)?);
let provider = Arc::new(ethcore_private_tx::Provider::new(client.clone(), account_provider, encryptor, private_tx_conf, io_service.channel())?);
let private_tx = Arc::new(PrivateTxService::new(provider));
let client_io = Arc::new(ClientIoHandler {
client: client.clone(),
snapshot: snapshot.clone(),
private_tx: private_tx.clone(),
});
io_service.register_handler(client_io)?;
@@ -84,6 +123,7 @@ impl ClientService {
io_service: Arc::new(io_service),
client: client,
snapshot: snapshot,
private_tx,
database: client_db,
_stop_guard: stop_guard,
})
@@ -104,6 +144,11 @@ impl ClientService {
self.snapshot.clone()
}
/// Get private transaction service.
pub fn private_tx_service(&self) -> Arc<PrivateTxService> {
self.private_tx.clone()
}
/// Get network service component
pub fn io(&self) -> Arc<IoService<ClientIoMessage>> {
self.io_service.clone()
@@ -122,6 +167,7 @@ impl ClientService {
struct ClientIoHandler {
client: Arc<Client>,
snapshot: Arc<SnapshotService>,
private_tx: Arc<PrivateTxService>,
}
const CLIENT_TICK_TIMER: TimerToken = 0;
@@ -180,6 +226,9 @@ impl IoHandler<ClientIoMessage> for ClientIoHandler {
ClientIoMessage::NewMessage(ref message) => if let Err(e) = self.client.engine().handle_message(message) {
trace!(target: "poa", "Invalid message received: {}", e);
},
ClientIoMessage::NewPrivateTransaction => if let Err(e) = self.private_tx.provider.on_private_transaction_queued() {
warn!("Failed to handle private transaction {:?}", e);
},
_ => {} // ignore other messages
}
}
@@ -192,6 +241,7 @@ mod tests {
use tempdir::TempDir;
use ethcore::account_provider::AccountProvider;
use ethcore::client::ClientConfig;
use ethcore::miner::Miner;
use ethcore::spec::Spec;
@@ -200,6 +250,8 @@ mod tests {
use kvdb_rocksdb::{Database, DatabaseConfig, CompactionProfile};
use super::*;
use ethcore_private_tx;
#[test]
fn it_can_be_started() {
let tempdir = TempDir::new("").unwrap();
@@ -241,6 +293,9 @@ mod tests {
restoration_db_handler,
tempdir.path(),
Arc::new(Miner::with_spec(&spec)),
Arc::new(AccountProvider::transient_provider()),
Box::new(ethcore_private_tx::NoopEncryptor),
Default::default()
);
assert!(service.is_ok());
drop(service.unwrap());

View File

@@ -645,7 +645,7 @@ pub fn enact_verified(
#[cfg(test)]
mod tests {
use tests::helpers::get_temp_state_db;
use test_helpers::get_temp_state_db;
use super::*;
use engines::EthEngine;
use vm::LastHashes;

View File

@@ -1421,7 +1421,7 @@ mod tests {
use ethereum_types::*;
use receipt::{Receipt, TransactionOutcome};
use blockchain::{BlockProvider, BlockChain, Config, ImportRoute};
use tests::helpers::{
use test_helpers::{
generate_dummy_blockchain, generate_dummy_blockchain_with_extra,
generate_dummy_empty_blockchain
};

View File

@@ -17,6 +17,16 @@
use ethereum_types::H256;
use bytes::Bytes;
/// Messages to broadcast via chain
pub enum ChainMessageType {
/// Consensus message
Consensus(Vec<u8>),
/// Message with private transaction
PrivateTransaction(Vec<u8>),
/// Message with signed private transaction
SignedPrivateTransaction(Vec<u8>),
}
/// Represents what has to be handled by actor listening to chain events
pub trait ChainNotify : Send + Sync {
/// fires when chain has new blocks.
@@ -45,7 +55,7 @@ pub trait ChainNotify : Send + Sync {
}
/// fires when chain broadcasts a message
fn broadcast(&self, _data: Vec<u8>) {}
fn broadcast(&self, _message_type: ChainMessageType) {}
/// fires when new transactions are received from a peer
fn transactions_received(&self,

View File

@@ -45,7 +45,7 @@ use client::{
use client::{
BlockId, TransactionId, UncleId, TraceId, ClientConfig, BlockChainClient,
MiningBlockChainClient, TraceFilter, CallAnalytics, BlockImportError, Mode,
ChainNotify, PruningInfo, ProvingBlockChainClient, EngineInfo
ChainNotify, PruningInfo, ProvingBlockChainClient, EngineInfo, ChainMessageType
};
use encoded;
use engines::{EthEngine, EpochTransition};
@@ -2126,7 +2126,7 @@ impl super::traits::EngineClient for Client {
}
fn broadcast_consensus_message(&self, message: Bytes) {
self.notify(|notify| notify.broadcast(message.clone()));
self.notify(|notify| notify.broadcast(ChainMessageType::Consensus(message.clone())));
}
fn epoch_transition_for(&self, parent_hash: H256) -> Option<::engines::EpochTransition> {
@@ -2237,7 +2237,7 @@ mod tests {
#[test]
fn should_not_cache_details_before_commit() {
use client::{BlockChainClient, ChainInfo};
use tests::helpers::{generate_dummy_client, get_good_dummy_block_hash};
use test_helpers::{generate_dummy_client, get_good_dummy_block_hash};
use std::thread;
use std::time::Duration;

View File

@@ -36,6 +36,8 @@ pub enum ClientIoMessage {
/// Take a snapshot for the block with given number.
TakeSnapshot(u64),
/// New consensus message received.
NewMessage(Bytes)
NewMessage(Bytes),
/// New private transaction arrived
NewPrivateTransaction,
}

View File

@@ -31,11 +31,12 @@ pub use self::error::Error;
pub use self::evm_test_client::{EvmTestClient, EvmTestError, TransactResult};
pub use self::io_message::ClientIoMessage;
pub use self::test_client::{TestBlockChainClient, EachBlockWith};
pub use self::chain_notify::ChainNotify;
pub use self::chain_notify::{ChainNotify, ChainMessageType};
pub use self::traits::{
Nonce, Balance, ChainInfo, BlockInfo, ReopenBlock, PrepareOpenBlock, CallContract, TransactionInfo, RegistryInfo, ScheduleInfo, ImportSealedBlock, BroadcastProposalBlock, ImportBlock,
StateOrBlock, StateClient, Call, EngineInfo, AccountData, BlockChain, BlockProducer, SealedBlockImporter
};
//pub use self::private_notify::PrivateNotify;
pub use state::StateInfo;
pub use self::traits::{BlockChainClient, MiningBlockChainClient, EngineClient, ProvingBlockChainClient};
@@ -53,3 +54,4 @@ pub use verification::VerifierType;
mod traits;
mod chain_notify;
mod private_notify;

View File

@@ -0,0 +1,23 @@
// Copyright 2015-2017 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 error::TransactionImportError;
/// Represent private transactions handler inside the client
pub trait PrivateNotify : Send + Sync {
/// fires when private transaction message queued via client io queue
fn private_transaction_queued(&self) -> Result<(), TransactionImportError>;
}

View File

@@ -1326,7 +1326,7 @@ mod tests {
use header::Header;
use rlp::encode;
use block::*;
use tests::helpers::{
use test_helpers::{
generate_dummy_client_with_spec_and_accounts, get_temp_state_db, generate_dummy_client,
TestNotify
};

View File

@@ -199,7 +199,7 @@ mod tests {
use hash::keccak;
use ethereum_types::H520;
use block::*;
use tests::helpers::get_temp_state_db;
use test_helpers::get_temp_state_db;
use account_provider::AccountProvider;
use header::Header;
use spec::Spec;

View File

@@ -67,7 +67,7 @@ impl<M: Machine> Engine<M> for InstantSeal<M>
mod tests {
use std::sync::Arc;
use ethereum_types::{H520, Address};
use tests::helpers::{get_temp_state_db};
use test_helpers::get_temp_state_db;
use spec::Spec;
use header::Header;
use block::*;

View File

@@ -514,7 +514,6 @@ impl Engine<EthereumMachine> for Tendermint {
fn fmt_err<T: ::std::fmt::Debug>(x: T) -> EngineError {
EngineError::MalformedMessage(format!("{:?}", x))
}
let rlp = UntrustedRlp::new(rlp);
let message: ConsensusMessage = rlp.as_val().map_err(fmt_err)?;
if !self.votes.is_old_or_known(&message) {
@@ -783,7 +782,7 @@ mod tests {
use header::Header;
use client::ChainInfo;
use miner::MinerService;
use tests::helpers::{
use test_helpers::{
TestNotify, get_temp_state_db, generate_dummy_client,
generate_dummy_client_with_spec_and_accounts
};

View File

@@ -145,8 +145,8 @@ mod tests {
use account_provider::AccountProvider;
use miner::MinerService;
use types::ids::BlockId;
use test_helpers::generate_dummy_client_with_spec_and_accounts;
use client::{BlockChainClient, ChainInfo, BlockInfo, CallContract};
use tests::helpers::generate_dummy_client_with_spec_and_accounts;
use super::super::ValidatorSet;
use super::ValidatorContract;

View File

@@ -155,7 +155,7 @@ mod tests {
use header::Header;
use miner::MinerService;
use spec::Spec;
use tests::helpers::{generate_dummy_client_with_spec_and_accounts, generate_dummy_client_with_spec_and_data};
use test_helpers::{generate_dummy_client_with_spec_and_accounts, generate_dummy_client_with_spec_and_data};
use types::ids::BlockId;
use ethereum_types::Address;

View File

@@ -459,7 +459,7 @@ mod tests {
use client::{ChainInfo, BlockInfo, ImportBlock};
use ethkey::Secret;
use miner::MinerService;
use tests::helpers::{generate_dummy_client_with_spec_and_accounts, generate_dummy_client_with_spec_and_data};
use test_helpers::{generate_dummy_client_with_spec_and_accounts, generate_dummy_client_with_spec_and_data};
use super::super::ValidatorSet;
use super::{ValidatorSafeContract, EVENT_NAME_HASH};

View File

@@ -16,7 +16,7 @@
//! General error types for use in ethcore.
use std::fmt;
use std::{fmt, error};
use kvdb;
use ethereum_types::{H256, U256, Address, Bloom};
use util_error::UtilError;
@@ -268,6 +268,13 @@ impl fmt::Display for Error {
}
}
impl error::Error for Error {
fn description(&self) -> &str {
// improve description
"ethcore error"
}
}
/// Result of import block operation.
pub type ImportResult = Result<H256, Error>;

View File

@@ -487,7 +487,7 @@ mod tests {
use std::sync::Arc;
use ethereum_types::{H64, H256, U256, Address};
use block::*;
use tests::helpers::get_temp_state_db;
use test_helpers::get_temp_state_db;
use error::{BlockError, Error};
use header::Header;
use spec::Spec;

View File

@@ -145,7 +145,7 @@ mod tests {
use ethereum_types::U256;
use state::*;
use super::*;
use tests::helpers::get_temp_state_db;
use test_helpers::get_temp_state_db;
use views::BlockView;
#[test]

View File

@@ -701,7 +701,7 @@ mod tests {
use error::ExecutionError;
use machine::EthereumMachine;
use state::{Substate, CleanupMode};
use tests::helpers::{get_temp_state_with_factory, get_temp_state};
use test_helpers::{get_temp_state_with_factory, get_temp_state};
use trace::trace;
use trace::{FlatTrace, Tracer, NoopTracer, ExecutiveTracer};
use trace::{VMTrace, VMOperation, VMExecutedOperation, MemoryDiff, StorageDiff, VMTracer, NoopVMTracer, ExecutiveVMTracer};
@@ -746,7 +746,6 @@ mod tests {
assert_eq!(state.storage_at(&address, &H256::new()).unwrap(), H256::from(&U256::from(0xf9u64)));
assert_eq!(state.balance(&sender).unwrap(), U256::from(0xf9));
assert_eq!(state.balance(&address).unwrap(), U256::from(0x7));
// 0 cause contract hasn't returned
assert_eq!(substate.contracts_created.len(), 0);
// TODO: just test state root.

View File

@@ -414,7 +414,7 @@ mod tests {
use ethereum_types::{U256, Address};
use evm::{EnvInfo, Ext, CallType};
use state::{State, Substate};
use tests::helpers::get_temp_state;
use test_helpers::get_temp_state;
use super::*;
use trace::{NoopTracer, NoopVMTracer};

View File

@@ -25,7 +25,7 @@ use vm::{
CreateContractAddress, ReturnData,
};
use externalities::*;
use tests::helpers::get_temp_state;
use test_helpers::get_temp_state;
use ethjson;
use trace::{Tracer, NoopTracer};
use trace::{VMTracer, NoopVMTracer};

View File

@@ -94,6 +94,7 @@ extern crate ansi_term;
extern crate unexpected;
extern crate kvdb;
extern crate kvdb_memorydb;
extern crate kvdb_rocksdb;
extern crate util_error;
extern crate snappy;
@@ -128,9 +129,6 @@ extern crate trace_time;
#[cfg_attr(test, macro_use)]
extern crate evm;
#[cfg(test)]
extern crate kvdb_rocksdb;
pub extern crate ethstore;
pub mod account_provider;
@@ -142,6 +140,7 @@ pub mod engines;
pub mod error;
pub mod ethereum;
pub mod executed;
pub mod executive;
pub mod header;
pub mod machine;
pub mod miner;
@@ -150,6 +149,8 @@ pub mod snapshot;
pub mod spec;
pub mod state;
pub mod state_db;
// Test helpers made public for usage outside ethcore
pub mod test_helpers;
pub mod trace;
pub mod verification;
pub mod views;
@@ -159,7 +160,6 @@ mod blooms;
mod pod_account;
mod account_db;
mod builtin;
mod executive;
mod externalities;
mod blockchain;
mod factory;

View File

@@ -24,7 +24,7 @@ use ethereum_types::{H256, U256, Address};
use parking_lot::{Mutex, RwLock};
use bytes::Bytes;
use engines::{EthEngine, Seal};
use error::*;
use error::{ExecutionError, Error};
use ethcore_miner::banning_queue::{BanningTransactionQueue, Threshold};
use ethcore_miner::local_transactions::{Status as LocalTransactionStatus};
use ethcore_miner::transaction_queue::{
@@ -1327,8 +1327,7 @@ mod tests {
use spec::Spec;
use transaction::{SignedTransaction, Transaction, PendingTransaction, Action};
use miner::MinerService;
use tests::helpers::{generate_dummy_client, generate_dummy_client_with_spec_and_accounts};
use test_helpers::{generate_dummy_client, generate_dummy_client_with_spec_and_accounts};
#[test]
fn should_prepare_block_to_seal() {

View File

@@ -210,7 +210,7 @@ pub fn from_fat_rlp(
mod tests {
use account_db::{AccountDB, AccountDBMut};
use basic_account::BasicAccount;
use tests::helpers::get_temp_state_db;
use test_helpers::get_temp_state_db;
use snapshot::tests::helpers::fill_storage;
use hash::{KECCAK_EMPTY, KECCAK_NULL_RLP, keccak};

View File

@@ -635,7 +635,7 @@ mod tests {
use snapshot::{ManifestData, RestorationStatus, SnapshotService};
use super::*;
use tempdir::TempDir;
use tests::helpers::restoration_db_handler;
use test_helpers::restoration_db_handler;
struct NoopDBRestore;
impl DatabaseRestore for NoopDBRestore {

View File

@@ -25,7 +25,7 @@ use client::{Client, BlockChainClient, ChainInfo};
use ethkey::Secret;
use snapshot::tests::helpers as snapshot_helpers;
use spec::Spec;
use tests::helpers;
use test_helpers::generate_dummy_client_with_spec_and_accounts;
use transaction::{Transaction, Action, SignedTransaction};
use tempdir::TempDir;
@@ -89,7 +89,7 @@ enum 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> {
let client = helpers::generate_dummy_client_with_spec_and_accounts(
let client = generate_dummy_client_with_spec_and_accounts(
spec_fixed_to_contract, Some(accounts.clone()));
let mut cur_signers = vec![*RICH_ADDR];

View File

@@ -24,7 +24,7 @@ use ids::BlockId;
use snapshot::service::{Service, ServiceParams};
use snapshot::{self, ManifestData, SnapshotService};
use spec::Spec;
use tests::helpers::{generate_dummy_client_with_spec_and_data, restoration_db_handler};
use test_helpers::{generate_dummy_client_with_spec_and_data, restoration_db_handler};
use io::IoChannel;
use kvdb_rocksdb::{Database, DatabaseConfig};

View File

@@ -892,7 +892,7 @@ impl Spec {
mod tests {
use super::*;
use state::State;
use tests::helpers::get_temp_state_db;
use test_helpers::get_temp_state_db;
use views::BlockView;
use tempdir::TempDir;

View File

@@ -180,6 +180,16 @@ impl Account {
self.init_code(code);
}
/// Reset this account's code and storage to given values.
pub fn reset_code_and_storage(&mut self, code: Arc<Bytes>, storage: HashMap<H256, H256>) {
self.code_hash = keccak(&*code);
self.code_cache = code;
self.code_size = Some(self.code_cache.len());
self.code_filth = Filth::Dirty;
self.storage_cache = Self::empty_storage_cache();
self.storage_changes = storage;
}
/// Set (and cache) the contents of the trie's storage at `key` to `value`.
pub fn set_storage(&mut self, key: H256, value: H256) {
self.storage_changes.insert(key, value);

View File

@@ -494,6 +494,13 @@ impl<B: Backend> State<B> {
(self.root, self.db)
}
/// Destroy the current object and return single account data.
pub fn into_account(self, account: &Address) -> trie::Result<(Option<Arc<Bytes>>, HashMap<H256, H256>)> {
// TODO: deconstruct without cloning.
let account = self.require(account, true)?;
Ok((account.code().clone(), account.storage_changes().clone()))
}
/// Return reference to root
pub fn root(&self) -> &H256 {
&self.root
@@ -1014,6 +1021,11 @@ impl<B: Backend> State<B> {
}
}))
}
/// Replace account code and storage. Creates account if it does not exist.
pub fn patch_account(&self, a: &Address, code: Arc<Bytes>, storage: HashMap<H256, H256>) -> trie::Result<()> {
Ok(self.require(a, false)?.reset_code_and_storage(code, storage))
}
}
// State proof implementations; useful for light client protocols.
@@ -1099,7 +1111,7 @@ mod tests {
use super::*;
use ethkey::Secret;
use ethereum_types::{H256, U256, Address};
use tests::helpers::{get_temp_state, get_temp_state_db};
use test_helpers::{get_temp_state, get_temp_state_db};
use machine::EthereumMachine;
use vm::EnvInfo;
use spec::*;

View File

@@ -480,7 +480,7 @@ unsafe impl Sync for SyncAccount {}
mod tests {
use ethereum_types::{H256, U256, Address};
use kvdb::DBTransaction;
use tests::helpers::{get_temp_state_db};
use test_helpers::get_temp_state_db;
use state::{Account, Backend};
use ethcore_logger::init_log;

View File

@@ -14,12 +14,14 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Set of different helpers for client tests
use account_provider::AccountProvider;
use ethereum_types::{H256, U256};
use ethereum_types::{H256, U256, Address};
use block::{OpenBlock, Drain};
use blockchain::{BlockChain, Config as BlockChainConfig};
use bytes::Bytes;
use client::{Client, ClientConfig, ChainInfo, ImportBlock, ChainNotify};
use client::{Client, ClientConfig, ChainInfo, ImportBlock, ChainNotify, ChainMessageType, PrepareOpenBlock};
use ethkey::KeyPair;
use evm::Factory as EvmFactory;
use factory::Factories;
@@ -39,6 +41,7 @@ use views::BlockView;
use kvdb::{KeyValueDB, KeyValueDBHandler};
use kvdb_rocksdb::{Database, DatabaseConfig};
/// Creates test block with corresponding header
pub fn create_test_block(header: &Header) -> Bytes {
let mut rlp = RlpStream::new_list(3);
rlp.append(header);
@@ -76,6 +79,7 @@ fn create_unverifiable_block(order: u32, parent_hash: H256) -> Bytes {
create_test_block(&create_unverifiable_block_header(order, parent_hash))
}
/// Creates test block with corresponding header and data
pub fn create_test_block_with_data(header: &Header, transactions: &[SignedTransaction], uncles: &[Header]) -> Bytes {
let mut rlp = RlpStream::new_list(3);
rlp.append(header);
@@ -87,23 +91,27 @@ pub fn create_test_block_with_data(header: &Header, transactions: &[SignedTransa
rlp.out()
}
/// Generates dummy client (not test client) with corresponding amount of blocks
pub fn generate_dummy_client(block_number: u32) -> Arc<Client> {
generate_dummy_client_with_spec_and_data(Spec::new_test, block_number, 0, &[])
}
/// Generates dummy client (not test client) with corresponding amount of blocks and txs per every block
pub fn generate_dummy_client_with_data(block_number: u32, txs_per_block: usize, tx_gas_prices: &[U256]) -> Arc<Client> {
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
pub fn generate_dummy_client_with_spec_and_accounts<F>(test_spec: F, accounts: Option<Arc<AccountProvider>>) -> Arc<Client> where F: Fn()->Spec {
generate_dummy_client_with_spec_accounts_and_data(test_spec, accounts, 0, 0, &[])
}
/// Generates dummy client (not test client) with corresponding blocks, accounts 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 {
let test_spec = test_spec();
let client_db = new_db();
@@ -174,6 +182,7 @@ pub fn generate_dummy_client_with_spec_accounts_and_data<F>(test_spec: F, accoun
client
}
/// Adds blocks to the client
pub fn push_blocks_to_client(client: &Arc<Client>, timestamp_salt: u64, starting_number: usize, block_number: usize) {
let test_spec = Spec::new_test();
let state_root = test_spec.genesis_header().state_root().clone();
@@ -203,6 +212,29 @@ pub fn push_blocks_to_client(client: &Arc<Client>, timestamp_salt: u64, starting
}
}
/// Adds one block with transactions
pub fn push_block_with_transactions(client: &Arc<Client>, transactions: &[SignedTransaction]) {
let test_spec = Spec::new_test();
let test_engine = &*test_spec.engine;
let block_number = client.chain_info().best_block_number as u64 + 1;
let mut b = client.prepare_open_block(Address::default(), (0.into(), 5000000.into()), Bytes::new());
b.set_timestamp(block_number * 10);
for t in transactions {
b.push_transaction(t.clone(), None).unwrap();
}
let b = b.close_and_lock().seal(test_engine, vec![]).unwrap();
if let Err(e) = client.import_block(b.rlp_bytes()) {
panic!("error importing block which is valid by definition: {:?}", e);
}
client.flush_queue();
client.import_verified_blocks();
}
/// Creates dummy client (not test client) with corresponding blocks
pub fn get_test_client_with_blocks(blocks: Vec<Bytes>) -> Arc<Client> {
let test_spec = Spec::new_test();
let client_db = new_db();
@@ -229,6 +261,7 @@ fn new_db() -> Arc<::kvdb::KeyValueDB> {
Arc::new(::kvdb_memorydb::create(::db::NUM_COLUMNS.unwrap_or(0)))
}
/// Generates dummy blockchain with corresponding amount of blocks
pub fn generate_dummy_blockchain(block_number: u32) -> BlockChain {
let db = new_db();
let bc = BlockChain::new(BlockChainConfig::default(), &create_unverifiable_block(0, H256::zero()), db.clone());
@@ -242,6 +275,7 @@ pub fn generate_dummy_blockchain(block_number: u32) -> BlockChain {
bc
}
/// Generates dummy blockchain with corresponding amount of blocks (using creation with extra method for blocks creation)
pub fn generate_dummy_blockchain_with_extra(block_number: u32) -> BlockChain {
let db = new_db();
let bc = BlockChain::new(BlockChainConfig::default(), &create_unverifiable_block(0, H256::zero()), db.clone());
@@ -256,17 +290,20 @@ pub fn generate_dummy_blockchain_with_extra(block_number: u32) -> BlockChain {
bc
}
/// Returns empty dummy blockchain
pub fn generate_dummy_empty_blockchain() -> BlockChain {
let db = new_db();
let bc = BlockChain::new(BlockChainConfig::default(), &create_unverifiable_block(0, H256::zero()), db.clone());
bc
}
/// Returns temp state
pub fn get_temp_state() -> State<::state_db::StateDB> {
let journal_db = get_temp_state_db();
State::new(journal_db, U256::from(0), Default::default())
}
/// Returns temp state using coresponding factory
pub fn get_temp_state_with_factory(factory: EvmFactory) -> State<::state_db::StateDB> {
let journal_db = get_temp_state_db();
let mut factories = Factories::default();
@@ -274,17 +311,20 @@ pub fn get_temp_state_with_factory(factory: EvmFactory) -> State<::state_db::Sta
State::new(journal_db, U256::from(0), factories)
}
/// Returns temp state db
pub fn get_temp_state_db() -> StateDB {
let db = new_db();
let journal_db = ::journaldb::new(db, ::journaldb::Algorithm::EarlyMerge, ::db::COL_STATE);
StateDB::new(journal_db, 5 * 1024 * 1024)
}
/// Returns sequence of hashes of the dummy blocks
pub fn get_good_dummy_block_seq(count: usize) -> Vec<Bytes> {
let test_spec = Spec::new_test();
get_good_dummy_block_fork_seq(1, count, &test_spec.genesis_header().hash())
}
/// Returns sequence of hashes of the dummy blocks beginning from corresponding parent
pub fn get_good_dummy_block_fork_seq(start_number: usize, count: usize, parent_hash: &H256) -> Vec<Bytes> {
let test_spec = Spec::new_test();
let genesis_gas = test_spec.genesis_header().gas_limit().clone();
@@ -308,6 +348,7 @@ pub fn get_good_dummy_block_fork_seq(start_number: usize, count: usize, parent_h
r
}
/// Returns hash and header of the correct dummy block
pub fn get_good_dummy_block_hash() -> (H256, Bytes) {
let mut block_header = Header::new();
let test_spec = Spec::new_test();
@@ -322,11 +363,13 @@ pub fn get_good_dummy_block_hash() -> (H256, Bytes) {
(block_header.hash(), create_test_block(&block_header))
}
/// Returns hash of the correct dummy block
pub fn get_good_dummy_block() -> Bytes {
let (_, bytes) = get_good_dummy_block_hash();
bytes
}
/// Returns hash of the dummy block with incorrect state root
pub fn get_bad_state_dummy_block() -> Bytes {
let mut block_header = Header::new();
let test_spec = Spec::new_test();
@@ -342,17 +385,25 @@ pub fn get_bad_state_dummy_block() -> Bytes {
create_test_block(&block_header)
}
/// Test actor for chain events
#[derive(Default)]
pub struct TestNotify {
/// Messages store
pub messages: RwLock<Vec<Bytes>>,
}
impl ChainNotify for TestNotify {
fn broadcast(&self, data: Vec<u8>) {
fn broadcast(&self, message: ChainMessageType) {
let data = match message {
ChainMessageType::Consensus(data) => data,
ChainMessageType::SignedPrivateTransaction(data) => data,
ChainMessageType::PrivateTransaction(data) => data,
};
self.messages.write().push(data);
}
}
/// Creates new instance of KeyValueDBHandler
pub fn restoration_db_handler(config: DatabaseConfig) -> Box<KeyValueDBHandler> {
use kvdb::Error;

View File

@@ -23,7 +23,7 @@ use state::{self, State, CleanupMode};
use executive::{Executive, TransactOptions};
use ethereum;
use block::IsBlock;
use tests::helpers::{
use test_helpers::{
generate_dummy_client, push_blocks_to_client, get_test_client_with_blocks, get_good_dummy_block_seq,
generate_dummy_client_with_data, get_good_dummy_block, get_bad_state_dummy_block
};

View File

@@ -22,7 +22,7 @@ use vm::{EnvInfo, ActionParams, ActionValue, CallType, ParamsType};
use evm::{Factory, VMType};
use executive::Executive;
use state::Substate;
use tests::helpers::get_temp_state_with_factory;
use test_helpers::get_temp_state_with_factory;
use trace::{NoopVMTracer, NoopTracer};
use transaction::SYSTEM_ADDRESS;

View File

@@ -14,7 +14,6 @@
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
pub mod helpers;
mod client;
mod evm;
mod trace;

View File

@@ -24,7 +24,7 @@ use ethereum_types::{U256, Address};
use io::*;
use spec::*;
use client::*;
use tests::helpers::get_temp_state_db;
use test_helpers::get_temp_state_db;
use client::{BlockChainClient, Client, ClientConfig};
use kvdb_rocksdb::{Database, DatabaseConfig};
use std::sync::Arc;

View File

@@ -731,7 +731,7 @@ mod tests {
use spec::Spec;
use super::{BlockQueue, Config, State};
use super::kind::blocks::Unverified;
use tests::helpers::{get_good_dummy_block_seq, get_good_dummy_block};
use test_helpers::{get_good_dummy_block_seq, get_good_dummy_block};
use error::*;
use views::*;

View File

@@ -359,7 +359,7 @@ mod tests {
use error::BlockError::*;
use ethkey::{Random, Generator};
use spec::{CommonParams, Spec};
use tests::helpers::{create_test_block_with_data, create_test_block};
use test_helpers::{create_test_block_with_data, create_test_block};
use transaction::{SignedTransaction, Transaction, UnverifiedTransaction, Action};
use types::log_entry::{LogEntry, LocalizedLogEntry};
use rlp;

View File

@@ -77,6 +77,25 @@ pub enum Condition {
Timestamp(u64),
}
/// Replay protection logic for v part of transaction's signature
pub mod signature {
/// Adds chain id into v
pub fn add_chain_replay_protection(v: u64, chain_id: Option<u64>) -> u64 {
v + if let Some(n) = chain_id { 35 + n * 2 } else { 27 }
}
/// Returns refined v
/// 0 if `v` would have been 27 under "Electrum" notation, 1 if 28 or 4 if invalid.
pub fn check_replay_protection(v: u64) -> u8 {
match v {
v if v == 27 => 0,
v if v == 28 => 1,
v if v > 36 => ((v - 1) % 2) as u8,
_ => 4
}
}
}
/// A set of information describing an externally-originating message call
/// or contract creation operation.
#[derive(Default, Debug, Clone, PartialEq, Eq)]
@@ -186,7 +205,7 @@ impl Transaction {
unsigned: self,
r: sig.r().into(),
s: sig.s().into(),
v: sig.v() as u64 + if let Some(n) = chain_id { 35 + n * 2 } else { 27 },
v: signature::add_chain_replay_protection(sig.v() as u64, chain_id),
hash: 0.into(),
}.compute_hash()
}
@@ -330,8 +349,7 @@ impl UnverifiedTransaction {
&self.unsigned
}
/// 0 if `v` would have been 27 under "Electrum" notation, 1 if 28 or 4 if invalid.
pub fn standard_v(&self) -> u8 { match self.v { v if v == 27 || v == 28 || v > 36 => ((v - 1) % 2) as u8, _ => 4 } }
pub fn standard_v(&self) -> u8 { signature::check_replay_protection(self.v) }
/// The `v` value that appears in the RLP.
pub fn original_v(&self) -> u64 { self.v }