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

Commit fcc291f

Browse files
committed
better docs, move type to common types, merge ImportBlocks and ExportBlocks
1 parent 832b176 commit fcc291f

File tree

7 files changed

+176
-135
lines changed

7 files changed

+176
-135
lines changed

ethcore/blockchain/src/blockchain.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -595,7 +595,7 @@ impl BlockChain {
595595
let best_block_rlp = bc.block(&best_block_hash)
596596
.expect("Best block is from a known block hash; qed");
597597

598-
// and write them
598+
// and write them to the cache.
599599
let mut best_block = bc.best_block.write();
600600
*best_block = BestBlock {
601601
total_difficulty: best_block_total_difficulty,
@@ -864,7 +864,7 @@ impl BlockChain {
864864
self.block_details.write().clear();
865865
self.block_hashes.write().clear();
866866
self.block_headers.write().clear();
867-
// Fetch best block details
867+
// Fetch best block details from disk
868868
let best_block_hash = self.db.key_value().get(db::COL_EXTRA, b"best")
869869
.expect("Low-level database error when fetching 'best' block. Some issue with disk?")
870870
.as_ref()
@@ -876,7 +876,7 @@ impl BlockChain {
876876
let best_block_rlp = self.block(&best_block_hash)
877877
.expect("Best block is from a known block hash; qed");
878878

879-
// and write them
879+
// and write them to the cache
880880
let mut best_block = self.best_block.write();
881881
*best_block = BestBlock {
882882
total_difficulty: best_block_total_difficulty,

ethcore/client-traits/src/lib.rs

Lines changed: 12 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ use trace::{
5555
localized::LocalizedTrace,
5656
VMTrace,
5757
};
58+
use common_types::data_format::DataFormat;
5859
use vm::{LastHashes, Schedule};
5960
use std::str::FromStr;
6061

@@ -510,34 +511,11 @@ pub trait ChainNotify: Send + Sync {
510511
fn transactions_received(&self, _txs: &[UnverifiedTransaction], _peer_id: usize) {
511512
// does nothing by default
512513
}
513-
514-
#[derive(Debug, PartialEq)]
515-
pub enum DataFormat {
516-
Hex,
517-
Binary,
518-
}
519-
520-
impl Default for DataFormat {
521-
fn default() -> Self {
522-
DataFormat::Binary
523-
}
524-
}
525-
526-
impl FromStr for DataFormat {
527-
type Err = String;
528-
529-
fn from_str(s: &str) -> Result<Self, Self::Err> {
530-
match s {
531-
"binary" | "bin" => Ok(DataFormat::Binary),
532-
"hex" => Ok(DataFormat::Hex),
533-
x => Err(format!("Invalid format: {}", x))
534-
}
535-
}
536514
}
537515

538-
/// Provides a method for exporting blocks
539-
pub trait ExportBlocks {
540-
/// Export blocks to destination, with the given from, to and format arguments.
516+
/// Provides a method for importing/exporting blocks
517+
pub trait ImportExportBlocks {
518+
/// Export blocks to destination, with the given from, to and format argument.
541519
/// destination could be a file or stdout.
542520
/// if the format is hex, each block is written on a new line.
543521
/// for binary exports, all block data is written to the same line.
@@ -548,18 +526,15 @@ pub trait ExportBlocks {
548526
to: BlockId,
549527
format: Option<DataFormat>
550528
) -> Result<(), String>;
551-
}
552529

553-
/// Provides a method for importing blocks
554-
pub trait ImportBlocks {
555-
/// Import blocks from destination, with the given format arguments
556-
/// source could be a file or stdout.
557-
/// For hex imports, it attempts to read the blocks on a line by line basis.
558-
/// For binary imports, it'll read the 8 byte rlp header in order to decode the block
530+
/// Import blocks from destination, with the given format argument
531+
/// Source could be a file or stdout.
532+
/// For hex format imports, it attempts to read the blocks on a line by line basis.
533+
/// For binary format imports, reads the 8 byte RLP header in order to decode the block
559534
/// length to be read.
560535
fn import_blocks<'a>(
561-
&self,
562-
source: Box<dyn std::io::Read + 'a>,
563-
format: Option<DataFormat>
564-
) -> Result<(), String>;
536+
&self,
537+
source: Box<dyn std::io::Read + 'a>,
538+
format: Option<DataFormat>
539+
) -> Result<(), String>;
565540
}

ethcore/src/client/client.rs

Lines changed: 110 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -15,116 +15,129 @@
1515
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
1616

1717
use std::cmp;
18-
use std::collections::{HashSet, BTreeMap, VecDeque};
19-
use std::sync::atomic::{AtomicUsize, AtomicBool, Ordering as AtomicOrdering};
18+
use std::collections::{BTreeMap, HashSet, VecDeque};
19+
use std::io::{BufRead, BufReader};
20+
use std::str::from_utf8;
2021
use std::sync::{Arc, Weak};
21-
use std::time::{Instant, Duration};
22+
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrdering};
23+
use std::time::{Duration, Instant};
2224

23-
use account_state::state::StateInfo;
24-
use blockchain::{BlockReceipts, BlockChain, BlockChainDB, BlockProvider, TreeRoute, TransactionAddress, ExtrasInsert, BlockNumberKey};
25+
use ansi_term::Colour;
2526
use bytes::Bytes;
26-
use call_contract::{CallContract, RegistryInfo};
27-
use ethcore_miner::pool::VerifiedTransaction;
28-
use ethereum_types::{H256, H264, Address, U256};
29-
use evm::Schedule;
27+
use bytes::ToPretty;
28+
use ethereum_types::{Address, H256, H264, U256};
3029
use hash::keccak;
31-
use io::IoChannel;
30+
use hash_db::EMPTY_PREFIX;
3231
use itertools::Itertools;
33-
use journaldb;
34-
use kvdb::{DBValue, KeyValueDB, DBTransaction};
32+
use kvdb::{DBTransaction, DBValue, KeyValueDB};
3533
use parking_lot::{Mutex, RwLock};
3634
use rand::rngs::OsRng;
37-
use trie::{TrieSpec, TrieFactory, Trie};
38-
use vm::{EnvInfo, LastHashes, CreateContractAddress};
39-
use hash_db::EMPTY_PREFIX;
40-
use block::{LockedBlock, Drain, ClosedBlock, OpenBlock, enact_verified, SealedBlock};
41-
use client::ancient_import::AncientVerifier;
35+
use rlp::PayloadInfo;
36+
use rustc_hex::FromHex;
37+
use trie::{Trie, TrieFactory, TrieSpec};
38+
39+
use account_state::State;
40+
use account_state::state::StateInfo;
41+
use block::{ClosedBlock, Drain, enact_verified, LockedBlock, OpenBlock, SealedBlock};
42+
use blockchain::{
43+
BlockChain,
44+
BlockChainDB,
45+
BlockNumberKey,
46+
BlockProvider,
47+
BlockReceipts,
48+
ExtrasInsert,
49+
TransactionAddress,
50+
TreeRoute
51+
};
52+
// re-export
53+
pub use blockchain::CacheSize as BlockChainCacheSize;
54+
use call_contract::{CallContract, RegistryInfo};
4255
use client::{
43-
ReopenBlock, PrepareOpenBlock, ImportSealedBlock, BroadcastProposalBlock,
44-
Call, BlockProducer, SealedBlockImporter, EngineInfo,
45-
ClientConfig, bad_blocks,
56+
bad_blocks, BlockProducer, BroadcastProposalBlock, Call,
57+
ClientConfig, EngineInfo, ImportSealedBlock, PrepareOpenBlock,
58+
ReopenBlock, SealedBlockImporter,
4659
};
60+
use client::ancient_import::AncientVerifier;
4761
use client_traits::{
48-
BlockInfo,
49-
ScheduleInfo,
50-
StateClient,
51-
BlockChainReset,
52-
Nonce,
53-
Balance,
54-
ChainInfo,
55-
TransactionInfo,
56-
ImportBlock,
5762
AccountData,
63+
BadBlocks,
64+
Balance,
5865
BlockChain as BlockChainTrait,
5966
BlockChainClient,
67+
BlockChainReset,
68+
BlockInfo,
69+
ChainInfo,
70+
ChainNotify,
71+
DatabaseRestore,
72+
ImportBlock,
73+
ImportExportBlocks,
6074
IoClient,
61-
BadBlocks,
75+
Nonce,
6276
ProvingBlockChainClient,
77+
ScheduleInfo,
78+
SnapshotClient,
79+
SnapshotWriter,
80+
StateClient,
6381
StateOrBlock,
64-
ExportBlocks,
65-
DataFormat,
66-
ImportBlocks
82+
Tick,
83+
TransactionInfo
6784
};
85+
use db::{keys::BlockDetails, Readable, Writable};
6886
use engine::Engine;
87+
use ethcore_miner::pool::VerifiedTransaction;
88+
use ethtrie::Layout;
89+
use evm::Schedule;
90+
use executive_state;
91+
use io::IoChannel;
92+
use journaldb;
6993
use machine::{
7094
executed::Executed,
71-
executive::{Executive, TransactOptions, contract_address},
95+
executive::{contract_address, Executive, TransactOptions},
7296
transaction_ext::Transaction,
7397
};
74-
use trie_vm_factories::{Factories, VmFactory};
7598
use miner::{Miner, MinerService};
7699
use snapshot;
77100
use spec::Spec;
78-
use account_state::State;
79-
use executive_state;
80101
use state_db::StateDB;
81-
use trace::{self, TraceDB, ImportRequest as TraceImportRequest, LocalizedTrace, Database as TraceDatabase};
102+
use trace::{self, Database as TraceDatabase, ImportRequest as TraceImportRequest, LocalizedTrace, TraceDB};
103+
use trie_vm_factories::{Factories, VmFactory};
82104
use types::{
83105
ancestry_action::AncestryAction,
84-
BlockNumber,
85106
block::PreverifiedBlock,
86107
block_status::BlockStatus,
87108
blockchain_info::BlockChainInfo,
88-
chain_notify::{NewBlocks, ChainRoute, ChainMessageType},
109+
BlockNumber,
110+
call_analytics::CallAnalytics,
111+
chain_notify::{ChainMessageType, ChainRoute, NewBlocks},
89112
client_types::ClientReport,
90-
import_route::ImportRoute,
91-
io_message::ClientIoMessage,
113+
client_types::Mode,
92114
encoded,
93115
engines::{
94-
ForkChoice,
95-
SealingState,
96-
MAX_UNCLE_AGE,
97116
epoch::{PendingTransition, Transition as EpochTransition},
117+
ForkChoice,
98118
machine::{AuxiliaryData, Call as MachineCall},
119+
MAX_UNCLE_AGE,
120+
SealingState,
99121
},
100-
errors::{EngineError, ExecutionError, BlockError, EthcoreError, SnapshotError, ImportError, EthcoreResult},
101-
ids::{BlockId, TransactionId, UncleId, TraceId},
102-
transaction::{self, LocalizedTransaction, UnverifiedTransaction, SignedTransaction, Action, CallError},
122+
errors::{BlockError, EngineError, EthcoreError, EthcoreResult, ExecutionError, ImportError, SnapshotError},
103123
filter::Filter,
104-
log_entry::LocalizedLogEntry,
105-
receipt::{Receipt, LocalizedReceipt},
106124
header::Header,
125+
ids::{BlockId, TraceId, TransactionId, UncleId},
126+
import_route::ImportRoute,
127+
io_message::ClientIoMessage,
128+
log_entry::LocalizedLogEntry,
129+
pruning_info::PruningInfo,
130+
receipt::{LocalizedReceipt, Receipt},
107131
snapshot::{Progress, Snapshotting},
108132
trace_filter::Filter as TraceFilter,
109-
pruning_info::PruningInfo,
110-
call_analytics::CallAnalytics,
111-
client_types::Mode,
133+
transaction::{self, Action, CallError, LocalizedTransaction, SignedTransaction, UnverifiedTransaction},
112134
verification::{Unverified, VerificationQueueInfo as BlockQueueInfo},
113135
};
114-
115-
use verification::queue::kind::BlockLike;
116-
use verification::{Verifier, BlockQueue};
136+
use types::data_format::DataFormat;
137+
use verification::{BlockQueue, Verifier};
117138
use verification;
118-
use ansi_term::Colour;
119-
use ethtrie::Layout;
120-
// re-export
121-
pub use blockchain::CacheSize as BlockChainCacheSize;
122-
use db::{Writable, Readable, keys::BlockDetails};
123-
use rlp::PayloadInfo;
124-
use std::io::{BufReader, BufRead};
125-
use rustc_hex::FromHex;
126-
use std::str::from_utf8;
127-
use bytes::ToPretty;
139+
use verification::queue::kind::BlockLike;
140+
use vm::{CreateContractAddress, EnvInfo, LastHashes};
128141

129142
use_contract!(registry, "res/contracts/registrar.json");
130143

@@ -2573,10 +2586,16 @@ impl SnapshotClient for Client {
25732586

25742587
}
25752588

2576-
impl ExportBlocks for Client {
2577-
fn export_blocks<'a>(&self, mut out: Box<dyn std::io::Write + 'a>, from: BlockId, to: BlockId, format: Option<DataFormat>) -> Result<(), String> {
2578-
let from = self.block_number(from).ok_or("From block could not be found")?;
2579-
let to = self.block_number(to).ok_or("To block could not be found")?;
2589+
impl ImportExportBlocks for Client {
2590+
fn export_blocks<'a>(
2591+
&self,
2592+
mut out: Box<dyn std::io::Write + 'a>,
2593+
from: BlockId,
2594+
to: BlockId,
2595+
format: Option<DataFormat>
2596+
) -> Result<(), String> {
2597+
let from = self.block_number(from).ok_or("Starting block could not be found")?;
2598+
let to = self.block_number(to).ok_or("End block could not be found")?;
25802599
let format = format.unwrap_or_default();
25812600

25822601
for i in from..=to {
@@ -2595,10 +2614,7 @@ impl ExportBlocks for Client {
25952614
}
25962615
Ok(())
25972616
}
2598-
}
2599-
26002617

2601-
impl ImportBlocks for Client {
26022618
fn import_blocks<'a>(
26032619
&self,
26042620
mut source: Box<dyn std::io::Read + 'a>,
@@ -2620,7 +2636,7 @@ impl ImportBlocks for Client {
26202636
}
26212637
};
26222638

2623-
let do_import = |bytes| {
2639+
let do_import = |bytes: Vec<u8>| {
26242640
let block = Unverified::from_rlp(bytes).map_err(|_| "Invalid block rlp")?;
26252641
while self.queue_info().is_full() { std::thread::sleep(Duration::from_secs(1)); }
26262642
match self.import_block(block) {
@@ -2658,7 +2674,8 @@ impl ImportBlocks for Client {
26582674
}
26592675
DataFormat::Hex => {
26602676
for line in BufReader::new(source).lines() {
2661-
let s = line.map_err(|err| format!("Error reading from the file/stream: {:?}", err))?;
2677+
let s = line
2678+
.map_err(|err| format!("Error reading from the file/stream: {:?}", err))?;
26622679
let s = if first_read > 0 {
26632680
from_utf8(&first_bytes)
26642681
.map_err(|err| format!("Invalid UTF-8: {:?}", err))?
@@ -2667,7 +2684,8 @@ impl ImportBlocks for Client {
26672684
s
26682685
};
26692686
first_read = 0;
2670-
let bytes = s.from_hex().map_err(|err| format!("Invalid hex in file/stream: {:?}", err))?;
2687+
let bytes = s.from_hex()
2688+
.map_err(|err| format!("Invalid hex in file/stream: {:?}", err))?;
26712689
do_import(bytes)?;
26722690
}
26732691
}
@@ -2756,26 +2774,29 @@ impl IoChannelQueue {
27562774

27572775
#[cfg(test)]
27582776
mod tests {
2759-
use ethereum_types::{H256, Address};
2777+
use std::sync::Arc;
2778+
use std::sync::atomic::{AtomicBool, Ordering};
2779+
use std::thread;
2780+
use std::time::Duration;
2781+
2782+
use ethereum_types::{Address, H256};
2783+
use hash::keccak;
2784+
use kvdb::DBTransaction;
2785+
2786+
use blockchain::ExtrasInsert;
27602787
use client_traits::{BlockChainClient, ChainInfo};
2788+
use ethkey::KeyPair;
2789+
use test_helpers::{generate_dummy_client, generate_dummy_client_with_data, get_good_dummy_block_hash};
27612790
use types::{
27622791
encoded,
27632792
engines::ForkChoice,
27642793
ids::{BlockId, TransactionId},
2765-
log_entry::{LogEntry, LocalizedLogEntry},
2766-
receipt::{Receipt, LocalizedReceipt, TransactionOutcome},
2767-
transaction::{Transaction, LocalizedTransaction, Action},
2794+
log_entry::{LocalizedLogEntry, LogEntry},
2795+
receipt::{LocalizedReceipt, Receipt, TransactionOutcome},
2796+
transaction::{Action, LocalizedTransaction, Transaction},
27682797
};
2769-
use test_helpers::{generate_dummy_client, get_good_dummy_block_hash, generate_dummy_client_with_data};
2770-
use std::thread;
2771-
use std::time::Duration;
2772-
use std::sync::Arc;
2773-
use std::sync::atomic::{AtomicBool, Ordering};
2774-
use kvdb::DBTransaction;
2775-
use blockchain::ExtrasInsert;
2776-
use hash::keccak;
2798+
27772799
use super::transaction_receipt;
2778-
use ethkey::KeyPair;
27792800

27802801
#[test]
27812802
fn should_not_cache_details_before_commit() {

0 commit comments

Comments
 (0)