From fc5d6ada36705f6e1120cbbbdf4d4e1c821f54ba Mon Sep 17 00:00:00 2001 From: Craig Raw Date: Thu, 29 Jul 2021 11:09:49 +0200 Subject: [PATCH] add caching for verbose transaction lookups to avoid repeat server requests --- .../sparrow/net/ElectrumServer.java | 29 +++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/sparrowwallet/sparrow/net/ElectrumServer.java b/src/main/java/com/sparrowwallet/sparrow/net/ElectrumServer.java index cb7a6195..e79b0c91 100644 --- a/src/main/java/com/sparrowwallet/sparrow/net/ElectrumServer.java +++ b/src/main/java/com/sparrowwallet/sparrow/net/ElectrumServer.java @@ -50,6 +50,8 @@ public class ElectrumServer { private static Map retrievedScriptHashes = Collections.synchronizedMap(new HashMap<>()); + private static Map retrievedTransactions = Collections.synchronizedMap(new HashMap<>()); + private static ElectrumServerRpc electrumServerRpc = new SimpleElectrumServerRpc(); private static String bwtElectrumServer; @@ -93,6 +95,7 @@ public class ElectrumServer { //If changing server, don't rely on previous transaction history if(previousServerAddress != null && !electrumServer.equals(previousServerAddress)) { retrievedScriptHashes.clear(); + retrievedTransactions.clear(); } previousServerAddress = electrumServer; @@ -1229,8 +1232,30 @@ public class ElectrumServer { protected Task> createTask() { return new Task<>() { protected Map call() throws ServerException { - ElectrumServer electrumServer = new ElectrumServer(); - return electrumServer.getReferencedTransactions(references, scriptHash); + Map transactionMap = new HashMap<>(); + for(Sha256Hash ref : references) { + if(retrievedTransactions.get(ref) != null) { + transactionMap.put(ref, retrievedTransactions.get(ref)); + } + } + + Set fetchReferences = new HashSet<>(references); + fetchReferences.removeAll(transactionMap.keySet()); + + if(!fetchReferences.isEmpty()) { + ElectrumServer electrumServer = new ElectrumServer(); + Map fetchedTransactions = electrumServer.getReferencedTransactions(fetchReferences, scriptHash); + transactionMap.putAll(fetchedTransactions); + + for(Map.Entry fetchedEntry : fetchedTransactions.entrySet()) { + if(fetchedEntry.getValue() != null && !Sha256Hash.ZERO_HASH.equals(fetchedEntry.getValue().getBlockHash()) && + AppServices.getCurrentBlockHeight() != null && fetchedEntry.getValue().getConfirmations(AppServices.getCurrentBlockHeight()) >= BlockTransactionHash.BLOCKS_TO_CONFIRM) { + retrievedTransactions.put(fetchedEntry.getKey(), fetchedEntry.getValue()); + } + } + } + + return transactionMap; } }; }