Remove private transactions

This commit is contained in:
Artem Vorotnikov
2020-09-02 18:43:14 +03:00
parent a8668b371c
commit ea0c13c0a4
54 changed files with 38 additions and 3992 deletions

View File

@@ -30,9 +30,8 @@ use std::{
};
use chain::{
sync_packet::SyncPacket::{PrivateTransactionPacket, SignedPrivateTransactionPacket},
ChainSyncApi, SyncStatus as EthSyncStatus, ETH_PROTOCOL_VERSION_62, ETH_PROTOCOL_VERSION_63,
PAR_PROTOCOL_VERSION_1, PAR_PROTOCOL_VERSION_2, PAR_PROTOCOL_VERSION_3,
PAR_PROTOCOL_VERSION_1, PAR_PROTOCOL_VERSION_2,
};
use ethcore::{
client::{BlockChainClient, ChainMessageType, ChainNotify, NewBlocks},
@@ -43,7 +42,6 @@ use ethkey::Secret;
use io::TimerToken;
use network::IpFilter;
use parking_lot::{Mutex, RwLock};
use private_tx::PrivateTxHandler;
use std::{
net::{AddrParseError, SocketAddr},
str::FromStr,
@@ -214,8 +212,6 @@ pub struct Params {
pub chain: Arc<dyn BlockChainClient>,
/// Snapshot service.
pub snapshot_service: Arc<dyn SnapshotService>,
/// Private tx service.
pub private_tx_handler: Option<Arc<dyn PrivateTxHandler>>,
/// Network layer configuration.
pub network_config: NetworkConfiguration,
}
@@ -239,12 +235,7 @@ impl EthSync {
connection_filter: Option<Arc<dyn ConnectionFilter>>,
) -> Result<Arc<EthSync>, Error> {
let (priority_tasks_tx, priority_tasks_rx) = mpsc::channel();
let sync = ChainSyncApi::new(
params.config,
&*params.chain,
params.private_tx_handler.as_ref().cloned(),
priority_tasks_rx,
);
let sync = ChainSyncApi::new(params.config, &*params.chain, priority_tasks_rx);
let service = NetworkService::new(
params.network_config.clone().into_basic()?,
connection_filter,
@@ -463,11 +454,7 @@ impl ChainNotify for EthSync {
.register_protocol(
self.eth_handler.clone(),
PAR_PROTOCOL,
&[
PAR_PROTOCOL_VERSION_1,
PAR_PROTOCOL_VERSION_2,
PAR_PROTOCOL_VERSION_3,
],
&[PAR_PROTOCOL_VERSION_1, PAR_PROTOCOL_VERSION_2],
)
.unwrap_or_else(|e| warn!("Error registering snapshot sync protocol: {:?}", e));
}
@@ -491,22 +478,6 @@ impl ChainNotify for EthSync {
.sync
.write()
.propagate_consensus_packet(&mut sync_io, message),
ChainMessageType::PrivateTransaction(transaction_hash, message) => {
self.eth_handler.sync.write().propagate_private_transaction(
&mut sync_io,
transaction_hash,
PrivateTransactionPacket,
message,
)
}
ChainMessageType::SignedPrivateTransaction(transaction_hash, message) => {
self.eth_handler.sync.write().propagate_private_transaction(
&mut sync_io,
transaction_hash,
SignedPrivateTransactionPacket,
message,
)
}
}
});
}

View File

@@ -36,15 +36,14 @@ use super::sync_packet::{
PacketInfo, SyncPacket,
SyncPacket::{
BlockBodiesPacket, BlockHeadersPacket, NewBlockHashesPacket, NewBlockPacket,
PrivateTransactionPacket, ReceiptsPacket, SignedPrivateTransactionPacket,
SnapshotDataPacket, SnapshotManifestPacket, StatusPacket,
ReceiptsPacket, SnapshotDataPacket, SnapshotManifestPacket, StatusPacket,
},
};
use super::{
BlockSet, ChainSync, ForkConfirmation, PacketDecodeError, PeerAsking, PeerInfo, SyncRequester,
SyncState, ETH_PROTOCOL_VERSION_62, ETH_PROTOCOL_VERSION_63, MAX_NEW_BLOCK_AGE, MAX_NEW_HASHES,
PAR_PROTOCOL_VERSION_1, PAR_PROTOCOL_VERSION_3,
PAR_PROTOCOL_VERSION_1, PAR_PROTOCOL_VERSION_2,
};
/// The Chain Sync Handler: handles responses from peers
@@ -70,12 +69,6 @@ impl SyncHandler {
NewBlockHashesPacket => SyncHandler::on_peer_new_hashes(sync, io, peer, &rlp),
SnapshotManifestPacket => SyncHandler::on_snapshot_manifest(sync, io, peer, &rlp),
SnapshotDataPacket => SyncHandler::on_snapshot_data(sync, io, peer, &rlp),
PrivateTransactionPacket => {
SyncHandler::on_private_transaction(sync, io, peer, &rlp)
}
SignedPrivateTransactionPacket => {
SyncHandler::on_signed_private_transaction(sync, io, peer, &rlp)
}
_ => {
debug!(target: "sync", "{}: Unknown packet {}", peer, packet_id.id());
Ok(())
@@ -661,7 +654,6 @@ impl SyncHandler {
let protocol_version: u8 = r.val_at(0)?;
let warp_protocol_version = io.protocol_version(&PAR_PROTOCOL, peer_id);
let warp_protocol = warp_protocol_version != 0;
let private_tx_protocol = warp_protocol_version >= PAR_PROTOCOL_VERSION_3.0;
let peer = PeerInfo {
protocol_version: protocol_version,
network_id: r.val_at(1)?,
@@ -673,7 +665,6 @@ impl SyncHandler {
asking_hash: None,
ask_time: Instant::now(),
last_sent_transactions: Default::default(),
last_sent_private_transactions: Default::default(),
expired: false,
confirmation: if sync.fork_block.is_none() {
ForkConfirmation::Confirmed
@@ -692,11 +683,6 @@ impl SyncHandler {
None
},
block_set: None,
private_tx_enabled: if private_tx_protocol {
r.val_at(7).unwrap_or(false)
} else {
false
},
client_version: ClientVersion::from(io.peer_version(peer_id)),
};
@@ -706,16 +692,14 @@ impl SyncHandler {
difficulty: {:?}, \
latest:{}, \
genesis:{}, \
snapshot:{:?}, \
private_tx_enabled:{})",
snapshot:{:?})",
peer_id,
peer.protocol_version,
peer.network_id,
peer.difficulty,
peer.latest_hash,
peer.genesis,
peer.snapshot_number,
peer.private_tx_enabled
peer.snapshot_number
);
if io.is_expired() {
trace!(target: "sync", "Status packet from expired session {}:{}", peer_id, io.peer_version(peer_id));
@@ -739,7 +723,7 @@ impl SyncHandler {
if false
|| (warp_protocol
&& (peer.protocol_version < PAR_PROTOCOL_VERSION_1.0
|| peer.protocol_version > PAR_PROTOCOL_VERSION_3.0))
|| peer.protocol_version > PAR_PROTOCOL_VERSION_2.0))
|| (!warp_protocol
&& (peer.protocol_version < ETH_PROTOCOL_VERSION_62.0
|| peer.protocol_version > ETH_PROTOCOL_VERSION_63.0))
@@ -795,72 +779,6 @@ impl SyncHandler {
io.chain().queue_transactions(transactions, peer_id);
Ok(())
}
/// Called when peer sends us signed private transaction packet
fn on_signed_private_transaction(
sync: &mut ChainSync,
_io: &mut dyn SyncIo,
peer_id: PeerId,
r: &Rlp,
) -> Result<(), DownloaderImportError> {
if !sync.peers.get(&peer_id).map_or(false, |p| p.can_sync()) {
trace!(target: "sync", "{} Ignoring packet from unconfirmed/unknown peer", peer_id);
return Ok(());
}
let private_handler = match sync.private_tx_handler {
Some(ref handler) => handler,
None => {
trace!(target: "sync", "{} Ignoring private tx packet from peer", peer_id);
return Ok(());
}
};
trace!(target: "sync", "Received signed private transaction packet from {:?}", peer_id);
match private_handler.import_signed_private_transaction(r.as_raw()) {
Ok(transaction_hash) => {
//don't send the packet back
if let Some(ref mut peer) = sync.peers.get_mut(&peer_id) {
peer.last_sent_private_transactions.insert(transaction_hash);
}
}
Err(e) => {
trace!(target: "sync", "Ignoring the message, error queueing: {}", e);
}
}
Ok(())
}
/// Called when peer sends us new private transaction packet
fn on_private_transaction(
sync: &mut ChainSync,
_io: &mut dyn SyncIo,
peer_id: PeerId,
r: &Rlp,
) -> Result<(), DownloaderImportError> {
if !sync.peers.get(&peer_id).map_or(false, |p| p.can_sync()) {
trace!(target: "sync", "{} Ignoring packet from unconfirmed/unknown peer", peer_id);
return Ok(());
}
let private_handler = match sync.private_tx_handler {
Some(ref handler) => handler,
None => {
trace!(target: "sync", "{} Ignoring private tx packet from peer", peer_id);
return Ok(());
}
};
trace!(target: "sync", "Received private transaction packet from {:?}", peer_id);
match private_handler.import_private_transaction(r.as_raw()) {
Ok(transaction_hash) => {
//don't send the packet back
if let Some(ref mut peer) = sync.peers.get_mut(&peer_id) {
peer.last_sent_private_transactions.insert(transaction_hash);
}
}
Err(e) => {
trace!(target: "sync", "Ignoring the message, error queueing: {}", e);
}
}
Ok(())
}
}
#[cfg(test)]

View File

@@ -107,14 +107,13 @@ use hash::keccak;
use heapsize::HeapSizeOf;
use network::{self, client_version::ClientVersion, PacketId, PeerId};
use parking_lot::{Mutex, RwLock, RwLockWriteGuard};
use private_tx::PrivateTxHandler;
use rand::Rng;
use rlp::{DecoderError, RlpStream};
use snapshot::Snapshot;
use std::{
cmp,
collections::{BTreeMap, HashMap, HashSet},
sync::{mpsc, Arc},
sync::mpsc,
time::{Duration, Instant},
};
use sync_io::SyncIo;
@@ -124,7 +123,7 @@ use types::{transaction::UnverifiedTransaction, BlockNumber};
use self::{
handler::SyncHandler,
sync_packet::{
PacketInfo, SyncPacket,
PacketInfo,
SyncPacket::{NewBlockPacket, StatusPacket},
},
};
@@ -144,8 +143,6 @@ pub const ETH_PROTOCOL_VERSION_62: (u8, u8) = (62, 0x11);
pub const PAR_PROTOCOL_VERSION_1: (u8, u8) = (1, 0x15);
/// 2 version of Parity protocol (consensus messages added).
pub const PAR_PROTOCOL_VERSION_2: (u8, u8) = (2, 0x16);
/// 3 version of Parity protocol (private transactions messages added).
pub const PAR_PROTOCOL_VERSION_3: (u8, u8) = (3, 0x18);
pub const MAX_BODIES_TO_SEND: usize = 256;
pub const MAX_HEADERS_TO_SEND: usize = 512;
@@ -318,12 +315,8 @@ pub struct PeerInfo {
ask_time: Instant,
/// Holds a set of transactions recently sent to this peer to avoid spamming.
last_sent_transactions: H256FastSet,
/// Holds a set of private transactions and their signatures recently sent to this peer to avoid spamming.
last_sent_private_transactions: H256FastSet,
/// Pending request is expired and result should be ignored
expired: bool,
/// Private transactions enabled
private_tx_enabled: bool,
/// Peer fork confirmation status
confirmation: ForkConfirmation,
/// Best snapshot hash
@@ -353,10 +346,6 @@ impl PeerInfo {
self.expired = true;
}
}
fn reset_private_stats(&mut self) {
self.last_sent_private_transactions.clear();
}
}
#[cfg(not(test))]
@@ -392,11 +381,10 @@ impl ChainSyncApi {
pub fn new(
config: SyncConfig,
chain: &dyn BlockChainClient,
private_tx_handler: Option<Arc<dyn PrivateTxHandler>>,
priority_tasks: mpsc::Receiver<PriorityTask>,
) -> Self {
ChainSyncApi {
sync: RwLock::new(ChainSync::new(config, chain, private_tx_handler)),
sync: RwLock::new(ChainSync::new(config, chain)),
priority_tasks: Mutex::new(priority_tasks),
}
}
@@ -640,19 +628,13 @@ pub struct ChainSync {
transactions_stats: TransactionsStats,
/// Enable ancient block downloading
download_old_blocks: bool,
/// Shared private tx service.
private_tx_handler: Option<Arc<dyn PrivateTxHandler>>,
/// Enable warp sync.
warp_sync: WarpSync,
}
impl ChainSync {
/// Create a new instance of syncing strategy.
pub fn new(
config: SyncConfig,
chain: &dyn BlockChainClient,
private_tx_handler: Option<Arc<dyn PrivateTxHandler>>,
) -> Self {
pub fn new(config: SyncConfig, chain: &dyn BlockChainClient) -> Self {
let chain_info = chain.chain_info();
let best_block = chain.chain_info().best_block_number;
let state = Self::get_init_state(config.warp_sync, chain);
@@ -677,7 +659,6 @@ impl ChainSync {
snapshot: Snapshot::new(),
sync_start_time: None,
transactions_stats: TransactionsStats::default(),
private_tx_handler,
warp_sync: config.warp_sync,
};
sync.update_targets(chain);
@@ -1207,7 +1188,6 @@ impl ChainSync {
fn send_status(&mut self, io: &mut dyn SyncIo, peer: PeerId) -> Result<(), network::Error> {
let warp_protocol_version = io.protocol_version(&PAR_PROTOCOL, peer);
let warp_protocol = warp_protocol_version != 0;
let private_tx_protocol = warp_protocol_version >= PAR_PROTOCOL_VERSION_3.0;
let protocol = if warp_protocol {
warp_protocol_version
} else {
@@ -1228,9 +1208,6 @@ impl ChainSync {
let manifest_hash = manifest.map_or(H256::new(), |m| keccak(m.into_rlp()));
packet.append(&manifest_hash);
packet.append(&block_number);
if private_tx_protocol {
packet.append(&self.private_tx_handler.is_some());
}
}
packet.complete_unbounded_list();
io.respond(StatusPacket.id(), packet.out())
@@ -1355,22 +1332,6 @@ impl ChainSync {
.collect()
}
fn get_private_transaction_peers(&self, transaction_hash: &H256) -> Vec<PeerId> {
self.peers
.iter()
.filter_map(|(id, p)| {
if p.protocol_version >= PAR_PROTOCOL_VERSION_3.0
&& !p.last_sent_private_transactions.contains(transaction_hash)
&& p.private_tx_enabled
{
Some(*id)
} else {
None
}
})
.collect()
}
/// Maintain other peers. Send out any new blocks and transactions
pub fn maintain_sync(&mut self, io: &mut dyn SyncIo) {
self.maybe_start_snapshot_sync(io);
@@ -1407,7 +1368,6 @@ impl ChainSync {
trace!(target: "sync", "Re-broadcasting transactions to a random peer.");
self.peers.values_mut().nth(peer).map(|peer_info| {
peer_info.last_sent_transactions.clear();
peer_info.reset_private_stats()
});
}
}
@@ -1443,23 +1403,6 @@ impl ChainSync {
pub fn propagate_consensus_packet(&mut self, io: &mut dyn SyncIo, packet: Bytes) {
SyncPropagator::propagate_consensus_packet(self, io, packet);
}
/// Broadcast private transaction message to peers.
pub fn propagate_private_transaction(
&mut self,
io: &mut dyn SyncIo,
transaction_hash: H256,
packet_id: SyncPacket,
packet: Bytes,
) {
SyncPropagator::propagate_private_transaction(
self,
io,
transaction_hash,
packet_id,
packet,
);
}
}
#[cfg(test)]
@@ -1565,7 +1508,7 @@ pub mod tests {
peer_latest_hash: H256,
client: &dyn BlockChainClient,
) -> ChainSync {
let mut sync = ChainSync::new(SyncConfig::default(), client, None);
let mut sync = ChainSync::new(SyncConfig::default(), client);
insert_dummy_peer(&mut sync, 0, peer_latest_hash);
sync
}
@@ -1584,9 +1527,7 @@ pub mod tests {
asking_hash: None,
ask_time: Instant::now(),
last_sent_transactions: Default::default(),
last_sent_private_transactions: Default::default(),
expired: false,
private_tx_enabled: false,
confirmation: super::ForkConfirmation::Confirmed,
snapshot_number: None,
snapshot_hash: None,

View File

@@ -328,29 +328,6 @@ impl SyncPropagator {
}
}
/// Broadcast private transaction message to peers.
pub fn propagate_private_transaction(
sync: &mut ChainSync,
io: &mut dyn SyncIo,
transaction_hash: H256,
packet_id: SyncPacket,
packet: Bytes,
) {
let lucky_peers =
ChainSync::select_random_peers(&sync.get_private_transaction_peers(&transaction_hash));
if lucky_peers.is_empty() {
error!(target: "privatetx", "Cannot propagate the packet, no peers with private tx enabled connected");
} else {
trace!(target: "privatetx", "Sending private transaction packet to {:?}", lucky_peers);
for peer_id in lucky_peers {
if let Some(ref mut peer) = sync.peers.get_mut(&peer_id) {
peer.last_sent_private_transactions.insert(transaction_hash);
}
SyncPropagator::send_packet(io, peer_id, packet_id, packet.clone());
}
}
}
fn select_peers_for_transactions<F>(sync: &ChainSync, filter: F) -> Vec<PeerId>
where
F: Fn(&PeerId) -> bool,
@@ -473,7 +450,7 @@ mod tests {
client.add_blocks(2, EachBlockWith::Uncle);
let queue = RwLock::new(VecDeque::new());
let block = client.block(BlockId::Latest).unwrap().into_inner();
let mut sync = ChainSync::new(SyncConfig::default(), &client, None);
let mut sync = ChainSync::new(SyncConfig::default(), &client);
sync.peers.insert(
0,
PeerInfo {
@@ -488,9 +465,7 @@ mod tests {
asking_hash: None,
ask_time: Instant::now(),
last_sent_transactions: Default::default(),
last_sent_private_transactions: Default::default(),
expired: false,
private_tx_enabled: false,
confirmation: ForkConfirmation::Confirmed,
snapshot_number: None,
snapshot_hash: None,
@@ -565,7 +540,7 @@ mod tests {
client.add_blocks(100, EachBlockWith::Uncle);
client.insert_transaction_to_queue();
// Sync with no peers
let mut sync = ChainSync::new(SyncConfig::default(), &client, None);
let mut sync = ChainSync::new(SyncConfig::default(), &client);
let queue = RwLock::new(VecDeque::new());
let ss = TestSnapshotService::new();
let mut io = TestIo::new(&mut client, &ss, &queue, None);
@@ -642,7 +617,7 @@ mod tests {
let mut client = TestBlockChainClient::new();
client.insert_transaction_with_gas_price_to_queue(U256::zero());
let block_hash = client.block_hash_delta_minus(1);
let mut sync = ChainSync::new(SyncConfig::default(), &client, None);
let mut sync = ChainSync::new(SyncConfig::default(), &client);
let queue = RwLock::new(VecDeque::new());
let ss = TestSnapshotService::new();
let mut io = TestIo::new(&mut client, &ss, &queue, None);
@@ -680,7 +655,7 @@ mod tests {
let tx1_hash = client.insert_transaction_to_queue();
let tx2_hash = client.insert_transaction_with_gas_price_to_queue(U256::zero());
let block_hash = client.block_hash_delta_minus(1);
let mut sync = ChainSync::new(SyncConfig::default(), &client, None);
let mut sync = ChainSync::new(SyncConfig::default(), &client);
let queue = RwLock::new(VecDeque::new());
let ss = TestSnapshotService::new();
let mut io = TestIo::new(&mut client, &ss, &queue, None);

View File

@@ -55,8 +55,6 @@ pub enum SyncPacket {
GetSnapshotDataPacket = 0x13,
SnapshotDataPacket = 0x14,
ConsensusDataPacket = 0x15,
PrivateTransactionPacket = 0x16,
SignedPrivateTransactionPacket = 0x17,
}
}
@@ -91,9 +89,7 @@ impl PacketInfo for SyncPacket {
| SnapshotManifestPacket
| GetSnapshotDataPacket
| SnapshotDataPacket
| ConsensusDataPacket
| PrivateTransactionPacket
| SignedPrivateTransactionPacket => PAR_PROTOCOL,
| ConsensusDataPacket => PAR_PROTOCOL,
}
}

View File

@@ -40,8 +40,6 @@ extern crate triehash_ethereum;
#[cfg(test)]
extern crate env_logger;
#[cfg(test)]
extern crate ethcore_private_tx;
#[cfg(test)]
extern crate kvdb_memorydb;
#[cfg(test)]
extern crate rustc_hex;
@@ -60,7 +58,6 @@ extern crate trace_time;
mod block_sync;
mod blocks;
mod chain;
mod private_tx;
mod snapshot;
mod sync_io;
mod transactions_stats;
@@ -74,4 +71,3 @@ pub use api::*;
pub use chain::{SyncState, SyncStatus};
pub use devp2p::validate_node_url;
pub use network::{ConnectionDirection, ConnectionFilter, Error, ErrorKind, NonReservedPeerMode};
pub use private_tx::{NoopPrivateTxHandler, PrivateTxHandler, SimplePrivateTxHandler};

View File

@@ -1,63 +0,0 @@
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity Ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
use ethereum_types::H256;
use parking_lot::Mutex;
/// Trait which should be implemented by a private transaction handler.
pub trait PrivateTxHandler: Send + Sync + 'static {
/// Function called on new private transaction received.
/// Returns the hash of the imported transaction
fn import_private_transaction(&self, rlp: &[u8]) -> Result<H256, String>;
/// Function called on new signed private transaction received.
/// Returns the hash of the imported transaction
fn import_signed_private_transaction(&self, rlp: &[u8]) -> Result<H256, String>;
}
/// Nonoperative private transaction handler.
pub struct NoopPrivateTxHandler;
impl PrivateTxHandler for NoopPrivateTxHandler {
fn import_private_transaction(&self, _rlp: &[u8]) -> Result<H256, String> {
Ok(H256::default())
}
fn import_signed_private_transaction(&self, _rlp: &[u8]) -> Result<H256, String> {
Ok(H256::default())
}
}
/// Simple private transaction handler. Used for tests.
#[derive(Default)]
pub struct SimplePrivateTxHandler {
/// imported private transactions
pub txs: Mutex<Vec<Vec<u8>>>,
/// imported signed private transactions
pub signed_txs: Mutex<Vec<Vec<u8>>>,
}
impl PrivateTxHandler for SimplePrivateTxHandler {
fn import_private_transaction(&self, rlp: &[u8]) -> Result<H256, String> {
self.txs.lock().push(rlp.to_vec());
Ok(H256::default())
}
fn import_signed_private_transaction(&self, rlp: &[u8]) -> Result<H256, String> {
self.signed_txs.lock().push(rlp.to_vec());
Ok(H256::default())
}
}

View File

@@ -17,11 +17,8 @@
use api::PAR_PROTOCOL;
use bytes::Bytes;
use chain::{
sync_packet::{
PacketInfo, SyncPacket,
SyncPacket::{PrivateTransactionPacket, SignedPrivateTransactionPacket},
},
ChainSync, SyncSupplier, ETH_PROTOCOL_VERSION_63, PAR_PROTOCOL_VERSION_3,
sync_packet::{PacketInfo, SyncPacket},
ChainSync, SyncSupplier, ETH_PROTOCOL_VERSION_63, PAR_PROTOCOL_VERSION_2,
};
use ethcore::{
client::{
@@ -36,7 +33,7 @@ use ethcore::{
use ethereum_types::H256;
use io::{IoChannel, IoContext, IoHandler};
use network::{self, client_version::ClientVersion, PacketId, PeerId, ProtocolId, SessionInfo};
use parking_lot::{Mutex, RwLock};
use parking_lot::RwLock;
use std::{
collections::{HashMap, HashSet, VecDeque},
sync::Arc,
@@ -44,7 +41,6 @@ use std::{
use sync_io::SyncIo;
use tests::snapshot::*;
use private_tx::SimplePrivateTxHandler;
use types::BlockNumber;
use SyncConfig;
@@ -177,7 +173,7 @@ where
fn protocol_version(&self, protocol: &ProtocolId, peer_id: PeerId) -> u8 {
if protocol == &PAR_PROTOCOL {
PAR_PROTOCOL_VERSION_3.0
PAR_PROTOCOL_VERSION_2.0
} else {
self.eth_protocol_version(peer_id)
}
@@ -262,7 +258,6 @@ where
pub snapshot_service: Arc<TestSnapshotService>,
pub sync: RwLock<ChainSync>,
pub queue: RwLock<VecDeque<TestPacket>>,
pub private_tx_handler: Arc<SimplePrivateTxHandler>,
pub io_queue: RwLock<VecDeque<ChainMessageType>>,
new_blocks_queue: RwLock<VecDeque<NewBlockMessage>>,
}
@@ -285,22 +280,6 @@ where
ChainMessageType::Consensus(data) => {
self.sync.write().propagate_consensus_packet(&mut io, data)
}
ChainMessageType::PrivateTransaction(transaction_hash, data) => {
self.sync.write().propagate_private_transaction(
&mut io,
transaction_hash,
PrivateTransactionPacket,
data,
)
}
ChainMessageType::SignedPrivateTransaction(transaction_hash, data) => {
self.sync.write().propagate_private_transaction(
&mut io,
transaction_hash,
SignedPrivateTransactionPacket,
data,
)
}
}
}
@@ -426,15 +405,13 @@ impl TestNet<EthPeer<TestBlockChainClient>> {
for _ in 0..n {
let chain = TestBlockChainClient::new();
let ss = Arc::new(TestSnapshotService::new());
let private_tx_handler = Arc::new(SimplePrivateTxHandler::default());
let sync = ChainSync::new(config.clone(), &chain, Some(private_tx_handler.clone()));
let sync = ChainSync::new(config.clone(), &chain);
net.peers.push(Arc::new(EthPeer {
sync: RwLock::new(sync),
snapshot_service: ss,
chain: Arc::new(chain),
miner: Arc::new(Miner::new_for_tests(&Spec::new_test(), None)),
queue: RwLock::new(VecDeque::new()),
private_tx_handler,
io_queue: RwLock::new(VecDeque::new()),
new_blocks_queue: RwLock::new(VecDeque::new()),
}));
@@ -476,16 +453,14 @@ impl TestNet<EthPeer<EthcoreClient>> {
)
.unwrap();
let private_tx_handler = Arc::new(SimplePrivateTxHandler::default());
let ss = Arc::new(TestSnapshotService::new());
let sync = ChainSync::new(config, &*client, Some(private_tx_handler.clone()));
let sync = ChainSync::new(config, &*client);
let peer = Arc::new(EthPeer {
sync: RwLock::new(sync),
snapshot_service: ss,
chain: client,
miner,
queue: RwLock::new(VecDeque::new()),
private_tx_handler,
io_queue: RwLock::new(VecDeque::new()),
new_blocks_queue: RwLock::new(VecDeque::new()),
});
@@ -604,15 +579,11 @@ impl<C: FlushingBlockChainClient> TestNet<EthPeer<C>> {
pub struct TestIoHandler {
pub client: Arc<EthcoreClient>,
pub private_tx_queued: Mutex<usize>,
}
impl TestIoHandler {
pub fn new(client: Arc<EthcoreClient>) -> Self {
TestIoHandler {
client,
private_tx_queued: Mutex::default(),
}
TestIoHandler { client }
}
}
@@ -620,7 +591,6 @@ impl IoHandler<ClientIoMessage> for TestIoHandler {
fn message(&self, _io: &IoContext<ClientIoMessage>, net_message: &ClientIoMessage) {
match *net_message {
ClientIoMessage::Execute(ref exec) => {
*self.private_tx_queued.lock() += 1;
(*exec.0)(&self.client);
}
_ => {} // ignore other messages

View File

@@ -17,7 +17,6 @@
mod chain;
mod consensus;
pub mod helpers;
mod private;
pub mod snapshot;
#[cfg(feature = "ipc")]

View File

@@ -1,200 +0,0 @@
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity Ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity Ethereum. If not, see <http://www.gnu.org/licenses/>.
use ethcore::{
client::{BlockChainClient, ClientIoMessage},
engines,
executive::contract_address,
miner::{self, MinerService},
spec::Spec,
test_helpers::push_block_with_transactions,
CreateContractAddress,
};
use ethcore_private_tx::{
Importer, NoopEncryptor, Provider, ProviderConfig, SignedPrivateTransaction, StoringKeyProvider,
};
use ethkey::KeyPair;
use hash::keccak;
use io::{IoChannel, IoHandler};
use rlp::Rlp;
use rustc_hex::FromHex;
use std::sync::Arc;
use tests::helpers::{TestIoHandler, TestNet};
use types::{
ids::BlockId,
transaction::{Action, Transaction},
};
use SyncConfig;
fn seal_spec() -> Spec {
let spec_data = include_str!("../res/private_spec.json");
Spec::load(&::std::env::temp_dir(), spec_data.as_bytes()).unwrap()
}
#[test]
fn send_private_transaction() {
// Setup two clients
let s0 = KeyPair::from_secret_slice(&keccak("1")).unwrap();
let s1 = KeyPair::from_secret_slice(&keccak("0")).unwrap();
let signer = Arc::new(ethcore_private_tx::KeyPairSigner(vec![
s0.clone(),
s1.clone(),
]));
let mut net = TestNet::with_spec(2, SyncConfig::default(), seal_spec);
let client0 = net.peer(0).chain.clone();
let client1 = net.peer(1).chain.clone();
let io_handler0: Arc<dyn IoHandler<ClientIoMessage>> =
Arc::new(TestIoHandler::new(net.peer(0).chain.clone()));
let io_handler1: Arc<dyn IoHandler<ClientIoMessage>> =
Arc::new(TestIoHandler::new(net.peer(1).chain.clone()));
net.peer(0)
.miner
.set_author(miner::Author::Sealer(engines::signer::from_keypair(
s0.clone(),
)));
net.peer(1)
.miner
.set_author(miner::Author::Sealer(engines::signer::from_keypair(
s1.clone(),
)));
net.peer(0)
.chain
.engine()
.register_client(Arc::downgrade(&net.peer(0).chain) as _);
net.peer(1)
.chain
.engine()
.register_client(Arc::downgrade(&net.peer(1).chain) as _);
net.peer(0)
.chain
.set_io_channel(IoChannel::to_handler(Arc::downgrade(&io_handler0)));
net.peer(1)
.chain
.set_io_channel(IoChannel::to_handler(Arc::downgrade(&io_handler1)));
let (address, _) = contract_address(
CreateContractAddress::FromSenderAndNonce,
&s0.address(),
&0.into(),
&[],
);
let chain_id = client0.signing_chain_id();
// Exhange statuses
net.sync();
// Setup private providers
let validator_config = ProviderConfig {
validator_accounts: vec![s1.address()],
signer_account: None,
};
let signer_config = ProviderConfig {
validator_accounts: Vec::new(),
signer_account: Some(s0.address()),
};
let private_keys = Arc::new(StoringKeyProvider::default());
let pm0 = Arc::new(Provider::new(
client0.clone(),
net.peer(0).miner.clone(),
signer.clone(),
Box::new(NoopEncryptor::default()),
signer_config,
IoChannel::to_handler(Arc::downgrade(&io_handler0)),
private_keys.clone(),
));
pm0.add_notify(net.peers[0].clone());
let pm1 = Arc::new(Provider::new(
client1.clone(),
net.peer(1).miner.clone(),
signer.clone(),
Box::new(NoopEncryptor::default()),
validator_config,
IoChannel::to_handler(Arc::downgrade(&io_handler1)),
private_keys.clone(),
));
pm1.add_notify(net.peers[1].clone());
// Create and deploy 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(&s0.secret(), None);
let validators = vec![s1.address()];
let (public_tx, _) = pm0
.public_creation_transaction(
BlockId::Latest,
&private_create_tx_signed,
&validators,
0.into(),
)
.unwrap();
let public_tx = public_tx.sign(&s0.secret(), chain_id);
let public_tx_copy = public_tx.clone();
push_block_with_transactions(&client0, &[public_tx]);
push_block_with_transactions(&client1, &[public_tx_copy]);
net.sync();
//Create private transaction for modifying 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(&s0.secret(), None);
assert!(pm0.create_private_transaction(private_tx).is_ok());
//send private transaction message to validator
net.sync();
let validator_handler = net.peer(1).private_tx_handler.clone();
let received_private_transactions = validator_handler.txs.lock().clone();
assert_eq!(received_private_transactions.len(), 1);
//process received private transaction message
let private_transaction = received_private_transactions[0].clone();
assert!(pm1.import_private_transaction(&private_transaction).is_ok());
//send signed response
net.sync();
let sender_handler = net.peer(0).private_tx_handler.clone();
let received_signed_private_transactions = sender_handler.signed_txs.lock().clone();
assert_eq!(received_signed_private_transactions.len(), 1);
//process signed response
let signed_private_transaction = received_signed_private_transactions[0].clone();
assert!(pm0
.import_signed_private_transaction(&signed_private_transaction)
.is_ok());
let signature: SignedPrivateTransaction =
Rlp::new(&signed_private_transaction).as_val().unwrap();
assert!(pm0.process_signature(&signature).is_ok());
let local_transactions = net.peer(0).miner.local_transactions();
assert_eq!(local_transactions.len(), 1);
}