From: Alekos Filini Date: Fri, 18 Jun 2021 11:13:45 +0000 (+0200) Subject: [verify] Cache txs to avoid multiple db/network lookups X-Git-Tag: v0.9.0~11 X-Git-Url: http://internal-gitweb-vhost/%22https:/parse/scripts/database/-script/-debug/struct.EncoderStringWriter.html?a=commitdiff_plain;h=a67aca32c051f2923a27f955ef8f0f96c70848e3;p=bdk [verify] Cache txs to avoid multiple db/network lookups --- diff --git a/src/wallet/verify.rs b/src/wallet/verify.rs index 34110516..2d5c193c 100644 --- a/src/wallet/verify.rs +++ b/src/wallet/verify.rs @@ -9,6 +9,7 @@ // You may not use this file except in accordance with one or both of these // licenses. +use std::collections::HashMap; use std::fmt; use bitcoin::consensus::serialize; @@ -34,9 +35,12 @@ pub fn verify_tx( log::debug!("Verifying {}", tx.txid()); let serialized_tx = serialize(tx); + let mut tx_cache = HashMap::<_, Transaction>::new(); for (index, input) in tx.input.iter().enumerate() { - let prev_tx = if let Some(prev_tx) = database.get_raw_tx(&input.previous_output.txid)? { + let prev_tx = if let Some(prev_tx) = tx_cache.get(&input.previous_output.txid) { + prev_tx.clone() + } else if let Some(prev_tx) = database.get_raw_tx(&input.previous_output.txid)? { prev_tx } else if let Some(prev_tx) = blockchain.get_tx(&input.previous_output.txid)? { prev_tx @@ -55,6 +59,10 @@ pub fn verify_tx( &serialized_tx, index, )?; + + // Since we have a local cache we might as well cache stuff from the db, as it will very + // likely decrease latency compared to reading from disk or performing an SQL query. + tx_cache.insert(prev_tx.txid(), prev_tx); } Ok(())