From e0939348c3e5d1aac24a1d53931b5fd26ebd35cc Mon Sep 17 00:00:00 2001
From: ThomasV <thomasv@gitorious>
Date: Sat, 15 Aug 2015 12:31:57 +0200
Subject: [PATCH] minimize calls to estimated_fee

---
 lib/wallet.py | 19 ++++++++++++++++---
 1 file changed, 16 insertions(+), 3 deletions(-)

diff --git a/lib/wallet.py b/lib/wallet.py
index b32774c1a..5de73b88a 100644
--- a/lib/wallet.py
+++ b/lib/wallet.py
@@ -878,6 +878,7 @@ class Abstract_Wallet(object):
         # this method can be overloaded
         return tx.get_fee()
 
+    @profiler
     def estimated_fee(self, tx, fee_per_kb):
         estimated_size = len(tx.serialize(-1))/2
         fee = int(fee_per_kb * estimated_size / 1000.)
@@ -897,7 +898,7 @@ class Abstract_Wallet(object):
         inputs = []
         tx = Transaction.from_io(inputs, outputs)
         fee = fixed_fee if fixed_fee is not None else 0
-        # add old inputs first
+        # add inputs, sorted by age
         for item in coins:
             v = item.get('value')
             total += v
@@ -911,15 +912,27 @@ class Abstract_Wallet(object):
                 break
         else:
             raise NotEnoughFunds()
-        # remove unneeded inputs
+        # remove unneeded inputs.
+        removed = False
         for item in sorted(tx.inputs, key=itemgetter('value')):
             v = item.get('value')
             if total - v >= amount + fee:
                 tx.inputs.remove(item)
                 total -= v
-                fee = fixed_fee if fixed_fee is not None else self.estimated_fee(tx, fee_per_kb)
+                removed = True
+                continue
             else:
                 break
+        if removed:
+            fee = fixed_fee if fixed_fee is not None else self.estimated_fee(tx, fee_per_kb)
+            for item in sorted(tx.inputs, key=itemgetter('value')):
+                v = item.get('value')
+                if total - v >= amount + fee:
+                    tx.inputs.remove(item)
+                    total -= v
+                    fee = fixed_fee if fixed_fee is not None else self.estimated_fee(tx, fee_per_kb)
+                    continue
+                break
         print_error("using %d inputs"%len(tx.inputs))
 
         # change address