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

Commit

Permalink
Fill transaction hash on ethGetLog of light client. (#9938)
Browse files Browse the repository at this point in the history
* Fill transaction hash on ethGetLog of light client. This is enifficient
but we keep align with spec.

* Using better variables names.

* Expose old fast light get log as `parity_getLogsLight`.

* Update rpc/src/v1/helpers/light_fetch.rs

Fix indent.

Co-Authored-By: cheme <[email protected]>

* Factor common code between light_logs and logs.

* Remove useless check

* Rename parity light logs to 'parity_getLogsNoTransactionHash'.
Fix indent and extra white lines.

* Use vec instead of tree map to avoid inner function.

* better loop
  • Loading branch information
cheme authored and 5chdn committed Jan 9, 2019
1 parent 008bf1b commit 7ccb614
Show file tree
Hide file tree
Showing 5 changed files with 91 additions and 32 deletions.
44 changes: 38 additions & 6 deletions rpc/src/v1/helpers/light_fetch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ use ethereum_types::{U256, Address};
use hash::H256;
use parking_lot::Mutex;
use fastmap::H256FastMap;
use std::collections::BTreeMap;
use transaction::{Action, Transaction as EthTransaction, PendingTransaction, SignedTransaction, LocalizedTransaction};

use v1::helpers::{CallRequest as CallRequestHelper, errors, dispatch};
Expand Down Expand Up @@ -310,9 +311,7 @@ impl LightFetch {
}))
}

/// Get transaction logs
pub fn logs(&self, filter: EthcoreFilter) -> impl Future<Item = Vec<Log>, Error = Error> + Send {
use std::collections::BTreeMap;
pub fn logs_no_tx_hash(&self, filter: EthcoreFilter) -> impl Future<Item = Vec<Log>, Error = Error> + Send {
use jsonrpc_core::futures::stream::{self, Stream};

const MAX_BLOCK_RANGE: u64 = 1000;
Expand Down Expand Up @@ -343,7 +342,7 @@ impl LightFetch {
// insert them into a BTreeMap to maintain order by number and block index.
stream::futures_unordered(receipts_futures)
.fold(BTreeMap::new(), move |mut matches, (num, hash, receipts)| {
let mut block_index = 0;
let mut block_index: usize = 0;
for (transaction_index, receipt) in receipts.into_iter().enumerate() {
for (transaction_log_index, log) in receipt.logs.into_iter().enumerate() {
if filter.matches(&log) {
Expand All @@ -366,9 +365,9 @@ impl LightFetch {
}
}
future::ok::<_,OnDemandError>(matches)
}) // and then collect them into a vector.
.map(|matches| matches.into_iter().map(|(_, v)| v).collect())
})
.map_err(errors::on_demand_error)
.map(|matches| matches.into_iter().map(|(_, v)| v).collect())
});

match maybe_future {
Expand All @@ -378,6 +377,39 @@ impl LightFetch {
})
}


/// Get transaction logs
pub fn logs(&self, filter: EthcoreFilter) -> impl Future<Item = Vec<Log>, Error = Error> + Send {
use jsonrpc_core::futures::stream::{self, Stream};
let fetcher_block = self.clone();
self.logs_no_tx_hash(filter)
// retrieve transaction hash.
.and_then(move |mut result| {
let mut blocks = BTreeMap::new();
for log in result.iter() {
let block_hash = log.block_hash.as_ref().expect("Previously initialized with value; qed");
blocks.entry(block_hash.clone()).or_insert_with(|| {
fetcher_block.block(BlockId::Hash(block_hash.clone().into()))
});
}
// future get blocks (unordered it)
stream::futures_unordered(blocks.into_iter().map(|(_, v)| v)).collect().map(move |blocks| {
let transactions_per_block: BTreeMap<_, _> = blocks.iter()
.map(|block| (block.hash(), block.transactions())).collect();
for log in result.iter_mut() {
let log_index: U256 = log.transaction_index.expect("Previously initialized with value; qed").into();
let block_hash = log.block_hash.clone().expect("Previously initialized with value; qed").into();
let tx_hash = transactions_per_block.get(&block_hash)
// transaction index is from an enumerate call in log common so not need to check value
.and_then(|txs| txs.get(log_index.as_usize()))
.map(|tr| tr.hash().into());
log.transaction_hash = tx_hash;
}
result
})
})
}

// Get a transaction by hash. also returns the index in the block.
// Only returns transactions in the canonical chain.
pub fn transaction_by_hash(&self, tx_hash: H256)
Expand Down
50 changes: 28 additions & 22 deletions rpc/src/v1/impls/eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,33 @@ enum PendingTransactionId {
Location(PendingOrBlock, usize)
}

pub fn base_logs<C, M, T: StateInfo + 'static> (client: &C, miner: &M, filter: Filter) -> BoxFuture<Vec<Log>> where
C: miner::BlockChainClient + BlockChainClient + StateClient<State=T> + Call<State=T>,
M: MinerService<State=T> {
let include_pending = filter.to_block == Some(BlockNumber::Pending);
let filter: EthcoreFilter = match filter.try_into() {
Ok(value) => value,
Err(err) => return Box::new(future::err(err)),
};
let mut logs = match client.logs(filter.clone()) {
Ok(logs) => logs
.into_iter()
.map(From::from)
.collect::<Vec<Log>>(),
Err(id) => return Box::new(future::err(errors::filter_block_not_found(id))),
};

if include_pending {
let best_block = client.chain_info().best_block_number;
let pending = pending_logs(&*miner, best_block, &filter);
logs.extend(pending);
}

let logs = limit_logs(logs, filter.limit);

Box::new(future::ok(logs))
}

impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> EthClient<C, SN, S, M, EM> where
C: miner::BlockChainClient + BlockChainClient + StateClient<State=T> + Call<State=T> + EngineInfo,
SN: SnapshotService,
Expand Down Expand Up @@ -714,28 +741,7 @@ impl<C, SN: ?Sized, S: ?Sized, M, EM, T: StateInfo + 'static> Eth for EthClient<
}

fn logs(&self, filter: Filter) -> BoxFuture<Vec<Log>> {
let include_pending = filter.to_block == Some(BlockNumber::Pending);
let filter: EthcoreFilter = match filter.try_into() {
Ok(value) => value,
Err(err) => return Box::new(future::err(err)),
};
let mut logs = match self.client.logs(filter.clone()) {
Ok(logs) => logs
.into_iter()
.map(From::from)
.collect::<Vec<Log>>(),
Err(id) => return Box::new(future::err(errors::filter_block_not_found(id))),
};

if include_pending {
let best_block = self.client.chain_info().best_block_number;
let pending = pending_logs(&*self.miner, best_block, &filter);
logs.extend(pending);
}

let logs = limit_logs(logs, filter.limit);

Box::new(future::ok(logs))
base_logs(&*self.client, &*self.miner, filter.into())
}

fn work(&self, no_new_work_timeout: Trailing<u64>) -> Result<Work> {
Expand Down
12 changes: 11 additions & 1 deletion rpc/src/v1/impls/light/parity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use ethcore::account_provider::AccountProvider;
use ethcore_logger::RotatingLogger;

use jsonrpc_core::{Result, BoxFuture};
use jsonrpc_core::futures::Future;
use jsonrpc_core::futures::{future, Future};
use jsonrpc_macros::Trailing;
use v1::helpers::{self, errors, ipfs, SigningQueue, SignerService, NetworkSettings};
use v1::helpers::dispatch::LightDispatcher;
Expand All @@ -42,6 +42,7 @@ use v1::types::{
BlockNumber, LightBlockNumber, ConsensusCapability, VersionInfo,
OperationsInfo, ChainStatus,
AccountInfo, HwAccountInfo, Header, RichHeader, Receipt,
Log, Filter,
};
use Host;

Expand Down Expand Up @@ -414,4 +415,13 @@ impl Parity for ParityClient {
fn submit_work_detail(&self, _nonce: H64, _pow_hash: H256, _mix_hash: H256) -> Result<H256> {
Err(errors::light_unimplemented(None))
}


fn logs_no_tx_hash(&self, filter: Filter) -> BoxFuture<Vec<Log>> {
let filter = match filter.try_into() {
Ok(value) => value,
Err(err) => return Box::new(future::err(err)),
};
Box::new(self.fetcher().logs_no_tx_hash(filter)) as BoxFuture<_>
}
}
8 changes: 7 additions & 1 deletion rpc/src/v1/impls/parity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ use v1::types::{
Peers, Transaction, RpcSettings, Histogram,
TransactionStats, LocalTransactionStatus,
BlockNumber, ConsensusCapability, VersionInfo,
OperationsInfo, ChainStatus,
OperationsInfo, ChainStatus, Log, Filter,
AccountInfo, HwAccountInfo, RichHeader, Receipt,
block_number_to_id
};
Expand Down Expand Up @@ -481,4 +481,10 @@ impl<C, M, U, S> Parity for ParityClient<C, M, U> where
fn submit_work_detail(&self, nonce: H64, pow_hash: H256, mix_hash: H256) -> Result<H256> {
helpers::submit_work_detail(&self.client, &self.miner, nonce, pow_hash, mix_hash)
}

fn logs_no_tx_hash(&self, filter: Filter) -> BoxFuture<Vec<Log>> {
use v1::impls::eth::base_logs;
// only specific impl for lightclient
base_logs(&*self.client, &*self.miner, filter.into())
}
}
9 changes: 7 additions & 2 deletions rpc/src/v1/traits/parity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,12 @@ use std::collections::BTreeMap;

use jsonrpc_core::{BoxFuture, Result};
use jsonrpc_macros::Trailing;

use v1::types::{
H64, H160, H256, H512, U256, Bytes, CallRequest,
Peers, Transaction, RpcSettings, Histogram,
TransactionStats, LocalTransactionStatus,
BlockNumber, ConsensusCapability, VersionInfo,
OperationsInfo, ChainStatus,
OperationsInfo, ChainStatus, Log, Filter,
AccountInfo, HwAccountInfo, RichHeader, Receipt,
};

Expand Down Expand Up @@ -227,5 +226,11 @@ build_rpc_trait! {
/// but returns block hash on success, and returns an explicit error message on failure).
#[rpc(name = "parity_submitWorkDetail")]
fn submit_work_detail(&self, H64, H256, H256) -> Result<H256>;

/// Returns logs matching given filter object.
/// Is allowed to skip filling transaction hash for faster query.
#[rpc(name = "parity_getLogsNoTransactionHash")]
fn logs_no_tx_hash(&self, Filter) -> BoxFuture<Vec<Log>>;

}
}

0 comments on commit 7ccb614

Please sign in to comment.