From cc3571e2ba29a9b8dd790ae8457794d92f93b8f5 Mon Sep 17 00:00:00 2001
From: backpacker69 <backpacker69@protonmail.com>
Date: Thu, 19 Oct 2023 15:22:50 +1100
Subject: [PATCH] optimizeutxoset fixes

---
 src/wallet/rpc/spend.cpp | 13 +++++--------
 1 file changed, 5 insertions(+), 8 deletions(-)

diff --git a/src/wallet/rpc/spend.cpp b/src/wallet/rpc/spend.cpp
index d2d84b710f..21528af273 100644
--- a/src/wallet/rpc/spend.cpp
+++ b/src/wallet/rpc/spend.cpp
@@ -392,18 +392,15 @@ RPCHelpMan optimizeutxoset()
             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Blackcoin address: ") + request.params[3].get_str());
         }
 
-        auto available_coins = AvailableCoins(*pwallet, &coin_control);
-        std::vector<COutput> coins = available_coins.All();
-        for (const COutput& out : coins) {
-            ExtractDestination(out.txout.scriptPubKey, tmpAddress);
-            if (tmpAddress == fromAddress) {
-                if (tmpAddress == dest && out.txout.nValue == amount)
-                    continue;
+        std::vector<COutput> vAvailableCoins = AvailableCoins(*pwallet, &coin_control).All();
+        for (const COutput& out : vAvailableCoins) {
+            const CScript& scriptPubKey = out.txout.scriptPubKey;
+            bool fValidAddress = ExtractDestination(scriptPubKey, tmpAddress);
+            if (fValidAddress && (tmpAddress == fromAddress)) {
                 coin_control.Select(out.outpoint);
                 availableCoins += out.txout.nValue;
             }
         }
-
         coin_control.m_allow_other_inputs = false;
     } else {
         const auto bal = GetBalance(*pwallet);