perf(rpc): fetch range of blocks and return empty if unchanged (#4592)

This commit is contained in:
Matthias Seitz
2023-09-18 16:10:32 +02:00
committed by GitHub
parent 66589209a0
commit 93ccf41550
2 changed files with 21 additions and 10 deletions

View File

@ -71,13 +71,20 @@ where
let info = self.inner.provider.chain_info()?;
let best_number = info.best_number;
// start_block is the block from which we should start fetching changes, the next block from
// the last time changes were polled, in other words the best block at last poll + 1
let (start_block, kind) = {
let mut filters = self.inner.active_filters.inner.lock().await;
let filter = filters.get_mut(&id).ok_or(FilterError::FilterNotFound(id))?;
if filter.block > best_number {
// no new blocks since the last poll
return Ok(FilterChanges::Empty)
}
// update filter
// we fetch all changes from [filter.block..best_block], so we advance the filter's
// block to `best_block +1`
// block to `best_block +1`, the next from which we should start fetching changes again
let mut block = best_number + 1;
std::mem::swap(&mut filter.block, &mut block);
filter.last_poll_timestamp = Instant::now();
@ -90,15 +97,14 @@ where
Err(EthApiError::Unsupported("pending transaction filter not supported").into())
}
FilterKind::Block => {
let mut block_hashes = Vec::new();
for block_num in start_block..best_number {
let block_hash = self
.inner
.provider
.block_hash(block_num)?
.ok_or(EthApiError::UnknownBlockNumber)?;
block_hashes.push(block_hash);
}
// Note: we need to fetch the block hashes from inclusive range
// [start_block..best_block]
let end_block = best_number + 1;
let block_hashes = self
.inner
.provider
.canonical_hashes_range(start_block, end_block)
.map_err(|_| EthApiError::UnknownBlockNumber)?;
Ok(FilterChanges::Hashes(block_hashes))
}
FilterKind::Log(filter) => {
@ -117,6 +123,7 @@ where
FilterBlockOption::AtBlockHash(_) => {
// blockHash is equivalent to fromBlock = toBlock = the block number with
// hash blockHash
// get_logs_in_block_range is inclusive
(start_block, best_number)
}
};

View File

@ -19,5 +19,9 @@ pub trait BlockHashReader: Send + Sync {
}
/// Get headers in range of block hashes or numbers
///
/// Returns the available hashes of that range.
///
/// Note: The range is `start..end`, so the expected result is `[start..end)`
fn canonical_hashes_range(&self, start: BlockNumber, end: BlockNumber) -> Result<Vec<H256>>;
}