]> Git Repo - VerusCoin.git/blob - src/wallet.cpp
Merge pull request #5481
[VerusCoin.git] / src / wallet.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #include "wallet.h"
7
8 #include "base58.h"
9 #include "checkpoints.h"
10 #include "coincontrol.h"
11 #include "net.h"
12 #include "script/script.h"
13 #include "script/sign.h"
14 #include "timedata.h"
15 #include "util.h"
16 #include "utilmoneystr.h"
17
18 #include <assert.h>
19
20 #include <boost/algorithm/string/replace.hpp>
21 #include <boost/thread.hpp>
22
23 using namespace std;
24
25 /**
26  * Settings
27  */
28 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
29 CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE;
30 unsigned int nTxConfirmTarget = 1;
31 bool bSpendZeroConfChange = true;
32 bool fSendFreeTransactions = false;
33 bool fPayAtLeastCustomFee = true;
34
35 /** 
36  * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) 
37  * Override with -mintxfee
38  */
39 CFeeRate CWallet::minTxFee = CFeeRate(1000);
40
41 /** @defgroup mapWallet
42  *
43  * @{
44  */
45
46 struct CompareValueOnly
47 {
48     bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
49                     const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
50     {
51         return t1.first < t2.first;
52     }
53 };
54
55 std::string COutput::ToString() const
56 {
57     return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
58 }
59
60 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
61 {
62     LOCK(cs_wallet);
63     std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
64     if (it == mapWallet.end())
65         return NULL;
66     return &(it->second);
67 }
68
69 CPubKey CWallet::GenerateNewKey()
70 {
71     AssertLockHeld(cs_wallet); // mapKeyMetadata
72     bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
73
74     RandAddSeedPerfmon();
75     CKey secret;
76     secret.MakeNewKey(fCompressed);
77
78     // Compressed public keys were introduced in version 0.6.0
79     if (fCompressed)
80         SetMinVersion(FEATURE_COMPRPUBKEY);
81
82     CPubKey pubkey = secret.GetPubKey();
83     assert(secret.VerifyPubKey(pubkey));
84
85     // Create new metadata
86     int64_t nCreationTime = GetTime();
87     mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
88     if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
89         nTimeFirstKey = nCreationTime;
90
91     if (!AddKeyPubKey(secret, pubkey))
92         throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
93     return pubkey;
94 }
95
96 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
97 {
98     AssertLockHeld(cs_wallet); // mapKeyMetadata
99     if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
100         return false;
101
102     // check if we need to remove from watch-only
103     CScript script;
104     script = GetScriptForDestination(pubkey.GetID());
105     if (HaveWatchOnly(script))
106         RemoveWatchOnly(script);
107
108     if (!fFileBacked)
109         return true;
110     if (!IsCrypted()) {
111         return CWalletDB(strWalletFile).WriteKey(pubkey,
112                                                  secret.GetPrivKey(),
113                                                  mapKeyMetadata[pubkey.GetID()]);
114     }
115     return true;
116 }
117
118 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
119                             const vector<unsigned char> &vchCryptedSecret)
120 {
121     if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
122         return false;
123     if (!fFileBacked)
124         return true;
125     {
126         LOCK(cs_wallet);
127         if (pwalletdbEncryption)
128             return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
129                                                         vchCryptedSecret,
130                                                         mapKeyMetadata[vchPubKey.GetID()]);
131         else
132             return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
133                                                             vchCryptedSecret,
134                                                             mapKeyMetadata[vchPubKey.GetID()]);
135     }
136     return false;
137 }
138
139 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
140 {
141     AssertLockHeld(cs_wallet); // mapKeyMetadata
142     if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
143         nTimeFirstKey = meta.nCreateTime;
144
145     mapKeyMetadata[pubkey.GetID()] = meta;
146     return true;
147 }
148
149 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
150 {
151     return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
152 }
153
154 bool CWallet::AddCScript(const CScript& redeemScript)
155 {
156     if (!CCryptoKeyStore::AddCScript(redeemScript))
157         return false;
158     if (!fFileBacked)
159         return true;
160     return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
161 }
162
163 bool CWallet::LoadCScript(const CScript& redeemScript)
164 {
165     /* A sanity check was added in pull #3843 to avoid adding redeemScripts
166      * that never can be redeemed. However, old wallets may still contain
167      * these. Do not add them to the wallet and warn. */
168     if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
169     {
170         std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
171         LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
172             __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
173         return true;
174     }
175
176     return CCryptoKeyStore::AddCScript(redeemScript);
177 }
178
179 bool CWallet::AddWatchOnly(const CScript &dest)
180 {
181     if (!CCryptoKeyStore::AddWatchOnly(dest))
182         return false;
183     nTimeFirstKey = 1; // No birthday information for watch-only keys.
184     NotifyWatchonlyChanged(true);
185     if (!fFileBacked)
186         return true;
187     return CWalletDB(strWalletFile).WriteWatchOnly(dest);
188 }
189
190 bool CWallet::RemoveWatchOnly(const CScript &dest)
191 {
192     AssertLockHeld(cs_wallet);
193     if (!CCryptoKeyStore::RemoveWatchOnly(dest))
194         return false;
195     if (!HaveWatchOnly())
196         NotifyWatchonlyChanged(false);
197     if (fFileBacked)
198         if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
199             return false;
200
201     return true;
202 }
203
204 bool CWallet::LoadWatchOnly(const CScript &dest)
205 {
206     return CCryptoKeyStore::AddWatchOnly(dest);
207 }
208
209 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
210 {
211     CCrypter crypter;
212     CKeyingMaterial vMasterKey;
213
214     {
215         LOCK(cs_wallet);
216         BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
217         {
218             if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
219                 return false;
220             if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
221                 continue; // try another master key
222             if (CCryptoKeyStore::Unlock(vMasterKey))
223                 return true;
224         }
225     }
226     return false;
227 }
228
229 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
230 {
231     bool fWasLocked = IsLocked();
232
233     {
234         LOCK(cs_wallet);
235         Lock();
236
237         CCrypter crypter;
238         CKeyingMaterial vMasterKey;
239         BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
240         {
241             if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
242                 return false;
243             if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
244                 return false;
245             if (CCryptoKeyStore::Unlock(vMasterKey))
246             {
247                 int64_t nStartTime = GetTimeMillis();
248                 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
249                 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
250
251                 nStartTime = GetTimeMillis();
252                 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
253                 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
254
255                 if (pMasterKey.second.nDeriveIterations < 25000)
256                     pMasterKey.second.nDeriveIterations = 25000;
257
258                 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
259
260                 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
261                     return false;
262                 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
263                     return false;
264                 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
265                 if (fWasLocked)
266                     Lock();
267                 return true;
268             }
269         }
270     }
271
272     return false;
273 }
274
275 void CWallet::SetBestChain(const CBlockLocator& loc)
276 {
277     CWalletDB walletdb(strWalletFile);
278     walletdb.WriteBestBlock(loc);
279 }
280
281 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
282 {
283     LOCK(cs_wallet); // nWalletVersion
284     if (nWalletVersion >= nVersion)
285         return true;
286
287     // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
288     if (fExplicit && nVersion > nWalletMaxVersion)
289             nVersion = FEATURE_LATEST;
290
291     nWalletVersion = nVersion;
292
293     if (nVersion > nWalletMaxVersion)
294         nWalletMaxVersion = nVersion;
295
296     if (fFileBacked)
297     {
298         CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
299         if (nWalletVersion > 40000)
300             pwalletdb->WriteMinVersion(nWalletVersion);
301         if (!pwalletdbIn)
302             delete pwalletdb;
303     }
304
305     return true;
306 }
307
308 bool CWallet::SetMaxVersion(int nVersion)
309 {
310     LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
311     // cannot downgrade below current version
312     if (nWalletVersion > nVersion)
313         return false;
314
315     nWalletMaxVersion = nVersion;
316
317     return true;
318 }
319
320 set<uint256> CWallet::GetConflicts(const uint256& txid) const
321 {
322     set<uint256> result;
323     AssertLockHeld(cs_wallet);
324
325     std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
326     if (it == mapWallet.end())
327         return result;
328     const CWalletTx& wtx = it->second;
329
330     std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
331
332     BOOST_FOREACH(const CTxIn& txin, wtx.vin)
333     {
334         if (mapTxSpends.count(txin.prevout) <= 1)
335             continue;  // No conflict if zero or one spends
336         range = mapTxSpends.equal_range(txin.prevout);
337         for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
338             result.insert(it->second);
339     }
340     return result;
341 }
342
343 void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range)
344 {
345     // We want all the wallet transactions in range to have the same metadata as
346     // the oldest (smallest nOrderPos).
347     // So: find smallest nOrderPos:
348
349     int nMinOrderPos = std::numeric_limits<int>::max();
350     const CWalletTx* copyFrom = NULL;
351     for (TxSpends::iterator it = range.first; it != range.second; ++it)
352     {
353         const uint256& hash = it->second;
354         int n = mapWallet[hash].nOrderPos;
355         if (n < nMinOrderPos)
356         {
357             nMinOrderPos = n;
358             copyFrom = &mapWallet[hash];
359         }
360     }
361     // Now copy data from copyFrom to rest:
362     for (TxSpends::iterator it = range.first; it != range.second; ++it)
363     {
364         const uint256& hash = it->second;
365         CWalletTx* copyTo = &mapWallet[hash];
366         if (copyFrom == copyTo) continue;
367         copyTo->mapValue = copyFrom->mapValue;
368         copyTo->vOrderForm = copyFrom->vOrderForm;
369         // fTimeReceivedIsTxTime not copied on purpose
370         // nTimeReceived not copied on purpose
371         copyTo->nTimeSmart = copyFrom->nTimeSmart;
372         copyTo->fFromMe = copyFrom->fFromMe;
373         copyTo->strFromAccount = copyFrom->strFromAccount;
374         // nOrderPos not copied on purpose
375         // cached members not copied on purpose
376     }
377 }
378
379 /**
380  * Outpoint is spent if any non-conflicted transaction
381  * spends it:
382  */
383 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
384 {
385     const COutPoint outpoint(hash, n);
386     pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
387     range = mapTxSpends.equal_range(outpoint);
388
389     for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
390     {
391         const uint256& wtxid = it->second;
392         std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
393         if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0)
394             return true; // Spent
395     }
396     return false;
397 }
398
399 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
400 {
401     mapTxSpends.insert(make_pair(outpoint, wtxid));
402
403     pair<TxSpends::iterator, TxSpends::iterator> range;
404     range = mapTxSpends.equal_range(outpoint);
405     SyncMetaData(range);
406 }
407
408
409 void CWallet::AddToSpends(const uint256& wtxid)
410 {
411     assert(mapWallet.count(wtxid));
412     CWalletTx& thisTx = mapWallet[wtxid];
413     if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
414         return;
415
416     BOOST_FOREACH(const CTxIn& txin, thisTx.vin)
417         AddToSpends(txin.prevout, wtxid);
418 }
419
420 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
421 {
422     if (IsCrypted())
423         return false;
424
425     CKeyingMaterial vMasterKey;
426     RandAddSeedPerfmon();
427
428     vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
429     GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
430
431     CMasterKey kMasterKey;
432     RandAddSeedPerfmon();
433
434     kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
435     GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
436
437     CCrypter crypter;
438     int64_t nStartTime = GetTimeMillis();
439     crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
440     kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
441
442     nStartTime = GetTimeMillis();
443     crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
444     kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
445
446     if (kMasterKey.nDeriveIterations < 25000)
447         kMasterKey.nDeriveIterations = 25000;
448
449     LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
450
451     if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
452         return false;
453     if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
454         return false;
455
456     {
457         LOCK(cs_wallet);
458         mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
459         if (fFileBacked)
460         {
461             assert(!pwalletdbEncryption);
462             pwalletdbEncryption = new CWalletDB(strWalletFile);
463             if (!pwalletdbEncryption->TxnBegin()) {
464                 delete pwalletdbEncryption;
465                 pwalletdbEncryption = NULL;
466                 return false;
467             }
468             pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
469         }
470
471         if (!EncryptKeys(vMasterKey))
472         {
473             if (fFileBacked) {
474                 pwalletdbEncryption->TxnAbort();
475                 delete pwalletdbEncryption;
476             }
477             // We now probably have half of our keys encrypted in memory, and half not...
478             // die and let the user reload their unencrypted wallet.
479             assert(false);
480         }
481
482         // Encryption was introduced in version 0.4.0
483         SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
484
485         if (fFileBacked)
486         {
487             if (!pwalletdbEncryption->TxnCommit()) {
488                 delete pwalletdbEncryption;
489                 // We now have keys encrypted in memory, but not on disk...
490                 // die to avoid confusion and let the user reload their unencrypted wallet.
491                 assert(false);
492             }
493
494             delete pwalletdbEncryption;
495             pwalletdbEncryption = NULL;
496         }
497
498         Lock();
499         Unlock(strWalletPassphrase);
500         NewKeyPool();
501         Lock();
502
503         // Need to completely rewrite the wallet file; if we don't, bdb might keep
504         // bits of the unencrypted private key in slack space in the database file.
505         CDB::Rewrite(strWalletFile);
506
507     }
508     NotifyStatusChanged(this);
509
510     return true;
511 }
512
513 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
514 {
515     AssertLockHeld(cs_wallet); // nOrderPosNext
516     int64_t nRet = nOrderPosNext++;
517     if (pwalletdb) {
518         pwalletdb->WriteOrderPosNext(nOrderPosNext);
519     } else {
520         CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
521     }
522     return nRet;
523 }
524
525 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
526 {
527     AssertLockHeld(cs_wallet); // mapWallet
528     CWalletDB walletdb(strWalletFile);
529
530     // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
531     TxItems txOrdered;
532
533     // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
534     // would make this much faster for applications that do this a lot.
535     for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
536     {
537         CWalletTx* wtx = &((*it).second);
538         txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
539     }
540     acentries.clear();
541     walletdb.ListAccountCreditDebit(strAccount, acentries);
542     BOOST_FOREACH(CAccountingEntry& entry, acentries)
543     {
544         txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
545     }
546
547     return txOrdered;
548 }
549
550 void CWallet::MarkDirty()
551 {
552     {
553         LOCK(cs_wallet);
554         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
555             item.second.MarkDirty();
556     }
557 }
558
559 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet)
560 {
561     uint256 hash = wtxIn.GetHash();
562
563     if (fFromLoadWallet)
564     {
565         mapWallet[hash] = wtxIn;
566         mapWallet[hash].BindWallet(this);
567         AddToSpends(hash);
568     }
569     else
570     {
571         LOCK(cs_wallet);
572         // Inserts only if not already there, returns tx inserted or tx found
573         pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
574         CWalletTx& wtx = (*ret.first).second;
575         wtx.BindWallet(this);
576         bool fInsertedNew = ret.second;
577         if (fInsertedNew)
578         {
579             wtx.nTimeReceived = GetAdjustedTime();
580             wtx.nOrderPos = IncOrderPosNext();
581
582             wtx.nTimeSmart = wtx.nTimeReceived;
583             if (wtxIn.hashBlock != 0)
584             {
585                 if (mapBlockIndex.count(wtxIn.hashBlock))
586                 {
587                     int64_t latestNow = wtx.nTimeReceived;
588                     int64_t latestEntry = 0;
589                     {
590                         // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
591                         int64_t latestTolerated = latestNow + 300;
592                         std::list<CAccountingEntry> acentries;
593                         TxItems txOrdered = OrderedTxItems(acentries);
594                         for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
595                         {
596                             CWalletTx *const pwtx = (*it).second.first;
597                             if (pwtx == &wtx)
598                                 continue;
599                             CAccountingEntry *const pacentry = (*it).second.second;
600                             int64_t nSmartTime;
601                             if (pwtx)
602                             {
603                                 nSmartTime = pwtx->nTimeSmart;
604                                 if (!nSmartTime)
605                                     nSmartTime = pwtx->nTimeReceived;
606                             }
607                             else
608                                 nSmartTime = pacentry->nTime;
609                             if (nSmartTime <= latestTolerated)
610                             {
611                                 latestEntry = nSmartTime;
612                                 if (nSmartTime > latestNow)
613                                     latestNow = nSmartTime;
614                                 break;
615                             }
616                         }
617                     }
618
619                     int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
620                     wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
621                 }
622                 else
623                     LogPrintf("AddToWallet() : found %s in block %s not in index\n",
624                              wtxIn.GetHash().ToString(),
625                              wtxIn.hashBlock.ToString());
626             }
627             AddToSpends(hash);
628         }
629
630         bool fUpdated = false;
631         if (!fInsertedNew)
632         {
633             // Merge
634             if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
635             {
636                 wtx.hashBlock = wtxIn.hashBlock;
637                 fUpdated = true;
638             }
639             if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
640             {
641                 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
642                 wtx.nIndex = wtxIn.nIndex;
643                 fUpdated = true;
644             }
645             if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
646             {
647                 wtx.fFromMe = wtxIn.fFromMe;
648                 fUpdated = true;
649             }
650         }
651
652         //// debug print
653         LogPrintf("AddToWallet %s  %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
654
655         // Write to disk
656         if (fInsertedNew || fUpdated)
657             if (!wtx.WriteToDisk())
658                 return false;
659
660         // Break debit/credit balance caches:
661         wtx.MarkDirty();
662
663         // Notify UI of new or updated transaction
664         NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
665
666         // notify an external script when a wallet transaction comes in or is updated
667         std::string strCmd = GetArg("-walletnotify", "");
668
669         if ( !strCmd.empty())
670         {
671             boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
672             boost::thread t(runCommand, strCmd); // thread runs free
673         }
674
675     }
676     return true;
677 }
678
679 /**
680  * Add a transaction to the wallet, or update it.
681  * pblock is optional, but should be provided if the transaction is known to be in a block.
682  * If fUpdate is true, existing transactions will be updated.
683  */
684 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
685 {
686     {
687         AssertLockHeld(cs_wallet);
688         bool fExisted = mapWallet.count(tx.GetHash()) != 0;
689         if (fExisted && !fUpdate) return false;
690         if (fExisted || IsMine(tx) || IsFromMe(tx))
691         {
692             CWalletTx wtx(this,tx);
693             // Get merkle branch if transaction was found in a block
694             if (pblock)
695                 wtx.SetMerkleBranch(*pblock);
696             return AddToWallet(wtx);
697         }
698     }
699     return false;
700 }
701
702 void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock)
703 {
704     LOCK2(cs_main, cs_wallet);
705     if (!AddToWalletIfInvolvingMe(tx, pblock, true))
706         return; // Not one of ours
707
708     // If a transaction changes 'conflicted' state, that changes the balance
709     // available of the outputs it spends. So force those to be
710     // recomputed, also:
711     BOOST_FOREACH(const CTxIn& txin, tx.vin)
712     {
713         if (mapWallet.count(txin.prevout.hash))
714             mapWallet[txin.prevout.hash].MarkDirty();
715     }
716 }
717
718 void CWallet::EraseFromWallet(const uint256 &hash)
719 {
720     if (!fFileBacked)
721         return;
722     {
723         LOCK(cs_wallet);
724         if (mapWallet.erase(hash))
725             CWalletDB(strWalletFile).EraseTx(hash);
726     }
727     return;
728 }
729
730
731 isminetype CWallet::IsMine(const CTxIn &txin) const
732 {
733     {
734         LOCK(cs_wallet);
735         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
736         if (mi != mapWallet.end())
737         {
738             const CWalletTx& prev = (*mi).second;
739             if (txin.prevout.n < prev.vout.size())
740                 return IsMine(prev.vout[txin.prevout.n]);
741         }
742     }
743     return ISMINE_NO;
744 }
745
746 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
747 {
748     {
749         LOCK(cs_wallet);
750         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
751         if (mi != mapWallet.end())
752         {
753             const CWalletTx& prev = (*mi).second;
754             if (txin.prevout.n < prev.vout.size())
755                 if (IsMine(prev.vout[txin.prevout.n]) & filter)
756                     return prev.vout[txin.prevout.n].nValue;
757         }
758     }
759     return 0;
760 }
761
762 bool CWallet::IsChange(const CTxOut& txout) const
763 {
764     // TODO: fix handling of 'change' outputs. The assumption is that any
765     // payment to a script that is ours, but is not in the address book
766     // is change. That assumption is likely to break when we implement multisignature
767     // wallets that return change back into a multi-signature-protected address;
768     // a better way of identifying which outputs are 'the send' and which are
769     // 'the change' will need to be implemented (maybe extend CWalletTx to remember
770     // which output, if any, was change).
771     if (::IsMine(*this, txout.scriptPubKey))
772     {
773         CTxDestination address;
774         if (!ExtractDestination(txout.scriptPubKey, address))
775             return true;
776
777         LOCK(cs_wallet);
778         if (!mapAddressBook.count(address))
779             return true;
780     }
781     return false;
782 }
783
784 int64_t CWalletTx::GetTxTime() const
785 {
786     int64_t n = nTimeSmart;
787     return n ? n : nTimeReceived;
788 }
789
790 int CWalletTx::GetRequestCount() const
791 {
792     // Returns -1 if it wasn't being tracked
793     int nRequests = -1;
794     {
795         LOCK(pwallet->cs_wallet);
796         if (IsCoinBase())
797         {
798             // Generated block
799             if (hashBlock != 0)
800             {
801                 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
802                 if (mi != pwallet->mapRequestCount.end())
803                     nRequests = (*mi).second;
804             }
805         }
806         else
807         {
808             // Did anyone request this transaction?
809             map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
810             if (mi != pwallet->mapRequestCount.end())
811             {
812                 nRequests = (*mi).second;
813
814                 // How about the block it's in?
815                 if (nRequests == 0 && hashBlock != 0)
816                 {
817                     map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
818                     if (mi != pwallet->mapRequestCount.end())
819                         nRequests = (*mi).second;
820                     else
821                         nRequests = 1; // If it's in someone else's block it must have got out
822                 }
823             }
824         }
825     }
826     return nRequests;
827 }
828
829 void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
830                            list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
831 {
832     nFee = 0;
833     listReceived.clear();
834     listSent.clear();
835     strSentAccount = strFromAccount;
836
837     // Compute fee:
838     CAmount nDebit = GetDebit(filter);
839     if (nDebit > 0) // debit>0 means we signed/sent this transaction
840     {
841         CAmount nValueOut = GetValueOut();
842         nFee = nDebit - nValueOut;
843     }
844
845     // Sent/received.
846     for (unsigned int i = 0; i < vout.size(); ++i)
847     {
848         const CTxOut& txout = vout[i];
849         isminetype fIsMine = pwallet->IsMine(txout);
850         // Only need to handle txouts if AT LEAST one of these is true:
851         //   1) they debit from us (sent)
852         //   2) the output is to us (received)
853         if (nDebit > 0)
854         {
855             // Don't report 'change' txouts
856             if (pwallet->IsChange(txout))
857                 continue;
858         }
859         else if (!(fIsMine & filter))
860             continue;
861
862         // In either case, we need to get the destination address
863         CTxDestination address;
864         if (!ExtractDestination(txout.scriptPubKey, address))
865         {
866             LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
867                      this->GetHash().ToString());
868             address = CNoDestination();
869         }
870
871         COutputEntry output = {address, txout.nValue, (int)i};
872
873         // If we are debited by the transaction, add the output as a "sent" entry
874         if (nDebit > 0)
875             listSent.push_back(output);
876
877         // If we are receiving the output, add it as a "received" entry
878         if (fIsMine & filter)
879             listReceived.push_back(output);
880     }
881
882 }
883
884 void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
885                                   CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
886 {
887     nReceived = nSent = nFee = 0;
888
889     CAmount allFee;
890     string strSentAccount;
891     list<COutputEntry> listReceived;
892     list<COutputEntry> listSent;
893     GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
894
895     if (strAccount == strSentAccount)
896     {
897         BOOST_FOREACH(const COutputEntry& s, listSent)
898             nSent += s.amount;
899         nFee = allFee;
900     }
901     {
902         LOCK(pwallet->cs_wallet);
903         BOOST_FOREACH(const COutputEntry& r, listReceived)
904         {
905             if (pwallet->mapAddressBook.count(r.destination))
906             {
907                 map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
908                 if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
909                     nReceived += r.amount;
910             }
911             else if (strAccount.empty())
912             {
913                 nReceived += r.amount;
914             }
915         }
916     }
917 }
918
919
920 bool CWalletTx::WriteToDisk()
921 {
922     return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
923 }
924
925 /**
926  * Scan the block chain (starting in pindexStart) for transactions
927  * from or to us. If fUpdate is true, found transactions that already
928  * exist in the wallet will be updated.
929  */
930 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
931 {
932     int ret = 0;
933     int64_t nNow = GetTime();
934
935     CBlockIndex* pindex = pindexStart;
936     {
937         LOCK2(cs_main, cs_wallet);
938
939         // no need to read and scan block, if block was created before
940         // our wallet birthday (as adjusted for block time variability)
941         while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
942             pindex = chainActive.Next(pindex);
943
944         ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
945         double dProgressStart = Checkpoints::GuessVerificationProgress(pindex, false);
946         double dProgressTip = Checkpoints::GuessVerificationProgress(chainActive.Tip(), false);
947         while (pindex)
948         {
949             if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
950                 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
951
952             CBlock block;
953             ReadBlockFromDisk(block, pindex);
954             BOOST_FOREACH(CTransaction& tx, block.vtx)
955             {
956                 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
957                     ret++;
958             }
959             pindex = chainActive.Next(pindex);
960             if (GetTime() >= nNow + 60) {
961                 nNow = GetTime();
962                 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(pindex));
963             }
964         }
965         ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
966     }
967     return ret;
968 }
969
970 void CWallet::ReacceptWalletTransactions()
971 {
972     LOCK2(cs_main, cs_wallet);
973     BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
974     {
975         const uint256& wtxid = item.first;
976         CWalletTx& wtx = item.second;
977         assert(wtx.GetHash() == wtxid);
978
979         int nDepth = wtx.GetDepthInMainChain();
980
981         if (!wtx.IsCoinBase() && nDepth < 0)
982         {
983             // Try to add to memory pool
984             LOCK(mempool.cs);
985             wtx.AcceptToMemoryPool(false);
986         }
987     }
988 }
989
990 void CWalletTx::RelayWalletTransaction()
991 {
992     if (!IsCoinBase())
993     {
994         if (GetDepthInMainChain() == 0) {
995             LogPrintf("Relaying wtx %s\n", GetHash().ToString());
996             RelayTransaction((CTransaction)*this);
997         }
998     }
999 }
1000
1001 set<uint256> CWalletTx::GetConflicts() const
1002 {
1003     set<uint256> result;
1004     if (pwallet != NULL)
1005     {
1006         uint256 myHash = GetHash();
1007         result = pwallet->GetConflicts(myHash);
1008         result.erase(myHash);
1009     }
1010     return result;
1011 }
1012
1013 void CWallet::ResendWalletTransactions()
1014 {
1015     // Do this infrequently and randomly to avoid giving away
1016     // that these are our transactions.
1017     if (GetTime() < nNextResend)
1018         return;
1019     bool fFirst = (nNextResend == 0);
1020     nNextResend = GetTime() + GetRand(30 * 60);
1021     if (fFirst)
1022         return;
1023
1024     // Only do it if there's been a new block since last time
1025     if (nTimeBestReceived < nLastResend)
1026         return;
1027     nLastResend = GetTime();
1028
1029     // Rebroadcast any of our txes that aren't in a block yet
1030     LogPrintf("ResendWalletTransactions()\n");
1031     {
1032         LOCK(cs_wallet);
1033         // Sort them in chronological order
1034         multimap<unsigned int, CWalletTx*> mapSorted;
1035         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1036         {
1037             CWalletTx& wtx = item.second;
1038             // Don't rebroadcast until it's had plenty of time that
1039             // it should have gotten in already by now.
1040             if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60)
1041                 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1042         }
1043         BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1044         {
1045             CWalletTx& wtx = *item.second;
1046             wtx.RelayWalletTransaction();
1047         }
1048     }
1049 }
1050
1051 /** @} */ // end of mapWallet
1052
1053
1054
1055
1056 /** @defgroup Actions
1057  *
1058  * @{
1059  */
1060
1061
1062 CAmount CWallet::GetBalance() const
1063 {
1064     CAmount nTotal = 0;
1065     {
1066         LOCK2(cs_main, cs_wallet);
1067         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1068         {
1069             const CWalletTx* pcoin = &(*it).second;
1070             if (pcoin->IsTrusted())
1071                 nTotal += pcoin->GetAvailableCredit();
1072         }
1073     }
1074
1075     return nTotal;
1076 }
1077
1078 CAmount CWallet::GetUnconfirmedBalance() const
1079 {
1080     CAmount nTotal = 0;
1081     {
1082         LOCK2(cs_main, cs_wallet);
1083         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1084         {
1085             const CWalletTx* pcoin = &(*it).second;
1086             if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
1087                 nTotal += pcoin->GetAvailableCredit();
1088         }
1089     }
1090     return nTotal;
1091 }
1092
1093 CAmount CWallet::GetImmatureBalance() const
1094 {
1095     CAmount nTotal = 0;
1096     {
1097         LOCK2(cs_main, cs_wallet);
1098         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1099         {
1100             const CWalletTx* pcoin = &(*it).second;
1101             nTotal += pcoin->GetImmatureCredit();
1102         }
1103     }
1104     return nTotal;
1105 }
1106
1107 CAmount CWallet::GetWatchOnlyBalance() const
1108 {
1109     CAmount nTotal = 0;
1110     {
1111         LOCK2(cs_main, cs_wallet);
1112         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1113         {
1114             const CWalletTx* pcoin = &(*it).second;
1115             if (pcoin->IsTrusted())
1116                 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1117         }
1118     }
1119
1120     return nTotal;
1121 }
1122
1123 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
1124 {
1125     CAmount nTotal = 0;
1126     {
1127         LOCK2(cs_main, cs_wallet);
1128         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1129         {
1130             const CWalletTx* pcoin = &(*it).second;
1131             if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0))
1132                 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1133         }
1134     }
1135     return nTotal;
1136 }
1137
1138 CAmount CWallet::GetImmatureWatchOnlyBalance() const
1139 {
1140     CAmount nTotal = 0;
1141     {
1142         LOCK2(cs_main, cs_wallet);
1143         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1144         {
1145             const CWalletTx* pcoin = &(*it).second;
1146             nTotal += pcoin->GetImmatureWatchOnlyCredit();
1147         }
1148     }
1149     return nTotal;
1150 }
1151
1152 /**
1153  * populate vCoins with vector of available COutputs.
1154  */
1155 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1156 {
1157     vCoins.clear();
1158
1159     {
1160         LOCK2(cs_main, cs_wallet);
1161         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1162         {
1163             const uint256& wtxid = it->first;
1164             const CWalletTx* pcoin = &(*it).second;
1165
1166             if (!IsFinalTx(*pcoin))
1167                 continue;
1168
1169             if (fOnlyConfirmed && !pcoin->IsTrusted())
1170                 continue;
1171
1172             if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1173                 continue;
1174
1175             int nDepth = pcoin->GetDepthInMainChain();
1176             if (nDepth < 0)
1177                 continue;
1178
1179             for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1180                 isminetype mine = IsMine(pcoin->vout[i]);
1181                 if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
1182                     !IsLockedCoin((*it).first, i) && pcoin->vout[i].nValue > 0 &&
1183                     (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1184                         vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO));
1185             }
1186         }
1187     }
1188 }
1189
1190 static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
1191                                   vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
1192 {
1193     vector<char> vfIncluded;
1194
1195     vfBest.assign(vValue.size(), true);
1196     nBest = nTotalLower;
1197
1198     seed_insecure_rand();
1199
1200     for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1201     {
1202         vfIncluded.assign(vValue.size(), false);
1203         CAmount nTotal = 0;
1204         bool fReachedTarget = false;
1205         for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1206         {
1207             for (unsigned int i = 0; i < vValue.size(); i++)
1208             {
1209                 //The solver here uses a randomized algorithm,
1210                 //the randomness serves no real security purpose but is just
1211                 //needed to prevent degenerate behavior and it is important
1212                 //that the rng is fast. We do not use a constant random sequence,
1213                 //because there may be some privacy improvement by making
1214                 //the selection random.
1215                 if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])
1216                 {
1217                     nTotal += vValue[i].first;
1218                     vfIncluded[i] = true;
1219                     if (nTotal >= nTargetValue)
1220                     {
1221                         fReachedTarget = true;
1222                         if (nTotal < nBest)
1223                         {
1224                             nBest = nTotal;
1225                             vfBest = vfIncluded;
1226                         }
1227                         nTotal -= vValue[i].first;
1228                         vfIncluded[i] = false;
1229                     }
1230                 }
1231             }
1232         }
1233     }
1234 }
1235
1236 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
1237                                  set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
1238 {
1239     setCoinsRet.clear();
1240     nValueRet = 0;
1241
1242     // List of values less than target
1243     pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1244     coinLowestLarger.first = std::numeric_limits<CAmount>::max();
1245     coinLowestLarger.second.first = NULL;
1246     vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
1247     CAmount nTotalLower = 0;
1248
1249     random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1250
1251     BOOST_FOREACH(const COutput &output, vCoins)
1252     {
1253         if (!output.fSpendable)
1254             continue;
1255
1256         const CWalletTx *pcoin = output.tx;
1257
1258         if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
1259             continue;
1260
1261         int i = output.i;
1262         CAmount n = pcoin->vout[i].nValue;
1263
1264         pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1265
1266         if (n == nTargetValue)
1267         {
1268             setCoinsRet.insert(coin.second);
1269             nValueRet += coin.first;
1270             return true;
1271         }
1272         else if (n < nTargetValue + CENT)
1273         {
1274             vValue.push_back(coin);
1275             nTotalLower += n;
1276         }
1277         else if (n < coinLowestLarger.first)
1278         {
1279             coinLowestLarger = coin;
1280         }
1281     }
1282
1283     if (nTotalLower == nTargetValue)
1284     {
1285         for (unsigned int i = 0; i < vValue.size(); ++i)
1286         {
1287             setCoinsRet.insert(vValue[i].second);
1288             nValueRet += vValue[i].first;
1289         }
1290         return true;
1291     }
1292
1293     if (nTotalLower < nTargetValue)
1294     {
1295         if (coinLowestLarger.second.first == NULL)
1296             return false;
1297         setCoinsRet.insert(coinLowestLarger.second);
1298         nValueRet += coinLowestLarger.first;
1299         return true;
1300     }
1301
1302     // Solve subset sum by stochastic approximation
1303     sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1304     vector<char> vfBest;
1305     CAmount nBest;
1306
1307     ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1308     if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1309         ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1310
1311     // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1312     //                                   or the next bigger coin is closer), return the bigger coin
1313     if (coinLowestLarger.second.first &&
1314         ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1315     {
1316         setCoinsRet.insert(coinLowestLarger.second);
1317         nValueRet += coinLowestLarger.first;
1318     }
1319     else {
1320         for (unsigned int i = 0; i < vValue.size(); i++)
1321             if (vfBest[i])
1322             {
1323                 setCoinsRet.insert(vValue[i].second);
1324                 nValueRet += vValue[i].first;
1325             }
1326
1327         LogPrint("selectcoins", "SelectCoins() best subset: ");
1328         for (unsigned int i = 0; i < vValue.size(); i++)
1329             if (vfBest[i])
1330                 LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first));
1331         LogPrint("selectcoins", "total %s\n", FormatMoney(nBest));
1332     }
1333
1334     return true;
1335 }
1336
1337 bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
1338 {
1339     vector<COutput> vCoins;
1340     AvailableCoins(vCoins, true, coinControl);
1341
1342     // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1343     if (coinControl && coinControl->HasSelected())
1344     {
1345         BOOST_FOREACH(const COutput& out, vCoins)
1346         {
1347             if(!out.fSpendable)
1348                 continue;
1349             nValueRet += out.tx->vout[out.i].nValue;
1350             setCoinsRet.insert(make_pair(out.tx, out.i));
1351         }
1352         return (nValueRet >= nTargetValue);
1353     }
1354
1355     return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1356             SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1357             (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet)));
1358 }
1359
1360
1361
1362
1363 bool CWallet::CreateTransaction(const vector<pair<CScript, CAmount> >& vecSend,
1364                                 CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl)
1365 {
1366     CAmount nValue = 0;
1367     BOOST_FOREACH (const PAIRTYPE(CScript, CAmount)& s, vecSend)
1368     {
1369         if (nValue < 0)
1370         {
1371             strFailReason = _("Transaction amounts must be positive");
1372             return false;
1373         }
1374         nValue += s.second;
1375     }
1376     if (vecSend.empty() || nValue < 0)
1377     {
1378         strFailReason = _("Transaction amounts must be positive");
1379         return false;
1380     }
1381
1382     wtxNew.fTimeReceivedIsTxTime = true;
1383     wtxNew.BindWallet(this);
1384     CMutableTransaction txNew;
1385
1386     // Discourage fee sniping.
1387     //
1388     // However because of a off-by-one-error in previous versions we need to
1389     // neuter it by setting nLockTime to at least one less than nBestHeight.
1390     // Secondly currently propagation of transactions created for block heights
1391     // corresponding to blocks that were just mined may be iffy - transactions
1392     // aren't re-accepted into the mempool - we additionally neuter the code by
1393     // going ten blocks back. Doesn't yet do anything for sniping, but does act
1394     // to shake out wallet bugs like not showing nLockTime'd transactions at
1395     // all.
1396     txNew.nLockTime = std::max(0, chainActive.Height() - 10);
1397
1398     // Secondly occasionally randomly pick a nLockTime even further back, so
1399     // that transactions that are delayed after signing for whatever reason,
1400     // e.g. high-latency mix networks and some CoinJoin implementations, have
1401     // better privacy.
1402     if (GetRandInt(10) == 0)
1403         txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
1404
1405     assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
1406     assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
1407
1408     {
1409         LOCK2(cs_main, cs_wallet);
1410         {
1411             nFeeRet = 0;
1412             while (true)
1413             {
1414                 txNew.vin.clear();
1415                 txNew.vout.clear();
1416                 wtxNew.fFromMe = true;
1417
1418                 CAmount nTotalValue = nValue + nFeeRet;
1419                 double dPriority = 0;
1420                 // vouts to the payees
1421                 BOOST_FOREACH (const PAIRTYPE(CScript, CAmount)& s, vecSend)
1422                 {
1423                     CTxOut txout(s.second, s.first);
1424                     if (txout.IsDust(::minRelayTxFee))
1425                     {
1426                         strFailReason = _("Transaction amount too small");
1427                         return false;
1428                     }
1429                     txNew.vout.push_back(txout);
1430                 }
1431
1432                 // Choose coins to use
1433                 set<pair<const CWalletTx*,unsigned int> > setCoins;
1434                 CAmount nValueIn = 0;
1435                 if (!SelectCoins(nTotalValue, setCoins, nValueIn, coinControl))
1436                 {
1437                     strFailReason = _("Insufficient funds");
1438                     return false;
1439                 }
1440                 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1441                 {
1442                     CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
1443                     //The priority after the next block (depth+1) is used instead of the current,
1444                     //reflecting an assumption the user would accept a bit more delay for
1445                     //a chance at a free transaction.
1446                     dPriority += (double)nCredit * (pcoin.first->GetDepthInMainChain()+1);
1447                 }
1448
1449                 CAmount nChange = nValueIn - nValue - nFeeRet;
1450
1451                 if (nChange > 0)
1452                 {
1453                     // Fill a vout to ourself
1454                     // TODO: pass in scriptChange instead of reservekey so
1455                     // change transaction isn't always pay-to-bitcoin-address
1456                     CScript scriptChange;
1457
1458                     // coin control: send change to custom address
1459                     if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1460                         scriptChange = GetScriptForDestination(coinControl->destChange);
1461
1462                     // no coin control: send change to newly generated address
1463                     else
1464                     {
1465                         // Note: We use a new key here to keep it from being obvious which side is the change.
1466                         //  The drawback is that by not reusing a previous key, the change may be lost if a
1467                         //  backup is restored, if the backup doesn't have the new private key for the change.
1468                         //  If we reused the old key, it would be possible to add code to look for and
1469                         //  rediscover unknown transactions that were written with keys of ours to recover
1470                         //  post-backup change.
1471
1472                         // Reserve a new key pair from key pool
1473                         CPubKey vchPubKey;
1474                         bool ret;
1475                         ret = reservekey.GetReservedKey(vchPubKey);
1476                         assert(ret); // should never fail, as we just unlocked
1477
1478                         scriptChange = GetScriptForDestination(vchPubKey.GetID());
1479                     }
1480
1481                     CTxOut newTxOut(nChange, scriptChange);
1482
1483                     // Never create dust outputs; if we would, just
1484                     // add the dust to the fee.
1485                     if (newTxOut.IsDust(::minRelayTxFee))
1486                     {
1487                         nFeeRet += nChange;
1488                         reservekey.ReturnKey();
1489                     }
1490                     else
1491                     {
1492                         // Insert change txn at random position:
1493                         vector<CTxOut>::iterator position = txNew.vout.begin()+GetRandInt(txNew.vout.size()+1);
1494                         txNew.vout.insert(position, newTxOut);
1495                     }
1496                 }
1497                 else
1498                     reservekey.ReturnKey();
1499
1500                 // Fill vin
1501                 //
1502                 // Note how the sequence number is set to max()-1 so that the
1503                 // nLockTime set above actually works.
1504                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1505                     txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
1506                                               std::numeric_limits<unsigned int>::max()-1));
1507
1508                 // Sign
1509                 int nIn = 0;
1510                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1511                     if (!SignSignature(*this, *coin.first, txNew, nIn++))
1512                     {
1513                         strFailReason = _("Signing transaction failed");
1514                         return false;
1515                     }
1516
1517                 // Embed the constructed transaction data in wtxNew.
1518                 *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
1519
1520                 // Limit size
1521                 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1522                 if (nBytes >= MAX_STANDARD_TX_SIZE)
1523                 {
1524                     strFailReason = _("Transaction too large");
1525                     return false;
1526                 }
1527                 dPriority = wtxNew.ComputePriority(dPriority, nBytes);
1528
1529                 // Can we complete this as a free transaction?
1530                 if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
1531                 {
1532                     // Not enough fee: enough priority?
1533                     double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget);
1534                     // Not enough mempool history to estimate: use hard-coded AllowFree.
1535                     if (dPriorityNeeded <= 0 && AllowFree(dPriority))
1536                         break;
1537
1538                     // Small enough, and priority high enough, to send for free
1539                     if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded)
1540                         break;
1541                 }
1542
1543                 CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
1544
1545                 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
1546                 // because we must be at the maximum allowed fee.
1547                 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
1548                 {
1549                     strFailReason = _("Transaction too large for fee policy");
1550                     return false;
1551                 }
1552
1553                 if (nFeeRet >= nFeeNeeded)
1554                     break; // Done, enough fee included.
1555
1556                 // Include more fee and try again.
1557                 nFeeRet = nFeeNeeded;
1558                 continue;
1559             }
1560         }
1561     }
1562     return true;
1563 }
1564
1565 bool CWallet::CreateTransaction(CScript scriptPubKey, const CAmount& nValue,
1566                                 CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl)
1567 {
1568     vector< pair<CScript, CAmount> > vecSend;
1569     vecSend.push_back(make_pair(scriptPubKey, nValue));
1570     return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strFailReason, coinControl);
1571 }
1572
1573 /**
1574  * Call after CreateTransaction unless you want to abort
1575  */
1576 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1577 {
1578     {
1579         LOCK2(cs_main, cs_wallet);
1580         LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
1581         {
1582             // This is only to keep the database open to defeat the auto-flush for the
1583             // duration of this scope.  This is the only place where this optimization
1584             // maybe makes sense; please don't do it anywhere else.
1585             CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1586
1587             // Take key pair from key pool so it won't be used again
1588             reservekey.KeepKey();
1589
1590             // Add tx to wallet, because if it has change it's also ours,
1591             // otherwise just for transaction history.
1592             AddToWallet(wtxNew);
1593
1594             // Notify that old coins are spent
1595             set<CWalletTx*> setCoins;
1596             BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1597             {
1598                 CWalletTx &coin = mapWallet[txin.prevout.hash];
1599                 coin.BindWallet(this);
1600                 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1601             }
1602
1603             if (fFileBacked)
1604                 delete pwalletdb;
1605         }
1606
1607         // Track how many getdata requests our transaction gets
1608         mapRequestCount[wtxNew.GetHash()] = 0;
1609
1610         // Broadcast
1611         if (!wtxNew.AcceptToMemoryPool(false))
1612         {
1613             // This must not fail. The transaction has already been signed and recorded.
1614             LogPrintf("CommitTransaction() : Error: Transaction not valid");
1615             return false;
1616         }
1617         wtxNew.RelayWalletTransaction();
1618     }
1619     return true;
1620 }
1621
1622 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
1623 {
1624     // payTxFee is user-set "I want to pay this much"
1625     CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
1626     // user selected total at least (default=true)
1627     if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK())
1628         nFeeNeeded = payTxFee.GetFeePerK();
1629     // User didn't set: use -txconfirmtarget to estimate...
1630     if (nFeeNeeded == 0)
1631         nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes);
1632     // ... unless we don't have enough mempool data, in which case fall
1633     // back to a hard-coded fee
1634     if (nFeeNeeded == 0)
1635         nFeeNeeded = minTxFee.GetFee(nTxBytes);
1636     // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee
1637     if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes))
1638         nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes);
1639     // But always obey the maximum
1640     if (nFeeNeeded > maxTxFee)
1641         nFeeNeeded = maxTxFee;
1642     return nFeeNeeded;
1643 }
1644
1645
1646
1647
1648 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
1649 {
1650     if (!fFileBacked)
1651         return DB_LOAD_OK;
1652     fFirstRunRet = false;
1653     DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1654     if (nLoadWalletRet == DB_NEED_REWRITE)
1655     {
1656         if (CDB::Rewrite(strWalletFile, "\x04pool"))
1657         {
1658             LOCK(cs_wallet);
1659             setKeyPool.clear();
1660             // Note: can't top-up keypool here, because wallet is locked.
1661             // User will be prompted to unlock wallet the next operation
1662             // the requires a new key.
1663         }
1664     }
1665
1666     if (nLoadWalletRet != DB_LOAD_OK)
1667         return nLoadWalletRet;
1668     fFirstRunRet = !vchDefaultKey.IsValid();
1669
1670     uiInterface.LoadWallet(this);
1671
1672     return DB_LOAD_OK;
1673 }
1674
1675
1676 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
1677 {
1678     if (!fFileBacked)
1679         return DB_LOAD_OK;
1680     DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
1681     if (nZapWalletTxRet == DB_NEED_REWRITE)
1682     {
1683         if (CDB::Rewrite(strWalletFile, "\x04pool"))
1684         {
1685             LOCK(cs_wallet);
1686             setKeyPool.clear();
1687             // Note: can't top-up keypool here, because wallet is locked.
1688             // User will be prompted to unlock wallet the next operation
1689             // that requires a new key.
1690         }
1691     }
1692
1693     if (nZapWalletTxRet != DB_LOAD_OK)
1694         return nZapWalletTxRet;
1695
1696     return DB_LOAD_OK;
1697 }
1698
1699
1700 bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
1701 {
1702     bool fUpdated = false;
1703     {
1704         LOCK(cs_wallet); // mapAddressBook
1705         std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
1706         fUpdated = mi != mapAddressBook.end();
1707         mapAddressBook[address].name = strName;
1708         if (!strPurpose.empty()) /* update purpose only if requested */
1709             mapAddressBook[address].purpose = strPurpose;
1710     }
1711     NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
1712                              strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
1713     if (!fFileBacked)
1714         return false;
1715     if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
1716         return false;
1717     return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
1718 }
1719
1720 bool CWallet::DelAddressBook(const CTxDestination& address)
1721 {
1722     {
1723         LOCK(cs_wallet); // mapAddressBook
1724
1725         if(fFileBacked)
1726         {
1727             // Delete destdata tuples associated with address
1728             std::string strAddress = CBitcoinAddress(address).ToString();
1729             BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
1730             {
1731                 CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
1732             }
1733         }
1734         mapAddressBook.erase(address);
1735     }
1736
1737     NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
1738
1739     if (!fFileBacked)
1740         return false;
1741     CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
1742     return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
1743 }
1744
1745 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
1746 {
1747     if (fFileBacked)
1748     {
1749         if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1750             return false;
1751     }
1752     vchDefaultKey = vchPubKey;
1753     return true;
1754 }
1755
1756 /**
1757  * Mark old keypool keys as used,
1758  * and generate all new keys 
1759  */
1760 bool CWallet::NewKeyPool()
1761 {
1762     {
1763         LOCK(cs_wallet);
1764         CWalletDB walletdb(strWalletFile);
1765         BOOST_FOREACH(int64_t nIndex, setKeyPool)
1766             walletdb.ErasePool(nIndex);
1767         setKeyPool.clear();
1768
1769         if (IsLocked())
1770             return false;
1771
1772         int64_t nKeys = max(GetArg("-keypool", 100), (int64_t)0);
1773         for (int i = 0; i < nKeys; i++)
1774         {
1775             int64_t nIndex = i+1;
1776             walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1777             setKeyPool.insert(nIndex);
1778         }
1779         LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
1780     }
1781     return true;
1782 }
1783
1784 bool CWallet::TopUpKeyPool(unsigned int kpSize)
1785 {
1786     {
1787         LOCK(cs_wallet);
1788
1789         if (IsLocked())
1790             return false;
1791
1792         CWalletDB walletdb(strWalletFile);
1793
1794         // Top up key pool
1795         unsigned int nTargetSize;
1796         if (kpSize > 0)
1797             nTargetSize = kpSize;
1798         else
1799             nTargetSize = max(GetArg("-keypool", 100), (int64_t) 0);
1800
1801         while (setKeyPool.size() < (nTargetSize + 1))
1802         {
1803             int64_t nEnd = 1;
1804             if (!setKeyPool.empty())
1805                 nEnd = *(--setKeyPool.end()) + 1;
1806             if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1807                 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1808             setKeyPool.insert(nEnd);
1809             LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
1810         }
1811     }
1812     return true;
1813 }
1814
1815 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
1816 {
1817     nIndex = -1;
1818     keypool.vchPubKey = CPubKey();
1819     {
1820         LOCK(cs_wallet);
1821
1822         if (!IsLocked())
1823             TopUpKeyPool();
1824
1825         // Get the oldest key
1826         if(setKeyPool.empty())
1827             return;
1828
1829         CWalletDB walletdb(strWalletFile);
1830
1831         nIndex = *(setKeyPool.begin());
1832         setKeyPool.erase(setKeyPool.begin());
1833         if (!walletdb.ReadPool(nIndex, keypool))
1834             throw runtime_error("ReserveKeyFromKeyPool() : read failed");
1835         if (!HaveKey(keypool.vchPubKey.GetID()))
1836             throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
1837         assert(keypool.vchPubKey.IsValid());
1838         LogPrintf("keypool reserve %d\n", nIndex);
1839     }
1840 }
1841
1842 void CWallet::KeepKey(int64_t nIndex)
1843 {
1844     // Remove from key pool
1845     if (fFileBacked)
1846     {
1847         CWalletDB walletdb(strWalletFile);
1848         walletdb.ErasePool(nIndex);
1849     }
1850     LogPrintf("keypool keep %d\n", nIndex);
1851 }
1852
1853 void CWallet::ReturnKey(int64_t nIndex)
1854 {
1855     // Return to key pool
1856     {
1857         LOCK(cs_wallet);
1858         setKeyPool.insert(nIndex);
1859     }
1860     LogPrintf("keypool return %d\n", nIndex);
1861 }
1862
1863 bool CWallet::GetKeyFromPool(CPubKey& result)
1864 {
1865     int64_t nIndex = 0;
1866     CKeyPool keypool;
1867     {
1868         LOCK(cs_wallet);
1869         ReserveKeyFromKeyPool(nIndex, keypool);
1870         if (nIndex == -1)
1871         {
1872             if (IsLocked()) return false;
1873             result = GenerateNewKey();
1874             return true;
1875         }
1876         KeepKey(nIndex);
1877         result = keypool.vchPubKey;
1878     }
1879     return true;
1880 }
1881
1882 int64_t CWallet::GetOldestKeyPoolTime()
1883 {
1884     int64_t nIndex = 0;
1885     CKeyPool keypool;
1886     ReserveKeyFromKeyPool(nIndex, keypool);
1887     if (nIndex == -1)
1888         return GetTime();
1889     ReturnKey(nIndex);
1890     return keypool.nTime;
1891 }
1892
1893 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
1894 {
1895     map<CTxDestination, CAmount> balances;
1896
1897     {
1898         LOCK(cs_wallet);
1899         BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
1900         {
1901             CWalletTx *pcoin = &walletEntry.second;
1902
1903             if (!IsFinalTx(*pcoin) || !pcoin->IsTrusted())
1904                 continue;
1905
1906             if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1907                 continue;
1908
1909             int nDepth = pcoin->GetDepthInMainChain();
1910             if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
1911                 continue;
1912
1913             for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1914             {
1915                 CTxDestination addr;
1916                 if (!IsMine(pcoin->vout[i]))
1917                     continue;
1918                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
1919                     continue;
1920
1921                 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
1922
1923                 if (!balances.count(addr))
1924                     balances[addr] = 0;
1925                 balances[addr] += n;
1926             }
1927         }
1928     }
1929
1930     return balances;
1931 }
1932
1933 set< set<CTxDestination> > CWallet::GetAddressGroupings()
1934 {
1935     AssertLockHeld(cs_wallet); // mapWallet
1936     set< set<CTxDestination> > groupings;
1937     set<CTxDestination> grouping;
1938
1939     BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
1940     {
1941         CWalletTx *pcoin = &walletEntry.second;
1942
1943         if (pcoin->vin.size() > 0)
1944         {
1945             bool any_mine = false;
1946             // group all input addresses with each other
1947             BOOST_FOREACH(CTxIn txin, pcoin->vin)
1948             {
1949                 CTxDestination address;
1950                 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
1951                     continue;
1952                 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
1953                     continue;
1954                 grouping.insert(address);
1955                 any_mine = true;
1956             }
1957
1958             // group change with input addresses
1959             if (any_mine)
1960             {
1961                BOOST_FOREACH(CTxOut txout, pcoin->vout)
1962                    if (IsChange(txout))
1963                    {
1964                        CTxDestination txoutAddr;
1965                        if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
1966                            continue;
1967                        grouping.insert(txoutAddr);
1968                    }
1969             }
1970             if (grouping.size() > 0)
1971             {
1972                 groupings.insert(grouping);
1973                 grouping.clear();
1974             }
1975         }
1976
1977         // group lone addrs by themselves
1978         for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1979             if (IsMine(pcoin->vout[i]))
1980             {
1981                 CTxDestination address;
1982                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
1983                     continue;
1984                 grouping.insert(address);
1985                 groupings.insert(grouping);
1986                 grouping.clear();
1987             }
1988     }
1989
1990     set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
1991     map< CTxDestination, set<CTxDestination>* > setmap;  // map addresses to the unique group containing it
1992     BOOST_FOREACH(set<CTxDestination> grouping, groupings)
1993     {
1994         // make a set of all the groups hit by this new group
1995         set< set<CTxDestination>* > hits;
1996         map< CTxDestination, set<CTxDestination>* >::iterator it;
1997         BOOST_FOREACH(CTxDestination address, grouping)
1998             if ((it = setmap.find(address)) != setmap.end())
1999                 hits.insert((*it).second);
2000
2001         // merge all hit groups into a new single group and delete old groups
2002         set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2003         BOOST_FOREACH(set<CTxDestination>* hit, hits)
2004         {
2005             merged->insert(hit->begin(), hit->end());
2006             uniqueGroupings.erase(hit);
2007             delete hit;
2008         }
2009         uniqueGroupings.insert(merged);
2010
2011         // update setmap
2012         BOOST_FOREACH(CTxDestination element, *merged)
2013             setmap[element] = merged;
2014     }
2015
2016     set< set<CTxDestination> > ret;
2017     BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2018     {
2019         ret.insert(*uniqueGrouping);
2020         delete uniqueGrouping;
2021     }
2022
2023     return ret;
2024 }
2025
2026 set<CTxDestination> CWallet::GetAccountAddresses(string strAccount) const
2027 {
2028     LOCK(cs_wallet);
2029     set<CTxDestination> result;
2030     BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
2031     {
2032         const CTxDestination& address = item.first;
2033         const string& strName = item.second.name;
2034         if (strName == strAccount)
2035             result.insert(address);
2036     }
2037     return result;
2038 }
2039
2040 bool CReserveKey::GetReservedKey(CPubKey& pubkey)
2041 {
2042     if (nIndex == -1)
2043     {
2044         CKeyPool keypool;
2045         pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2046         if (nIndex != -1)
2047             vchPubKey = keypool.vchPubKey;
2048         else {
2049             return false;
2050         }
2051     }
2052     assert(vchPubKey.IsValid());
2053     pubkey = vchPubKey;
2054     return true;
2055 }
2056
2057 void CReserveKey::KeepKey()
2058 {
2059     if (nIndex != -1)
2060         pwallet->KeepKey(nIndex);
2061     nIndex = -1;
2062     vchPubKey = CPubKey();
2063 }
2064
2065 void CReserveKey::ReturnKey()
2066 {
2067     if (nIndex != -1)
2068         pwallet->ReturnKey(nIndex);
2069     nIndex = -1;
2070     vchPubKey = CPubKey();
2071 }
2072
2073 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2074 {
2075     setAddress.clear();
2076
2077     CWalletDB walletdb(strWalletFile);
2078
2079     LOCK2(cs_main, cs_wallet);
2080     BOOST_FOREACH(const int64_t& id, setKeyPool)
2081     {
2082         CKeyPool keypool;
2083         if (!walletdb.ReadPool(id, keypool))
2084             throw runtime_error("GetAllReserveKeyHashes() : read failed");
2085         assert(keypool.vchPubKey.IsValid());
2086         CKeyID keyID = keypool.vchPubKey.GetID();
2087         if (!HaveKey(keyID))
2088             throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2089         setAddress.insert(keyID);
2090     }
2091 }
2092
2093 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2094 {
2095     {
2096         LOCK(cs_wallet);
2097         // Only notify UI if this transaction is in this wallet
2098         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2099         if (mi != mapWallet.end())
2100             NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2101     }
2102 }
2103
2104 void CWallet::LockCoin(COutPoint& output)
2105 {
2106     AssertLockHeld(cs_wallet); // setLockedCoins
2107     setLockedCoins.insert(output);
2108 }
2109
2110 void CWallet::UnlockCoin(COutPoint& output)
2111 {
2112     AssertLockHeld(cs_wallet); // setLockedCoins
2113     setLockedCoins.erase(output);
2114 }
2115
2116 void CWallet::UnlockAllCoins()
2117 {
2118     AssertLockHeld(cs_wallet); // setLockedCoins
2119     setLockedCoins.clear();
2120 }
2121
2122 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
2123 {
2124     AssertLockHeld(cs_wallet); // setLockedCoins
2125     COutPoint outpt(hash, n);
2126
2127     return (setLockedCoins.count(outpt) > 0);
2128 }
2129
2130 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
2131 {
2132     AssertLockHeld(cs_wallet); // setLockedCoins
2133     for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
2134          it != setLockedCoins.end(); it++) {
2135         COutPoint outpt = (*it);
2136         vOutpts.push_back(outpt);
2137     }
2138 }
2139
2140 /** @} */ // end of Actions
2141
2142 class CAffectedKeysVisitor : public boost::static_visitor<void> {
2143 private:
2144     const CKeyStore &keystore;
2145     std::vector<CKeyID> &vKeys;
2146
2147 public:
2148     CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
2149
2150     void Process(const CScript &script) {
2151         txnouttype type;
2152         std::vector<CTxDestination> vDest;
2153         int nRequired;
2154         if (ExtractDestinations(script, type, vDest, nRequired)) {
2155             BOOST_FOREACH(const CTxDestination &dest, vDest)
2156                 boost::apply_visitor(*this, dest);
2157         }
2158     }
2159
2160     void operator()(const CKeyID &keyId) {
2161         if (keystore.HaveKey(keyId))
2162             vKeys.push_back(keyId);
2163     }
2164
2165     void operator()(const CScriptID &scriptId) {
2166         CScript script;
2167         if (keystore.GetCScript(scriptId, script))
2168             Process(script);
2169     }
2170
2171     void operator()(const CNoDestination &none) {}
2172 };
2173
2174 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
2175     AssertLockHeld(cs_wallet); // mapKeyMetadata
2176     mapKeyBirth.clear();
2177
2178     // get birth times for keys with metadata
2179     for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2180         if (it->second.nCreateTime)
2181             mapKeyBirth[it->first] = it->second.nCreateTime;
2182
2183     // map in which we'll infer heights of other keys
2184     CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin
2185     std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2186     std::set<CKeyID> setKeys;
2187     GetKeys(setKeys);
2188     BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2189         if (mapKeyBirth.count(keyid) == 0)
2190             mapKeyFirstBlock[keyid] = pindexMax;
2191     }
2192     setKeys.clear();
2193
2194     // if there are no such keys, we're done
2195     if (mapKeyFirstBlock.empty())
2196         return;
2197
2198     // find first block that affects those keys, if there are any left
2199     std::vector<CKeyID> vAffected;
2200     for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2201         // iterate over all wallet transactions...
2202         const CWalletTx &wtx = (*it).second;
2203         BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2204         if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
2205             // ... which are already in a block
2206             int nHeight = blit->second->nHeight;
2207             BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2208                 // iterate over all their outputs
2209                 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
2210                 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2211                     // ... and all their affected keys
2212                     std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2213                     if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2214                         rit->second = blit->second;
2215                 }
2216                 vAffected.clear();
2217             }
2218         }
2219     }
2220
2221     // Extract block timestamps for those keys
2222     for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2223         mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
2224 }
2225
2226 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
2227 {
2228     if (boost::get<CNoDestination>(&dest))
2229         return false;
2230
2231     mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
2232     if (!fFileBacked)
2233         return true;
2234     return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
2235 }
2236
2237 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
2238 {
2239     if (!mapAddressBook[dest].destdata.erase(key))
2240         return false;
2241     if (!fFileBacked)
2242         return true;
2243     return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
2244 }
2245
2246 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
2247 {
2248     mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
2249     return true;
2250 }
2251
2252 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
2253 {
2254     std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
2255     if(i != mapAddressBook.end())
2256     {
2257         CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
2258         if(j != i->second.destdata.end())
2259         {
2260             if(value)
2261                 *value = j->second;
2262             return true;
2263         }
2264     }
2265     return false;
2266 }
2267
2268 CKeyPool::CKeyPool()
2269 {
2270     nTime = GetTime();
2271 }
2272
2273 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
2274 {
2275     nTime = GetTime();
2276     vchPubKey = vchPubKeyIn;
2277 }
2278
2279 CWalletKey::CWalletKey(int64_t nExpires)
2280 {
2281     nTimeCreated = (nExpires ? GetTime() : 0);
2282     nTimeExpires = nExpires;
2283 }
2284
2285 int CMerkleTx::SetMerkleBranch(const CBlock& block)
2286 {
2287     AssertLockHeld(cs_main);
2288     CBlock blockTmp;
2289
2290     // Update the tx's hashBlock
2291     hashBlock = block.GetHash();
2292
2293     // Locate the transaction
2294     for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
2295         if (block.vtx[nIndex] == *(CTransaction*)this)
2296             break;
2297     if (nIndex == (int)block.vtx.size())
2298     {
2299         vMerkleBranch.clear();
2300         nIndex = -1;
2301         LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
2302         return 0;
2303     }
2304
2305     // Fill in merkle branch
2306     vMerkleBranch = block.GetMerkleBranch(nIndex);
2307
2308     // Is the tx in a block that's in the main chain
2309     BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
2310     if (mi == mapBlockIndex.end())
2311         return 0;
2312     const CBlockIndex* pindex = (*mi).second;
2313     if (!pindex || !chainActive.Contains(pindex))
2314         return 0;
2315
2316     return chainActive.Height() - pindex->nHeight + 1;
2317 }
2318
2319 int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const
2320 {
2321     if (hashBlock == 0 || nIndex == -1)
2322         return 0;
2323     AssertLockHeld(cs_main);
2324
2325     // Find the block it claims to be in
2326     BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
2327     if (mi == mapBlockIndex.end())
2328         return 0;
2329     CBlockIndex* pindex = (*mi).second;
2330     if (!pindex || !chainActive.Contains(pindex))
2331         return 0;
2332
2333     // Make sure the merkle branch connects to this block
2334     if (!fMerkleVerified)
2335     {
2336         if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
2337             return 0;
2338         fMerkleVerified = true;
2339     }
2340
2341     pindexRet = pindex;
2342     return chainActive.Height() - pindex->nHeight + 1;
2343 }
2344
2345 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
2346 {
2347     AssertLockHeld(cs_main);
2348     int nResult = GetDepthInMainChainINTERNAL(pindexRet);
2349     if (nResult == 0 && !mempool.exists(GetHash()))
2350         return -1; // Not in chain, not in mempool
2351
2352     return nResult;
2353 }
2354
2355 int CMerkleTx::GetBlocksToMaturity() const
2356 {
2357     if (!IsCoinBase())
2358         return 0;
2359     return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
2360 }
2361
2362
2363 bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectInsaneFee)
2364 {
2365     CValidationState state;
2366     return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectInsaneFee);
2367 }
2368
This page took 0.161676 seconds and 4 git commands to generate.