From 61f58173cba7cf297b609f894a7711cd9a6b2efb Mon Sep 17 00:00:00 2001 From: CalDescent Date: Wed, 9 Feb 2022 19:46:20 +0000 Subject: [PATCH] Revert "Removed transaction caching. Can be reintroduced later." This reverts commit 9804eccbf0aa1b5051afdf2e18d7b0554f931a71. --- .../java/org/qortal/crosschain/Bitcoiny.java | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/qortal/crosschain/Bitcoiny.java b/src/main/java/org/qortal/crosschain/Bitcoiny.java index bf5bd230..2678a08e 100644 --- a/src/main/java/org/qortal/crosschain/Bitcoiny.java +++ b/src/main/java/org/qortal/crosschain/Bitcoiny.java @@ -33,6 +33,7 @@ import org.qortal.utils.Amounts; import org.qortal.utils.BitTwiddling; import com.google.common.hash.HashCode; +import org.qortal.utils.NTP; /** Bitcoin-like (Bitcoin, Litecoin, etc.) support */ public abstract class Bitcoiny implements ForeignBlockchain { @@ -47,6 +48,12 @@ public abstract class Bitcoiny implements ForeignBlockchain { protected final NetworkParameters params; + /** Cache recent transactions to speed up subsequent lookups */ + protected List transactionsCache; + protected Long transactionsCacheTimestamp; + protected String transactionsCacheXpub; + protected static long TRANSACTIONS_CACHE_TIMEOUT = 2 * 60 * 1000L; // 2 minutes + /** Keys that have been previously marked as fully spent,
* i.e. keys with transactions but with no unspent outputs. */ protected final Set spentKeys = Collections.synchronizedSet(new HashSet<>()); @@ -343,6 +350,17 @@ public abstract class Bitcoiny implements ForeignBlockchain { public List getWalletTransactions(String key58) throws ForeignBlockchainException { synchronized (this) { + // Serve from the cache if it's recent, and matches this xpub + if (Objects.equals(transactionsCacheXpub, key58)) { + if (transactionsCache != null && transactionsCacheTimestamp != null) { + Long now = NTP.getTime(); + boolean isCacheStale = (now != null && now - transactionsCacheTimestamp >= TRANSACTIONS_CACHE_TIMEOUT); + if (!isCacheStale) { + return transactionsCache; + } + } + } + Context.propagate(bitcoinjContext); Wallet wallet = walletFromDeterministicKey58(key58); @@ -405,9 +423,13 @@ public abstract class Bitcoiny implements ForeignBlockchain { Comparator newestTimestampFirstComparator = Comparator.comparingInt(SimpleTransaction::getTimestamp).reversed(); // Update cache and return - return walletTransactions.stream() + transactionsCacheTimestamp = NTP.getTime(); + transactionsCacheXpub = key58; + transactionsCache = walletTransactions.stream() .map(t -> convertToSimpleTransaction(t, keySet)) .sorted(newestTimestampFirstComparator).collect(Collectors.toList()); + + return transactionsCache; } }