From 64f18bce18fca78258b04da75b11a9fa6d807f4e Mon Sep 17 00:00:00 2001 From: Matt Whitlock Date: Sat, 4 Nov 2023 17:01:09 -0400 Subject: [PATCH] get_imported_privkey_branch: use O(m+n) algorithm instead of O(m*n) The algorithm in get_imported_privkey_branch was O(m*n): for each imported path, it was iterating over the entire set of UTXOs. Rewrite the algorithm to make one pass over the set of UTXOs up front to compute the balance of each script (O(m)) and then, separately, one pass over the set of imported paths to pluck out the balance for each path (O(n)). --- src/jmclient/wallet_utils.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/jmclient/wallet_utils.py b/src/jmclient/wallet_utils.py index c1165ff..786637f 100644 --- a/src/jmclient/wallet_utils.py +++ b/src/jmclient/wallet_utils.py @@ -7,7 +7,7 @@ import sys from datetime import datetime, timedelta from optparse import OptionParser from numbers import Integral -from collections import Counter +from collections import Counter, defaultdict from itertools import islice, chain from jmclient import (get_network, WALLET_IMPLEMENTATIONS, Storage, podle, jm_single, WalletError, BaseWallet, VolatileStorage, @@ -403,15 +403,15 @@ def get_tx_info(txid, tx_cache=None): def get_imported_privkey_branch(wallet_service, m, showprivkey): entries = [] + balance_by_script = defaultdict(int) + for data in wallet_service.get_utxos_at_mixdepth(m, + include_disabled=True).values(): + balance_by_script[data['script']] += data['value'] for path in wallet_service.yield_imported_paths(m): addr = wallet_service.get_address_from_path(path) script = wallet_service.get_script_from_path(path) - balance = 0.0 - for data in wallet_service.get_utxos_at_mixdepth(m, - include_disabled=True).values(): - if script == data['script']: - balance += data['value'] - status = ('used' if balance > 0.0 else 'empty') + balance = balance_by_script.get(script, 0) + status = ('used' if balance else 'empty') if showprivkey: wip_privkey = wallet_service.get_wif_path(path) else: