openethereum/ethcore/src/tests/client.rs

374 lines
12 KiB
Rust
Raw Normal View History

// Copyright 2015-2017 Parity Technologies (UK) Ltd.
2016-02-05 13:40:41 +01:00
// 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/>.
2017-07-29 17:12:07 +02:00
use std::str::FromStr;
2017-07-29 21:56:42 +02:00
use std::sync::Arc;
use hash::keccak;
use io::IoChannel;
`Client` refactoring (#7038) * Improves `BestBlock` comment * Improves `TraceDB` comment * Improves `journaldb::Algorithm` comment. Probably the whole enum should be renamed to `Strategy` or something alike. * Comments some of the `Client`'s fields * Deglobs client imports * Fixes comments * Extracts `import_lock` to `Importer` struct * Extracts `verifier` to `Importer` struct * Extracts `block_queue` to `Importer` struct * Extracts `miner` to `Importer` struct * Extracts `ancient_verifier` to `Importer` struct * Extracts `rng` to `Importer` struct * Extracts `import_old_block` to `Importer` struct * Adds `Nonce` trait * Adds `Balance` trait * Adds `ChainInfo` trait * Fixes imports for tests using `chain_info` method * Adds `BlockInfo` trait * Adds more `ChainInfo` imports * Adds `BlockInfo` imports * Adds `ReopenBlock` trait * Adds `PrepareOpenBlock` trait * Fixes import in tests * Adds `CallContract` trait * Fixes imports in tests using `call_contract` method * Adds `TransactionInfo` trait * Adds `RegistryInfo` trait * Fixes imports in tests using `registry_address` method * Adds `ScheduleInfo` trait * Adds `ImportSealedBlock` trait * Fixes imports in test using `import_sealed_block` method * Adds `BroadcastProposalBlock` trait * Migrates `Miner` to static dispatch * Fixes tests * Moves `calculate_enacted_retracted` to `Importer` * Moves import-related methods to `Importer` * Removes redundant `import_old_block` wrapper * Extracts `import_block*` into separate trait * Fixes tests * Handles `Pending` in `LightFetch` * Handles `Pending` in filters * Handles `Pending` in `ParityClient` * Handles `Pending` in `EthClient` * Removes `BlockId::Pending`, partly refactors dependent code * Adds `StateInfo` trait * Exports `StateOrBlock` and `BlockChain` types from `client` module * Refactors `balance` RPC using generic API * Refactors `storage_at` RPC using generic API * Makes `MinerService::pending_state`'s return type dynamic * Adds `StateOrBlock` and `BlockChain` types * Adds impl of `client::BlockChain` for `Client` * Exports `StateInfo` trait from `client` module * Missing `self` use To be fixed up to "Adds impl of `client::BlockChain` for `Client`" * Adds `number_to_id` and refactors dependent RPC methods * Refactors `code_at` using generic API * Adds `StateClient` trait * Refactors RPC to use `StateClient` trait * Reverts `client::BlockChain` trait stuff, refactors methods to accept `StateOrBlock` * Refactors TestClient * Adds helper function `block_number_to_id` * Uses `block_number_to_id` instead of local function * Handles `Pending` in `list_accounts` and `list_storage_keys` * Attempt to use associated types for state instead of trait objects * Simplifies `state_at_beginning` * Extracts `call` and `call_many` into separate trait * Refactors `build_last_hashes` to accept reference * Exports `Call` type from the module * Refactors `call` and `call_many` to accept state and header * Exports `state_at` in `StateClient` * Exports `pending_block_header` from `MinerService` * Refactors RPC `call` method using new API * Adds missing parentheses * Refactors `parity::call` to use new call API * Update .gitlab-ci.yml fix gitlab lint * Fixes error handling * Refactors `traces::call` and `call_many` to use new call API * Refactors `call_contract` * Refactors `block_header` * Refactors internal RPC method `block` * Moves `estimate_gas` to `Call` trait, refactors parameters * Refactors `estimate_gas` in RPC * Refactors `uncle` * Refactors RPC `transaction` * Covers missing branches * Makes it all compile, fixes compiler grumbles * Adds casts in `blockchain` module * Fixes `PendingBlock` tests, work on `MinerService` * Adds test stubs for StateClient and EngineInfo * Makes `state_db` public * Adds missing impls for `TestBlockChainClient` * Adds trait documentation * Adds missing docs to the `state_db` module * Fixes trivial compilation errors * Moves `code_hash` method to a `BlockInfo` trait * Refactors `Verifier` to be generic over client * Refactors `TransactionFilter` to be generic over client * Refactors `Miner` and `Client` to reflect changes in verifier and txfilter API * Moves `ServiceTransactionChecker` back to `ethcore` * Fixes trait bounds in `Miner` API * Fixes `Client` * Fixes lifetime bound in `FullFamilyParams` * Adds comments to `FullFamilyParams` * Fixes imports in `ethcore` * Fixes BlockNumber handling in `code_at` and `replay_block_transactions` * fix compile issues * First step to redundant trait merge * Fixes compilation error in RPC tests * Adds mock `State` as a stub for `TestClient` * Handles `StateOrBlock::State` in `TestBlockChainClient::balance` * Fixes `transaction_count` RPC * Fixes `transaction_count` * Moves `service_transaction.json` to the `contracts` subfolder * Fixes compilation errors in tests * Refactors client to use `AccountData` * Refactors client to use `BlockChain` * Refactors miner to use aggregate traits * Adds `SealedBlockImporter` trait * Refactors miner to use `SealedBlockImporter` trait * Removes unused imports * Simplifies `RegistryInfo::registry_address` * Fixes indentation * Removes commented out trait bound
2018-03-03 18:42:13 +01:00
use client::{BlockChainClient, Client, ClientConfig, BlockId, ChainInfo, BlockInfo, PrepareOpenBlock, ImportSealedBlock, ImportBlock};
use state::{self, State, CleanupMode};
use executive::{Executive, TransactOptions};
use ethereum;
2016-03-02 00:34:38 +01:00
use block::IsBlock;
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
2018-04-09 16:14:33 +02:00
use test_helpers::{
2018-03-12 18:05:52 +01:00
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
};
use types::filter::Filter;
use ethereum_types::{U256, Address};
use kvdb_rocksdb::{Database, DatabaseConfig};
2016-05-31 22:24:32 +02:00
use miner::Miner;
use spec::Spec;
use views::BlockView;
use ethkey::KeyPair;
use transaction::{PendingTransaction, Transaction, Action, Condition};
2016-12-16 13:27:14 +01:00
use miner::MinerService;
use tempdir::TempDir;
2016-01-26 11:39:49 +01:00
2016-01-26 14:33:22 +01:00
#[test]
fn imports_from_empty() {
let tempdir = TempDir::new("").unwrap();
2018-03-12 18:05:52 +01:00
let spec = Spec::new_test();
let db_config = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
let client_db = Arc::new(Database::open(&db_config, tempdir.path().to_str().unwrap()).unwrap());
let client = Client::new(
ClientConfig::default(),
&spec,
client_db,
Arc::new(Miner::with_spec(&spec)),
IoChannel::disconnected(),
).unwrap();
client.import_verified_blocks();
2016-01-26 14:33:22 +01:00
client.flush_queue();
}
#[test]
fn should_return_registrar() {
let tempdir = TempDir::new("").unwrap();
let spec = ethereum::new_morden(&tempdir.path().to_owned());
let db_config = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
let client_db = Arc::new(Database::open(&db_config, tempdir.path().to_str().unwrap()).unwrap());
let client = Client::new(
ClientConfig::default(),
&spec,
client_db,
Arc::new(Miner::with_spec(&spec)),
IoChannel::disconnected(),
).unwrap();
let params = client.additional_params();
2016-11-28 13:20:49 +01:00
let address = &params["registrar"];
assert_eq!(address.len(), 40);
assert!(U256::from_str(address).is_ok());
}
2016-03-11 20:24:44 +01:00
#[test]
fn returns_state_root_basic() {
2017-04-06 19:26:17 +02:00
let client = generate_dummy_client(6);
2018-03-12 18:05:52 +01:00
let test_spec = Spec::new_test();
let genesis_header = test_spec.genesis_header();
2016-03-11 20:24:44 +01:00
assert!(client.state_data(genesis_header.state_root()).is_some());
2016-03-11 20:24:44 +01:00
}
2016-01-26 14:33:22 +01:00
#[test]
fn imports_good_block() {
let tempdir = TempDir::new("").unwrap();
2018-03-12 18:05:52 +01:00
let spec = Spec::new_test();
let db_config = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
let client_db = Arc::new(Database::open(&db_config, tempdir.path().to_str().unwrap()).unwrap());
let client = Client::new(
ClientConfig::default(),
&spec,
client_db,
Arc::new(Miner::with_spec(&spec)),
IoChannel::disconnected(),
).unwrap();
2016-01-26 14:33:22 +01:00
let good_block = get_good_dummy_block();
2016-11-28 13:20:49 +01:00
if client.import_block(good_block).is_err() {
2016-01-26 14:33:22 +01:00
panic!("error importing block being good by definition");
}
client.flush_queue();
client.import_verified_blocks();
2016-01-26 14:33:22 +01:00
let block = client.block_header(BlockId::Number(1)).unwrap();
assert!(!block.into_inner().is_empty());
2016-01-26 14:33:22 +01:00
}
#[test]
fn query_none_block() {
let tempdir = TempDir::new("").unwrap();
2018-03-12 18:05:52 +01:00
let spec = Spec::new_test();
let db_config = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
let client_db = Arc::new(Database::open(&db_config, tempdir.path().to_str().unwrap()).unwrap());
2016-01-26 14:33:22 +01:00
let client = Client::new(
ClientConfig::default(),
&spec,
client_db,
Arc::new(Miner::with_spec(&spec)),
IoChannel::disconnected(),
).unwrap();
let non_existant = client.block_header(BlockId::Number(188));
2016-01-26 14:55:08 +01:00
assert!(non_existant.is_none());
}
#[test]
fn query_bad_block() {
2017-04-06 19:26:17 +02:00
let client = get_test_client_with_blocks(vec![get_bad_state_dummy_block()]);
let bad_block: Option<_> = client.block_header(BlockId::Number(1));
2016-01-26 14:55:08 +01:00
assert!(bad_block.is_none());
2016-01-26 18:05:25 +01:00
}
#[test]
fn returns_chain_info() {
let dummy_block = get_good_dummy_block();
2017-04-06 19:26:17 +02:00
let client = get_test_client_with_blocks(vec![dummy_block.clone()]);
2016-01-26 18:05:25 +01:00
let block = BlockView::new(&dummy_block);
let info = client.chain_info();
assert_eq!(info.best_block_hash, block.header().hash());
2016-01-27 13:23:24 +01:00
}
#[test]
fn returns_logs() {
let dummy_block = get_good_dummy_block();
2017-04-06 19:26:17 +02:00
let client = get_test_client_with_blocks(vec![dummy_block.clone()]);
let logs = client.logs(Filter {
from_block: BlockId::Earliest,
to_block: BlockId::Latest,
address: None,
topics: vec![],
limit: None,
});
assert_eq!(logs.len(), 0);
}
#[test]
fn returns_logs_with_limit() {
let dummy_block = get_good_dummy_block();
2017-04-06 19:26:17 +02:00
let client = get_test_client_with_blocks(vec![dummy_block.clone()]);
let logs = client.logs(Filter {
from_block: BlockId::Earliest,
to_block: BlockId::Latest,
address: None,
topics: vec![],
limit: None,
});
assert_eq!(logs.len(), 0);
}
#[test]
fn returns_block_body() {
let dummy_block = get_good_dummy_block();
2017-04-06 19:26:17 +02:00
let client = get_test_client_with_blocks(vec![dummy_block.clone()]);
let block = BlockView::new(&dummy_block);
let body = client.block_body(BlockId::Hash(block.header().hash())).unwrap();
let body = body.rlp();
assert_eq!(body.item_count(), 2);
assert_eq!(body.at(0).as_raw()[..], block.rlp().at(1).as_raw()[..]);
assert_eq!(body.at(1).as_raw()[..], block.rlp().at(2).as_raw()[..]);
}
2016-01-27 13:23:24 +01:00
#[test]
fn imports_block_sequence() {
2017-04-06 19:26:17 +02:00
let client = generate_dummy_client(6);
let block = client.block_header(BlockId::Number(5)).unwrap();
2016-01-27 13:23:24 +01:00
assert!(!block.into_inner().is_empty());
2016-01-27 13:23:24 +01:00
}
#[test]
fn can_collect_garbage() {
2017-04-06 19:26:17 +02:00
let client = generate_dummy_client(100);
client.tick(true);
2016-02-25 14:09:39 +01:00
assert!(client.blockchain_cache_info().blocks < 100 * 1024);
2016-02-02 22:50:41 +01:00
}
2016-03-02 15:06:53 +01:00
#[test]
fn can_generate_gas_price_median() {
2017-04-06 19:26:17 +02:00
let client = generate_dummy_client_with_data(3, 1, slice_into![1, 2, 3]);
2017-02-17 16:18:31 +01:00
assert_eq!(Some(&U256::from(2)), client.gas_price_corpus(3).median());
2017-04-06 19:26:17 +02:00
let client = generate_dummy_client_with_data(4, 1, slice_into![1, 4, 3, 2]);
2017-02-17 16:18:31 +01:00
assert_eq!(Some(&U256::from(3)), client.gas_price_corpus(3).median());
}
#[test]
fn can_generate_gas_price_histogram() {
2017-04-06 19:26:17 +02:00
let client = generate_dummy_client_with_data(20, 1, slice_into![6354,8593,6065,4842,7845,7002,689,4958,4250,6098,5804,4320,643,8895,2296,8589,7145,2000,2512,1408]);
2017-02-17 16:18:31 +01:00
let hist = client.gas_price_corpus(20).histogram(5).unwrap();
let correct_hist = ::stats::Histogram { bucket_bounds: vec_into![643, 2294, 3945, 5596, 7247, 8898], counts: vec![4,2,4,6,4] };
assert_eq!(hist, correct_hist);
}
#[test]
fn empty_gas_price_histogram() {
2017-04-06 19:26:17 +02:00
let client = generate_dummy_client_with_data(20, 0, slice_into![]);
2017-02-17 16:18:31 +01:00
assert!(client.gas_price_corpus(20).histogram(5).is_none());
}
#[test]
fn corpus_is_sorted() {
2017-04-06 19:26:17 +02:00
let client = generate_dummy_client_with_data(2, 1, slice_into![U256::from_str("11426908979").unwrap(), U256::from_str("50426908979").unwrap()]);
let corpus = client.gas_price_corpus(20);
assert!(corpus[0] < corpus[1]);
}
2016-03-02 15:06:53 +01:00
#[test]
fn can_handle_long_fork() {
2017-04-06 19:26:17 +02:00
let client = generate_dummy_client(1200);
2016-05-27 18:57:12 +02:00
for _ in 0..20 {
client.import_verified_blocks();
2016-03-02 15:06:53 +01:00
}
assert_eq!(1200, client.chain_info().best_block_number);
2017-04-06 19:26:17 +02:00
push_blocks_to_client(&client, 45, 1201, 800);
push_blocks_to_client(&client, 49, 1201, 800);
push_blocks_to_client(&client, 53, 1201, 600);
2016-03-02 15:06:53 +01:00
for _ in 0..400 {
client.import_verified_blocks();
2016-03-02 15:06:53 +01:00
}
assert_eq!(2000, client.chain_info().best_block_number);
}
2016-03-02 00:34:38 +01:00
#[test]
fn can_mine() {
let dummy_blocks = get_good_dummy_block_seq(2);
2017-04-06 19:26:17 +02:00
let client = get_test_client_with_blocks(vec![dummy_blocks[0].clone()]);
2016-06-23 14:43:20 +02:00
let b = client.prepare_open_block(Address::default(), (3141562.into(), 31415620.into()), vec![]).close();
assert_eq!(*b.block().header().parent_hash(), BlockView::new(&dummy_blocks[0]).header_view().hash());
}
#[test]
fn change_history_size() {
let tempdir = TempDir::new("").unwrap();
let test_spec = Spec::new_null();
let mut config = ClientConfig::default();
let db_config = DatabaseConfig::with_columns(::db::NUM_COLUMNS);
let client_db = Arc::new(Database::open(&db_config, tempdir.path().to_str().unwrap()).unwrap());
config.history = 2;
let address = Address::random();
{
let client = Client::new(
ClientConfig::default(),
&test_spec,
client_db.clone(),
Arc::new(Miner::with_spec(&test_spec)),
IoChannel::disconnected()
).unwrap();
for _ in 0..20 {
let mut b = client.prepare_open_block(Address::default(), (3141562.into(), 31415620.into()), vec![]);
b.block_mut().state_mut().add_balance(&address, &5.into(), CleanupMode::NoEmpty).unwrap();
b.block_mut().state_mut().commit().unwrap();
let b = b.close_and_lock().seal(&*test_spec.engine, vec![]).unwrap();
client.import_sealed_block(b).unwrap(); // account change is in the journal overlay
}
}
let mut config = ClientConfig::default();
config.history = 10;
let client = Client::new(
config,
&test_spec,
client_db,
Arc::new(Miner::with_spec(&test_spec)),
IoChannel::disconnected(),
).unwrap();
assert_eq!(client.state().balance(&address).unwrap(), 100.into());
}
2016-12-16 13:27:14 +01:00
#[test]
fn does_not_propagate_delayed_transactions() {
let key = KeyPair::from_secret(keccak("test").into()).unwrap();
2016-12-16 13:27:14 +01:00
let secret = key.secret();
let tx0 = PendingTransaction::new(Transaction {
nonce: 0.into(),
gas_price: 0.into(),
gas: 21000.into(),
action: Action::Call(Address::default()),
value: 0.into(),
data: Vec::new(),
}.sign(secret, None), Some(Condition::Number(2)));
2016-12-16 13:27:14 +01:00
let tx1 = PendingTransaction::new(Transaction {
nonce: 1.into(),
gas_price: 0.into(),
gas: 21000.into(),
action: Action::Call(Address::default()),
value: 0.into(),
data: Vec::new(),
}.sign(secret, None), None);
2017-04-06 19:26:17 +02:00
let client = generate_dummy_client(1);
2016-12-16 13:27:14 +01:00
2017-04-06 19:26:17 +02:00
client.miner().import_own_transaction(&*client, tx0).unwrap();
client.miner().import_own_transaction(&*client, tx1).unwrap();
2016-12-16 14:54:26 +01:00
assert_eq!(0, client.ready_transactions().len());
assert_eq!(2, client.miner().pending_transactions().len());
2017-04-06 19:26:17 +02:00
push_blocks_to_client(&client, 53, 2, 2);
2016-12-17 12:28:31 +01:00
client.flush_queue();
2016-12-16 14:54:26 +01:00
assert_eq!(2, client.ready_transactions().len());
assert_eq!(2, client.miner().pending_transactions().len());
2016-12-16 13:27:14 +01:00
}
#[test]
fn transaction_proof() {
use ::client::ProvingBlockChainClient;
2017-04-06 19:26:17 +02:00
let client = generate_dummy_client(0);
let address = Address::random();
let test_spec = Spec::new_test();
for _ in 0..20 {
let mut b = client.prepare_open_block(Address::default(), (3141562.into(), 31415620.into()), vec![]);
b.block_mut().state_mut().add_balance(&address, &5.into(), CleanupMode::NoEmpty).unwrap();
b.block_mut().state_mut().commit().unwrap();
let b = b.close_and_lock().seal(&*test_spec.engine, vec![]).unwrap();
client.import_sealed_block(b).unwrap(); // account change is in the journal overlay
}
let transaction = Transaction {
nonce: 0.into(),
gas_price: 0.into(),
gas: 21000.into(),
action: Action::Call(Address::default()),
value: 5.into(),
data: Vec::new(),
}.fake_sign(address);
2017-04-19 14:58:19 +02:00
let proof = client.prove_transaction(transaction.clone(), BlockId::Latest).unwrap().1;
let backend = state::backend::ProofCheck::new(&proof);
let mut factories = ::factory::Factories::default();
factories.accountdb = ::account_db::Factory::Plain; // raw state values, no mangled keys.
let root = *client.best_block_header().state_root();
let mut state = State::from_existing(backend, root, 0.into(), factories.clone()).unwrap();
Executive::new(&mut state, &client.latest_env_info(), test_spec.engine.machine())
.transact(&transaction, TransactOptions::with_no_tracing().dont_check_nonce()).unwrap();
assert_eq!(state.balance(&Address::default()).unwrap(), 5.into());
assert_eq!(state.balance(&address).unwrap(), 95.into());
}