From d5f4c4cf52f7bd6ed5d773155878149ca40874e6 Mon Sep 17 00:00:00 2001 From: Mononaut Date: Thu, 25 Jan 2024 19:46:50 +0000 Subject: [PATCH] Add chunked mempool txids endpoint --- src/new_index/mempool.rs | 25 +++++++++++++++++++++++++ src/rest.rs | 6 ++++++ 2 files changed, 31 insertions(+) diff --git a/src/new_index/mempool.rs b/src/new_index/mempool.rs index ccd50fe1..931dc9d9 100644 --- a/src/new_index/mempool.rs +++ b/src/new_index/mempool.rs @@ -1,3 +1,4 @@ +use bitcoin::hashes::Hash; use bounded_vec_deque::BoundedVecDeque; use itertools::Itertools; @@ -288,6 +289,30 @@ impl Mempool { self.txstore.keys().collect() } + // Get all txids in the mempool with the given prefix + pub fn txids_by_prefix(&self, prefix: &str) -> Result> { + let _timer = self + .latency + .with_label_values(&["txids_by_prefix"]) + .start_timer(); + + // get Txid range bounds for the given prefix + let start_bytes = + hex::decode(format!("{:0<64}", prefix)).chain_err(|| "invalid hash prefix")?; + let end_bytes = + hex::decode(format!("{:f<64}", prefix)).chain_err(|| "invalid hash prefix")?; + let start_txid = + Txid::from_hash(Hash::from_slice(&start_bytes).chain_err(|| "invalid hash prefix")?); + let end_txid = + Txid::from_hash(Hash::from_slice(&end_bytes).chain_err(|| "invalid hash prefix")?); + + Ok(self + .txstore + .range(start_txid..=end_txid) + .map(|(k, _v)| k) + .collect()) + } + // Get all txs in the mempool pub fn txs(&self) -> Vec { let _timer = self.latency.with_label_values(&["txs"]).start_timer(); diff --git a/src/rest.rs b/src/rest.rs index 375d351a..035a315f 100644 --- a/src/rest.rs +++ b/src/rest.rs @@ -1256,6 +1256,12 @@ fn handle_request( (&Method::GET, Some(&"mempool"), Some(&"txids"), None, None, None) => { json_response(query.mempool().txids(), TTL_SHORT) } + (&Method::GET, Some(&"mempool"), Some(&"txids"), Some(prefix), None, None) => { + match query.mempool().txids_by_prefix(prefix) { + Ok(txids) => json_response(txids, TTL_SHORT), + Err(err) => http_message(StatusCode::BAD_REQUEST, err.to_string(), 0), + } + } ( &Method::GET, Some(&INTERNAL_PREFIX),