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