96e84b73d2aaf2993aba27c0e4fe3ff036eadada
[novacoin.git] / src / wallet.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #include "txdb.h"
7 #include "wallet.h"
8 #include "walletdb.h"
9 #include "crypter.h"
10 #include "ui_interface.h"
11 #include "base58.h"
12 #include "kernel.h"
13 #include "coincontrol.h"
14 #include <boost/algorithm/string/replace.hpp>
15
16 using namespace std;
17 extern int nStakeMaxAge;
18
19 //////////////////////////////////////////////////////////////////////////////
20 //
21 // mapWallet
22 //
23
24 struct CompareValueOnly
25 {
26     bool operator()(const pair<int64, pair<const CWalletTx*, unsigned int> >& t1,
27                     const pair<int64, pair<const CWalletTx*, unsigned int> >& t2) const
28     {
29         return t1.first < t2.first;
30     }
31 };
32
33 CPubKey CWallet::GenerateNewKey()
34 {
35     bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
36
37     RandAddSeedPerfmon();
38     CKey key;
39     key.MakeNewKey(fCompressed);
40
41     // Compressed public keys were introduced in version 0.6.0
42     if (fCompressed)
43         SetMinVersion(FEATURE_COMPRPUBKEY);
44
45     CPubKey pubkey = key.GetPubKey();
46
47     // Create new metadata
48     int64 nCreationTime = GetTime();
49     mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime);
50     if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
51         nTimeFirstKey = nCreationTime;
52
53     if (!AddKey(key))
54         throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
55     return key.GetPubKey();
56 }
57
58 bool CWallet::AddKey(const CKey& key)
59 {
60     CPubKey pubkey = key.GetPubKey();
61
62     if (!CCryptoKeyStore::AddKey(key))
63         return false;
64     if (!fFileBacked)
65         return true;
66     if (!IsCrypted())
67         return CWalletDB(strWalletFile).WriteKey(pubkey, key.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]);
68     return true;
69 }
70
71 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey, const vector<unsigned char> &vchCryptedSecret)
72 {
73     if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
74         return false;
75     if (!fFileBacked)
76         return true;
77     {
78         LOCK(cs_wallet);
79         if (pwalletdbEncryption)
80             return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
81         else
82             return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]);
83     }
84     return false;
85 }
86
87 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
88 {
89     if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
90         nTimeFirstKey = meta.nCreateTime;
91
92     mapKeyMetadata[pubkey.GetID()] = meta;
93     return true;
94 }
95
96 bool CWallet::AddCScript(const CScript& redeemScript)
97 {
98     if (!CCryptoKeyStore::AddCScript(redeemScript))
99         return false;
100     if (!fFileBacked)
101         return true;
102     return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
103 }
104
105 bool CWallet::AddWatchOnly(const CScript &dest)
106 {
107     if (!CCryptoKeyStore::AddWatchOnly(dest))
108         return false;
109     nTimeFirstKey = 1; // No birthday information for watch-only keys.
110     if (!fFileBacked)
111         return true;
112     return CWalletDB(strWalletFile).WriteWatchOnly(dest);
113 }
114
115 bool CWallet::LoadWatchOnly(const CScript &dest)
116 {
117     return CCryptoKeyStore::AddWatchOnly(dest);
118 }
119
120 // ppcoin: optional setting to unlock wallet for block minting only;
121 //         serves to disable the trivial sendmoney when OS account compromised
122 bool fWalletUnlockMintOnly = false;
123
124 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
125 {
126     if (!IsLocked())
127         return false;
128
129     CCrypter crypter;
130     CKeyingMaterial vMasterKey;
131
132     {
133         LOCK(cs_wallet);
134         BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
135         {
136             if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
137                 return false;
138             if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
139                 return false;
140             if (CCryptoKeyStore::Unlock(vMasterKey))
141                 return true;
142         }
143     }
144     return false;
145 }
146
147 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
148 {
149     bool fWasLocked = IsLocked();
150
151     {
152         LOCK(cs_wallet);
153         Lock();
154
155         CCrypter crypter;
156         CKeyingMaterial vMasterKey;
157         BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
158         {
159             if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
160                 return false;
161             if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
162                 return false;
163             if (CCryptoKeyStore::Unlock(vMasterKey))
164             {
165                 int64 nStartTime = GetTimeMillis();
166                 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
167                 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
168
169                 nStartTime = GetTimeMillis();
170                 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
171                 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
172
173                 if (pMasterKey.second.nDeriveIterations < 25000)
174                     pMasterKey.second.nDeriveIterations = 25000;
175
176                 printf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
177
178                 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
179                     return false;
180                 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
181                     return false;
182                 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
183                 if (fWasLocked)
184                     Lock();
185                 return true;
186             }
187         }
188     }
189
190     return false;
191 }
192
193 void CWallet::SetBestChain(const CBlockLocator& loc)
194 {
195     CWalletDB walletdb(strWalletFile);
196     walletdb.WriteBestBlock(loc);
197 }
198
199 // This class implements an addrIncoming entry that causes pre-0.4
200 // clients to crash on startup if reading a private-key-encrypted wallet.
201 class CCorruptAddress
202 {
203 public:
204     IMPLEMENT_SERIALIZE
205     (
206         if (nType & SER_DISK)
207             READWRITE(nVersion);
208     )
209 };
210
211 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
212 {
213     if (nWalletVersion >= nVersion)
214         return true;
215
216     // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
217     if (fExplicit && nVersion > nWalletMaxVersion)
218             nVersion = FEATURE_LATEST;
219
220     nWalletVersion = nVersion;
221
222     if (nVersion > nWalletMaxVersion)
223         nWalletMaxVersion = nVersion;
224
225     if (fFileBacked)
226     {
227         CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
228         if (nWalletVersion >= 40000)
229         {
230             // Versions prior to 0.4.0 did not support the "minversion" record.
231             // Use a CCorruptAddress to make them crash instead.
232             CCorruptAddress corruptAddress;
233             pwalletdb->WriteSetting("addrIncoming", corruptAddress);
234         }
235         if (nWalletVersion > 40000)
236             pwalletdb->WriteMinVersion(nWalletVersion);
237         if (!pwalletdbIn)
238             delete pwalletdb;
239     }
240
241     return true;
242 }
243
244 bool CWallet::SetMaxVersion(int nVersion)
245 {
246     // cannot downgrade below current version
247     if (nWalletVersion > nVersion)
248         return false;
249
250     nWalletMaxVersion = nVersion;
251
252     return true;
253 }
254
255 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
256 {
257     if (IsCrypted())
258         return false;
259
260     CKeyingMaterial vMasterKey;
261     RandAddSeedPerfmon();
262
263     vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
264     RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
265
266     CMasterKey kMasterKey(nDerivationMethodIndex);
267
268     RandAddSeedPerfmon();
269     kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
270     RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
271
272     CCrypter crypter;
273     int64 nStartTime = GetTimeMillis();
274     crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
275     kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
276
277     nStartTime = GetTimeMillis();
278     crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
279     kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
280
281     if (kMasterKey.nDeriveIterations < 25000)
282         kMasterKey.nDeriveIterations = 25000;
283
284     printf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
285
286     if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
287         return false;
288     if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
289         return false;
290
291     {
292         LOCK(cs_wallet);
293         mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
294         if (fFileBacked)
295         {
296             pwalletdbEncryption = new CWalletDB(strWalletFile);
297             if (!pwalletdbEncryption->TxnBegin())
298                 return false;
299             pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
300         }
301
302         if (!EncryptKeys(vMasterKey))
303         {
304             if (fFileBacked)
305                 pwalletdbEncryption->TxnAbort();
306             exit(1); //We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet.
307         }
308
309         // Encryption was introduced in version 0.4.0
310         SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
311
312         if (fFileBacked)
313         {
314             if (!pwalletdbEncryption->TxnCommit())
315                 exit(1); //We now have keys encrypted in memory, but no on disk...die to avoid confusion and let the user reload their unencrypted wallet.
316
317             delete pwalletdbEncryption;
318             pwalletdbEncryption = NULL;
319         }
320
321         Lock();
322         Unlock(strWalletPassphrase);
323         NewKeyPool();
324         Lock();
325
326         // Need to completely rewrite the wallet file; if we don't, bdb might keep
327         // bits of the unencrypted private key in slack space in the database file.
328         CDB::Rewrite(strWalletFile);
329
330     }
331     NotifyStatusChanged(this);
332
333     return true;
334 }
335
336 int64 CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
337 {
338     int64 nRet = nOrderPosNext++;
339     if (pwalletdb) {
340         pwalletdb->WriteOrderPosNext(nOrderPosNext);
341     } else {
342         CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
343     }
344     return nRet;
345 }
346
347 CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount)
348 {
349     CWalletDB walletdb(strWalletFile);
350
351     // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap.
352     TxItems txOrdered;
353
354     // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry
355     // would make this much faster for applications that do this a lot.
356     for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
357     {
358         CWalletTx* wtx = &((*it).second);
359         txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0)));
360     }
361     acentries.clear();
362     walletdb.ListAccountCreditDebit(strAccount, acentries);
363     BOOST_FOREACH(CAccountingEntry& entry, acentries)
364     {
365         txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
366     }
367
368     return txOrdered;
369 }
370
371 void CWallet::WalletUpdateSpent(const CTransaction &tx, bool fBlock)
372 {
373     // Anytime a signature is successfully verified, it's proof the outpoint is spent.
374     // Update the wallet spent flag if it doesn't know due to wallet.dat being
375     // restored from backup or the user making copies of wallet.dat.
376     {
377         LOCK(cs_wallet);
378         BOOST_FOREACH(const CTxIn& txin, tx.vin)
379         {
380             map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
381             if (mi != mapWallet.end())
382             {
383                 CWalletTx& wtx = (*mi).second;
384                 if (txin.prevout.n >= wtx.vout.size())
385                     printf("WalletUpdateSpent: bad wtx %s\n", wtx.GetHash().ToString().c_str());
386                 else if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n]))
387                 {
388                     printf("WalletUpdateSpent found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(false)).c_str(), wtx.GetHash().ToString().c_str());
389                     wtx.MarkSpent(txin.prevout.n);
390                     wtx.WriteToDisk();
391                     NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED);
392                 }
393             }
394         }
395
396         if (fBlock)
397         {
398             uint256 hash = tx.GetHash();
399             map<uint256, CWalletTx>::iterator mi = mapWallet.find(hash);
400             CWalletTx& wtx = (*mi).second;
401
402             BOOST_FOREACH(const CTxOut& txout, tx.vout)
403             {
404                 if (IsMine(txout))
405                 {
406                     wtx.MarkUnspent(&txout - &tx.vout[0]);
407                     wtx.WriteToDisk();
408                     NotifyTransactionChanged(this, hash, CT_UPDATED);
409                 }
410             }
411         }
412
413     }
414 }
415
416 void CWallet::MarkDirty()
417 {
418     {
419         LOCK(cs_wallet);
420         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
421             item.second.MarkDirty();
422     }
423 }
424
425 bool CWallet::AddToWallet(const CWalletTx& wtxIn)
426 {
427     uint256 hash = wtxIn.GetHash();
428     {
429         LOCK(cs_wallet);
430         // Inserts only if not already there, returns tx inserted or tx found
431         pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
432         CWalletTx& wtx = (*ret.first).second;
433         wtx.BindWallet(this);
434         bool fInsertedNew = ret.second;
435         if (fInsertedNew)
436         {
437             wtx.nTimeReceived = GetAdjustedTime();
438             wtx.nOrderPos = IncOrderPosNext();
439
440             wtx.nTimeSmart = wtx.nTimeReceived;
441             if (wtxIn.hashBlock != 0)
442             {
443                 if (mapBlockIndex.count(wtxIn.hashBlock))
444                 {
445                     unsigned int latestNow = wtx.nTimeReceived;
446                     unsigned int latestEntry = 0;
447                     {
448                         // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
449                         int64 latestTolerated = latestNow + 300;
450                         std::list<CAccountingEntry> acentries;
451                         TxItems txOrdered = OrderedTxItems(acentries);
452                         for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
453                         {
454                             CWalletTx *const pwtx = (*it).second.first;
455                             if (pwtx == &wtx)
456                                 continue;
457                             CAccountingEntry *const pacentry = (*it).second.second;
458                             int64 nSmartTime;
459                             if (pwtx)
460                             {
461                                 nSmartTime = pwtx->nTimeSmart;
462                                 if (!nSmartTime)
463                                     nSmartTime = pwtx->nTimeReceived;
464                             }
465                             else
466                                 nSmartTime = pacentry->nTime;
467                             if (nSmartTime <= latestTolerated)
468                             {
469                                 latestEntry = nSmartTime;
470                                 if (nSmartTime > latestNow)
471                                     latestNow = nSmartTime;
472                                 break;
473                             }
474                         }
475                     }
476
477                     unsigned int& blocktime = mapBlockIndex[wtxIn.hashBlock]->nTime;
478                     wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
479                 }
480                 else
481                     printf("AddToWallet() : found %s in block %s not in index\n",
482                            wtxIn.GetHash().ToString().substr(0,10).c_str(),
483                            wtxIn.hashBlock.ToString().c_str());
484             }
485         }
486
487         bool fUpdated = false;
488         if (!fInsertedNew)
489         {
490             // Merge
491             if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock)
492             {
493                 wtx.hashBlock = wtxIn.hashBlock;
494                 fUpdated = true;
495             }
496             if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex))
497             {
498                 wtx.vMerkleBranch = wtxIn.vMerkleBranch;
499                 wtx.nIndex = wtxIn.nIndex;
500                 fUpdated = true;
501             }
502             if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
503             {
504                 wtx.fFromMe = wtxIn.fFromMe;
505                 fUpdated = true;
506             }
507             fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent);
508         }
509
510         //// debug print
511         printf("AddToWallet %s  %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
512
513         // Write to disk
514         if (fInsertedNew || fUpdated)
515             if (!wtx.WriteToDisk())
516                 return false;
517 #ifndef QT_GUI
518         // If default receiving address gets used, replace it with a new one
519         CScript scriptDefaultKey;
520         scriptDefaultKey.SetDestination(vchDefaultKey.GetID());
521         BOOST_FOREACH(const CTxOut& txout, wtx.vout)
522         {
523             if (txout.scriptPubKey == scriptDefaultKey)
524             {
525                 CPubKey newDefaultKey;
526                 if (GetKeyFromPool(newDefaultKey, false))
527                 {
528                     SetDefaultKey(newDefaultKey);
529                     SetAddressBookName(vchDefaultKey.GetID(), "");
530                 }
531             }
532         }
533 #endif
534         // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins
535         WalletUpdateSpent(wtx, (wtxIn.hashBlock != 0));
536
537         // Notify UI of new or updated transaction
538         NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
539
540         // notify an external script when a wallet transaction comes in or is updated
541         std::string strCmd = GetArg("-walletnotify", "");
542
543         if ( !strCmd.empty())
544         {
545             boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
546             boost::thread t(runCommand, strCmd); // thread runs free
547         }
548
549     }
550     return true;
551 }
552
553 // Add a transaction to the wallet, or update it.
554 // pblock is optional, but should be provided if the transaction is known to be in a block.
555 // If fUpdate is true, existing transactions will be updated.
556 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
557 {
558     uint256 hash = tx.GetHash();
559     {
560         LOCK(cs_wallet);
561         bool fExisted = mapWallet.count(hash);
562         if (fExisted && !fUpdate) return false;
563         if (fExisted || IsMine(tx) || IsFromMe(tx))
564         {
565             CWalletTx wtx(this,tx);
566             // Get merkle branch if transaction was found in a block
567             if (pblock)
568                 wtx.SetMerkleBranch(pblock);
569             return AddToWallet(wtx);
570         }
571         else
572             WalletUpdateSpent(tx);
573     }
574     return false;
575 }
576
577 bool CWallet::EraseFromWallet(uint256 hash)
578 {
579     if (!fFileBacked)
580         return false;
581     {
582         LOCK(cs_wallet);
583         if (mapWallet.erase(hash))
584             CWalletDB(strWalletFile).EraseTx(hash);
585     }
586     return true;
587 }
588
589
590 isminetype CWallet::IsMine(const CTxIn &txin) const
591 {
592     {
593         LOCK(cs_wallet);
594         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
595         if (mi != mapWallet.end())
596         {
597             const CWalletTx& prev = (*mi).second;
598             if (txin.prevout.n < prev.vout.size())
599                 return IsMine(prev.vout[txin.prevout.n]);
600         }
601     }
602     return MINE_NO;
603 }
604
605 int64 CWallet::GetDebit(const CTxIn &txin) const
606 {
607     {
608         LOCK(cs_wallet);
609         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
610         if (mi != mapWallet.end())
611         {
612             const CWalletTx& prev = (*mi).second;
613             if (txin.prevout.n < prev.vout.size())
614                 if (IsMine(prev.vout[txin.prevout.n]))
615                     return prev.vout[txin.prevout.n].nValue;
616         }
617     }
618     return 0;
619 }
620
621 bool CWallet::IsChange(const CTxOut& txout) const
622 {
623     // TODO: fix handling of 'change' outputs. The assumption is that any
624     // payment to a script that is ours, but isn't in the address book
625     // is change. That assumption is likely to break when we implement multisignature
626     // wallets that return change back into a multi-signature-protected address;
627     // a better way of identifying which outputs are 'the send' and which are
628     // 'the change' will need to be implemented (maybe extend CWalletTx to remember
629     // which output, if any, was change).
630     if (::IsMine(*this, txout.scriptPubKey))
631     {
632         CTxDestination address;
633         if (!ExtractDestination(txout.scriptPubKey, address))
634             return true;
635
636         LOCK(cs_wallet);
637         if (!mapAddressBook.count(address))
638             return true;
639     }
640     return false;
641 }
642
643 int64 CWalletTx::GetTxTime() const
644 {
645     int64 n = nTimeSmart;
646     return n ? n : nTimeReceived;
647 }
648
649 int CWalletTx::GetRequestCount() const
650 {
651     // Returns -1 if it wasn't being tracked
652     int nRequests = -1;
653     {
654         LOCK(pwallet->cs_wallet);
655         if (IsCoinBase() || IsCoinStake())
656         {
657             // Generated block
658             if (hashBlock != 0)
659             {
660                 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
661                 if (mi != pwallet->mapRequestCount.end())
662                     nRequests = (*mi).second;
663             }
664         }
665         else
666         {
667             // Did anyone request this transaction?
668             map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
669             if (mi != pwallet->mapRequestCount.end())
670             {
671                 nRequests = (*mi).second;
672
673                 // How about the block it's in?
674                 if (nRequests == 0 && hashBlock != 0)
675                 {
676                     map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
677                     if (mi != pwallet->mapRequestCount.end())
678                         nRequests = (*mi).second;
679                     else
680                         nRequests = 1; // If it's in someone else's block it must have got out
681                 }
682             }
683         }
684     }
685     return nRequests;
686 }
687
688 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
689                            list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const
690 {
691     nGeneratedImmature = nGeneratedMature = nFee = 0;
692     listReceived.clear();
693     listSent.clear();
694     strSentAccount = strFromAccount;
695
696     if (IsCoinBase() || IsCoinStake())
697     {
698         if (GetBlocksToMaturity() > 0)
699             nGeneratedImmature = pwallet->GetCredit(*this);
700         else
701             nGeneratedMature = GetCredit(false);
702         return;
703     }
704
705     // Compute fee:
706     int64 nDebit = GetDebit();
707     if (nDebit > 0) // debit>0 means we signed/sent this transaction
708     {
709         int64 nValueOut = GetValueOut();
710         nFee = nDebit - nValueOut;
711     }
712
713     // Sent/received.
714     BOOST_FOREACH(const CTxOut& txout, vout)
715     {
716         bool fIsMine;
717         // Only need to handle txouts if AT LEAST one of these is true:
718         //   1) they debit from us (sent)
719         //   2) the output is to us (received)
720         if (nDebit > 0)
721         {
722             // Don't report 'change' txouts
723             if (pwallet->IsChange(txout))
724                 continue;
725             fIsMine = pwallet->IsMine(txout);
726         }
727         else if (!(fIsMine = pwallet->IsMine(txout)))
728             continue;
729
730         // In either case, we need to get the destination address
731         CTxDestination address;
732         if (!ExtractDestination(txout.scriptPubKey, address))
733         {
734             printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
735                    this->GetHash().ToString().c_str());
736             address = CNoDestination();
737         }
738
739         // If we are debited by the transaction, add the output as a "sent" entry
740         if (nDebit > 0)
741             listSent.push_back(make_pair(address, txout.nValue));
742
743         // If we are receiving the output, add it as a "received" entry
744         if (fIsMine)
745             listReceived.push_back(make_pair(address, txout.nValue));
746     }
747
748 }
749
750 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
751                                   int64& nSent, int64& nFee) const
752 {
753     nGenerated = nReceived = nSent = nFee = 0;
754
755     int64 allGeneratedImmature, allGeneratedMature, allFee;
756     allGeneratedImmature = allGeneratedMature = allFee = 0;
757     string strSentAccount;
758     list<pair<CTxDestination, int64> > listReceived;
759     list<pair<CTxDestination, int64> > listSent;
760     GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
761
762     if (strAccount == "")
763         nGenerated = allGeneratedMature;
764     if (strAccount == strSentAccount)
765     {
766         BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
767             nSent += s.second;
768         nFee = allFee;
769     }
770     {
771         LOCK(pwallet->cs_wallet);
772         BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
773         {
774             if (pwallet->mapAddressBook.count(r.first))
775             {
776                 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
777                 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
778                     nReceived += r.second;
779             }
780             else if (strAccount.empty())
781             {
782                 nReceived += r.second;
783             }
784         }
785     }
786 }
787
788 void CWalletTx::AddSupportingTransactions(CTxDB& txdb)
789 {
790     vtxPrev.clear();
791
792     const int COPY_DEPTH = 3;
793     if (SetMerkleBranch() < COPY_DEPTH)
794     {
795         vector<uint256> vWorkQueue;
796         BOOST_FOREACH(const CTxIn& txin, vin)
797             vWorkQueue.push_back(txin.prevout.hash);
798
799         // This critsect is OK because txdb is already open
800         {
801             LOCK(pwallet->cs_wallet);
802             map<uint256, const CMerkleTx*> mapWalletPrev;
803             set<uint256> setAlreadyDone;
804             for (unsigned int i = 0; i < vWorkQueue.size(); i++)
805             {
806                 uint256 hash = vWorkQueue[i];
807                 if (setAlreadyDone.count(hash))
808                     continue;
809                 setAlreadyDone.insert(hash);
810
811                 CMerkleTx tx;
812                 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
813                 if (mi != pwallet->mapWallet.end())
814                 {
815                     tx = (*mi).second;
816                     BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
817                         mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
818                 }
819                 else if (mapWalletPrev.count(hash))
820                 {
821                     tx = *mapWalletPrev[hash];
822                 }
823                 else if (!fClient && txdb.ReadDiskTx(hash, tx))
824                 {
825                     ;
826                 }
827                 else
828                 {
829                     printf("ERROR: AddSupportingTransactions() : unsupported transaction\n");
830                     continue;
831                 }
832
833                 int nDepth = tx.SetMerkleBranch();
834                 vtxPrev.push_back(tx);
835
836                 if (nDepth < COPY_DEPTH)
837                 {
838                     BOOST_FOREACH(const CTxIn& txin, tx.vin)
839                         vWorkQueue.push_back(txin.prevout.hash);
840                 }
841             }
842         }
843     }
844
845     reverse(vtxPrev.begin(), vtxPrev.end());
846 }
847
848 bool CWalletTx::WriteToDisk()
849 {
850     return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
851 }
852
853 // Scan the block chain (starting in pindexStart) for transactions
854 // from or to us. If fUpdate is true, found transactions that already
855 // exist in the wallet will be updated.
856 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
857 {
858     int ret = 0;
859
860     CBlockIndex* pindex = pindexStart;
861     {
862         LOCK(cs_wallet);
863         while (pindex)
864         {
865             CBlock block;
866             block.ReadFromDisk(pindex, true);
867             BOOST_FOREACH(CTransaction& tx, block.vtx)
868             {
869                 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
870                     ret++;
871             }
872             pindex = pindex->pnext;
873         }
874     }
875     return ret;
876 }
877
878 int CWallet::ScanForWalletTransaction(const uint256& hashTx)
879 {
880     CTransaction tx;
881     tx.ReadFromDisk(COutPoint(hashTx, 0));
882     if (AddToWalletIfInvolvingMe(tx, NULL, true, true))
883         return 1;
884     return 0;
885 }
886
887 void CWallet::ReacceptWalletTransactions()
888 {
889     CTxDB txdb("r");
890     bool fRepeat = true;
891     while (fRepeat)
892     {
893         LOCK(cs_wallet);
894         fRepeat = false;
895         vector<CDiskTxPos> vMissingTx;
896         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
897         {
898             CWalletTx& wtx = item.second;
899             if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
900                 continue;
901
902             CTxIndex txindex;
903             bool fUpdated = false;
904             if (txdb.ReadTxIndex(wtx.GetHash(), txindex))
905             {
906                 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
907                 if (txindex.vSpent.size() != wtx.vout.size())
908                 {
909                     printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %"PRIszu" != wtx.vout.size() %"PRIszu"\n", txindex.vSpent.size(), wtx.vout.size());
910                     continue;
911                 }
912                 for (unsigned int i = 0; i < txindex.vSpent.size(); i++)
913                 {
914                     if (wtx.IsSpent(i))
915                         continue;
916                     if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i]))
917                     {
918                         wtx.MarkSpent(i);
919                         fUpdated = true;
920                         vMissingTx.push_back(txindex.vSpent[i]);
921                     }
922                 }
923                 if (fUpdated)
924                 {
925                     printf("ReacceptWalletTransactions found spent coin %snvc %s\n", FormatMoney(wtx.GetCredit(false)).c_str(), wtx.GetHash().ToString().c_str());
926                     wtx.MarkDirty();
927                     wtx.WriteToDisk();
928                 }
929             }
930             else
931             {
932                 // Re-accept any txes of ours that aren't already in a block
933                 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
934                     wtx.AcceptWalletTransaction(txdb, false);
935             }
936         }
937         if (!vMissingTx.empty())
938         {
939             // TODO: optimize this to scan just part of the block chain?
940             if (ScanForWalletTransactions(pindexGenesisBlock))
941                 fRepeat = true;  // Found missing transactions: re-do re-accept.
942         }
943     }
944 }
945
946 void CWalletTx::RelayWalletTransaction(CTxDB& txdb)
947 {
948     BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
949     {
950         if (!(tx.IsCoinBase() || tx.IsCoinStake()))
951         {
952             uint256 hash = tx.GetHash();
953             if (!txdb.ContainsTx(hash))
954                 RelayTransaction((CTransaction)tx, hash);
955         }
956     }
957     if (!(IsCoinBase() || IsCoinStake()))
958     {
959         uint256 hash = GetHash();
960         if (!txdb.ContainsTx(hash))
961         {
962             printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
963             RelayTransaction((CTransaction)*this, hash);
964         }
965     }
966 }
967
968 void CWalletTx::RelayWalletTransaction()
969 {
970    CTxDB txdb("r");
971    RelayWalletTransaction(txdb);
972 }
973
974 void CWallet::ResendWalletTransactions()
975 {
976     // Do this infrequently and randomly to avoid giving away
977     // that these are our transactions.
978     static int64 nNextTime;
979     if (GetTime() < nNextTime)
980         return;
981     bool fFirst = (nNextTime == 0);
982     nNextTime = GetTime() + GetRand(30 * 60);
983     if (fFirst)
984         return;
985
986     // Only do it if there's been a new block since last time
987     static int64 nLastTime;
988     if (nTimeBestReceived < nLastTime)
989         return;
990     nLastTime = GetTime();
991
992     // Rebroadcast any of our txes that aren't in a block yet
993     printf("ResendWalletTransactions()\n");
994     CTxDB txdb("r");
995     {
996         LOCK(cs_wallet);
997         // Sort them in chronological order
998         multimap<unsigned int, CWalletTx*> mapSorted;
999         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1000         {
1001             CWalletTx& wtx = item.second;
1002             // Don't rebroadcast until it's had plenty of time that
1003             // it should have gotten in already by now.
1004             if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
1005                 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1006         }
1007         BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1008         {
1009             CWalletTx& wtx = *item.second;
1010             if (wtx.CheckTransaction())
1011                 wtx.RelayWalletTransaction(txdb);
1012             else
1013                 printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str());
1014         }
1015     }
1016 }
1017
1018
1019
1020
1021
1022
1023 //////////////////////////////////////////////////////////////////////////////
1024 //
1025 // Actions
1026 //
1027
1028
1029 int64 CWallet::GetBalance() const
1030 {
1031     int64 nTotal = 0;
1032     {
1033         LOCK(cs_wallet);
1034         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1035         {
1036             const CWalletTx* pcoin = &(*it).second;
1037             if (pcoin->IsTrusted())
1038                 nTotal += pcoin->GetAvailableCredit();
1039         }
1040     }
1041
1042     return nTotal;
1043 }
1044
1045 int64 CWallet::GetBalanceWatchOnly() const
1046 {
1047     int64 nTotal = 0;
1048     {
1049         LOCK(cs_wallet);
1050         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1051         {
1052             const CWalletTx* pcoin = &(*it).second;
1053             if (pcoin->IsTrusted())
1054                 nTotal += pcoin->GetAvailableCreditWatchOnly();
1055         }
1056     }
1057
1058     return nTotal;
1059 }
1060
1061 int64 CWallet::GetUnconfirmedBalance() const
1062 {
1063     int64 nTotal = 0;
1064     {
1065         LOCK(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->IsFinal() || !pcoin->IsTrusted())
1070                 nTotal += pcoin->GetAvailableCredit(false);
1071         }
1072     }
1073     return nTotal;
1074 }
1075
1076 int64 CWallet::GetImmatureBalance() const
1077 {
1078     int64 nTotal = 0;
1079     {
1080         LOCK(cs_wallet);
1081         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1082         {
1083             const CWalletTx& pcoin = (*it).second;
1084             if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
1085                 nTotal += GetCredit(pcoin);
1086         }
1087     }
1088     return nTotal;
1089 }
1090
1091 // populate vCoins with vector of spendable COutputs
1092 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
1093 {
1094     vCoins.clear();
1095
1096     {
1097         LOCK(cs_wallet);
1098         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1099         {
1100             const CWalletTx* pcoin = &(*it).second;
1101
1102             if (!pcoin->IsFinal())
1103                 continue;
1104
1105             if (fOnlyConfirmed && !pcoin->IsTrusted())
1106                 continue;
1107
1108             if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1109                 continue;
1110
1111             if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1112                 continue;
1113
1114             for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1115                 isminetype mine = IsMine(pcoin->vout[i]);
1116                 if (!(pcoin->IsSpent(i)) && mine != MINE_NO && 
1117                     pcoin->vout[i].nValue >= nMinimumInputValue &&
1118                     (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1119                 {
1120                     vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1121                 }
1122             }
1123         }
1124     }
1125 }
1126
1127 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
1128 {
1129     vCoins.clear();
1130
1131     {
1132         LOCK(cs_wallet);
1133         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1134         {
1135             const CWalletTx* pcoin = &(*it).second;
1136
1137             if (!pcoin->IsFinal())
1138                 continue;
1139
1140             if(pcoin->GetDepthInMainChain() < nConf)
1141                 continue;
1142
1143             for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1144                 isminetype mine = IsMine(pcoin->vout[i]);
1145
1146                 if (!(pcoin->IsSpent(i)) && mine != MINE_NO && pcoin->vout[i].nValue >= nMinimumInputValue)
1147                     vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain(), mine == MINE_SPENDABLE));
1148             }
1149         }
1150     }
1151 }
1152
1153 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1154                                   vector<char>& vfBest, int64& nBest, int iterations = 1000)
1155 {
1156     vector<char> vfIncluded;
1157
1158     vfBest.assign(vValue.size(), true);
1159     nBest = nTotalLower;
1160
1161     for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1162     {
1163         vfIncluded.assign(vValue.size(), false);
1164         int64 nTotal = 0;
1165         bool fReachedTarget = false;
1166         for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1167         {
1168             for (unsigned int i = 0; i < vValue.size(); i++)
1169             {
1170                 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1171                 {
1172                     nTotal += vValue[i].first;
1173                     vfIncluded[i] = true;
1174                     if (nTotal >= nTargetValue)
1175                     {
1176                         fReachedTarget = true;
1177                         if (nTotal < nBest)
1178                         {
1179                             nBest = nTotal;
1180                             vfBest = vfIncluded;
1181                         }
1182                         nTotal -= vValue[i].first;
1183                         vfIncluded[i] = false;
1184                     }
1185                 }
1186             }
1187         }
1188     }
1189 }
1190
1191 // ppcoin: total coins staked (non-spendable until maturity)
1192 int64 CWallet::GetStake() const
1193 {
1194     int64 nTotal = 0;
1195     LOCK(cs_wallet);
1196     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1197     {
1198         const CWalletTx* pcoin = &(*it).second;
1199         if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1200             nTotal += CWallet::GetCredit(*pcoin);
1201     }
1202     return nTotal;
1203 }
1204
1205 int64 CWallet::GetNewMint() const
1206 {
1207     int64 nTotal = 0;
1208     LOCK(cs_wallet);
1209     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1210     {
1211         const CWalletTx* pcoin = &(*it).second;
1212         if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1213             nTotal += CWallet::GetCredit(*pcoin);
1214     }
1215     return nTotal;
1216 }
1217
1218 bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1219 {
1220     setCoinsRet.clear();
1221     nValueRet = 0;
1222
1223     // List of values less than target
1224     pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1225     coinLowestLarger.first = std::numeric_limits<int64>::max();
1226     coinLowestLarger.second.first = NULL;
1227     vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1228     int64 nTotalLower = 0;
1229
1230     random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1231
1232     BOOST_FOREACH(const COutput &output, vCoins)
1233     {
1234         if (!output.fSpendable)
1235             continue;
1236
1237         const CWalletTx *pcoin = output.tx;
1238
1239         if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
1240             continue;
1241
1242         int i = output.i;
1243
1244         // Follow the timestamp rules
1245         if (pcoin->nTime > nSpendTime)
1246             continue;
1247
1248         int64 n = pcoin->vout[i].nValue;
1249
1250         pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1251
1252         if (n == nTargetValue)
1253         {
1254             setCoinsRet.insert(coin.second);
1255             nValueRet += coin.first;
1256             return true;
1257         }
1258         else if (n < nTargetValue + CENT)
1259         {
1260             vValue.push_back(coin);
1261             nTotalLower += n;
1262         }
1263         else if (n < coinLowestLarger.first)
1264         {
1265             coinLowestLarger = coin;
1266         }
1267     }
1268
1269     if (nTotalLower == nTargetValue)
1270     {
1271         for (unsigned int i = 0; i < vValue.size(); ++i)
1272         {
1273             setCoinsRet.insert(vValue[i].second);
1274             nValueRet += vValue[i].first;
1275         }
1276         return true;
1277     }
1278
1279     if (nTotalLower < nTargetValue)
1280     {
1281         if (coinLowestLarger.second.first == NULL)
1282             return false;
1283         setCoinsRet.insert(coinLowestLarger.second);
1284         nValueRet += coinLowestLarger.first;
1285         return true;
1286     }
1287
1288     // Solve subset sum by stochastic approximation
1289     sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1290     vector<char> vfBest;
1291     int64 nBest;
1292
1293     ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1294     if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1295         ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1296
1297     // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1298     //                                   or the next bigger coin is closer), return the bigger coin
1299     if (coinLowestLarger.second.first &&
1300         ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1301     {
1302         setCoinsRet.insert(coinLowestLarger.second);
1303         nValueRet += coinLowestLarger.first;
1304     }
1305     else {
1306         for (unsigned int i = 0; i < vValue.size(); i++)
1307             if (vfBest[i])
1308             {
1309                 setCoinsRet.insert(vValue[i].second);
1310                 nValueRet += vValue[i].first;
1311             }
1312
1313         if (fDebug && GetBoolArg("-printpriority"))
1314         {
1315             //// debug print
1316             printf("SelectCoins() best subset: ");
1317             for (unsigned int i = 0; i < vValue.size(); i++)
1318                 if (vfBest[i])
1319                     printf("%s ", FormatMoney(vValue[i].first).c_str());
1320             printf("total %s\n", FormatMoney(nBest).c_str());
1321         }
1322     }
1323
1324     return true;
1325 }
1326
1327 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const
1328 {
1329     vector<COutput> vCoins;
1330     AvailableCoins(vCoins, true, coinControl);
1331
1332     // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1333     if (coinControl && coinControl->HasSelected())
1334     {
1335         BOOST_FOREACH(const COutput& out, vCoins)
1336         {
1337             if(!out.fSpendable)
1338                 continue;
1339             nValueRet += out.tx->vout[out.i].nValue;
1340             setCoinsRet.insert(make_pair(out.tx, out.i));
1341         }
1342         return (nValueRet >= nTargetValue);
1343     }
1344
1345     return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1346             SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1347             SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1348 }
1349
1350 // Select some coins without random shuffle or best subset approximation
1351 bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1352 {
1353     vector<COutput> vCoins;
1354     AvailableCoinsMinConf(vCoins, nMinConf);
1355
1356     setCoinsRet.clear();
1357     nValueRet = 0;
1358
1359     BOOST_FOREACH(COutput output, vCoins)
1360     {
1361         if(!output.fSpendable)
1362             continue;
1363         const CWalletTx *pcoin = output.tx;
1364         int i = output.i;
1365
1366         // Stop if we've chosen enough inputs
1367         if (nValueRet >= nTargetValue)
1368             break;
1369
1370         // Follow the timestamp rules
1371         if (pcoin->nTime > nSpendTime)
1372             continue;
1373
1374         int64 n = pcoin->vout[i].nValue;
1375
1376         pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1377
1378         if (n >= nTargetValue)
1379         {
1380             // If input value is greater or equal to target then simply insert
1381             //    it into the current subset and exit
1382             setCoinsRet.insert(coin.second);
1383             nValueRet += coin.first;
1384             break;
1385         }
1386         else if (n < nTargetValue + CENT)
1387         {
1388             setCoinsRet.insert(coin.second);
1389             nValueRet += coin.first;
1390         }
1391     }
1392
1393     return true;
1394 }
1395
1396 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1397 {
1398     int64 nValue = 0;
1399     BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1400     {
1401         if (nValue < 0)
1402             return false;
1403         nValue += s.second;
1404     }
1405     if (vecSend.empty() || nValue < 0)
1406         return false;
1407
1408     wtxNew.BindWallet(this);
1409
1410     {
1411         LOCK2(cs_main, cs_wallet);
1412         // txdb must be opened before the mapWallet lock
1413         CTxDB txdb("r");
1414         {
1415             nFeeRet = nTransactionFee;
1416             while (true)
1417             {
1418                 wtxNew.vin.clear();
1419                 wtxNew.vout.clear();
1420                 wtxNew.fFromMe = true;
1421
1422                 int64 nTotalValue = nValue + nFeeRet;
1423                 double dPriority = 0;
1424                 // vouts to the payees
1425                 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1426                     wtxNew.vout.push_back(CTxOut(s.second, s.first));
1427
1428                 // Choose coins to use
1429                 set<pair<const CWalletTx*,unsigned int> > setCoins;
1430                 int64 nValueIn = 0;
1431                 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1432                     return false;
1433                 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1434                 {
1435                     int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1436                     dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1437                 }
1438
1439                 int64 nChange = nValueIn - nValue - nFeeRet;
1440                 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1441                 // or until nChange becomes zero
1442                 // NOTE: this depends on the exact behaviour of GetMinFee
1443                 if (wtxNew.nTime < FEE_SWITCH_TIME && !fTestNet)
1444                 {
1445                     if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1446                     {
1447                         int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1448                         nChange -= nMoveToFee;
1449                         nFeeRet += nMoveToFee;
1450                     }
1451
1452                     // sub-cent change is moved to fee
1453                     if (nChange > 0 && nChange < CENT)
1454                     {
1455                         nFeeRet += nChange;
1456                         nChange = 0;
1457                     }
1458                 }
1459
1460                 if (nChange > 0)
1461                 {
1462                     // Fill a vout to ourself
1463                     // TODO: pass in scriptChange instead of reservekey so
1464                     // change transaction isn't always pay-to-bitcoin-address
1465                     CScript scriptChange;
1466
1467                     // coin control: send change to custom address
1468                     if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1469                         scriptChange.SetDestination(coinControl->destChange);
1470
1471                     // no coin control: send change to newly generated address
1472                     else
1473                     {
1474                         // Note: We use a new key here to keep it from being obvious which side is the change.
1475                         //  The drawback is that by not reusing a previous key, the change may be lost if a
1476                         //  backup is restored, if the backup doesn't have the new private key for the change.
1477                         //  If we reused the old key, it would be possible to add code to look for and
1478                         //  rediscover unknown transactions that were written with keys of ours to recover
1479                         //  post-backup change.
1480
1481                         // Reserve a new key pair from key pool
1482                         CPubKey vchPubKey = reservekey.GetReservedKey();
1483
1484                         scriptChange.SetDestination(vchPubKey.GetID());
1485                     }
1486
1487                     // Insert change txn at random position:
1488                     vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1489                     wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1490                 }
1491                 else
1492                     reservekey.ReturnKey();
1493
1494                 // Fill vin
1495                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1496                     wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1497
1498                 // Sign
1499                 int nIn = 0;
1500                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1501                     if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1502                         return false;
1503
1504                 // Limit size
1505                 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1506                 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1507                     return false;
1508                 dPriority /= nBytes;
1509
1510                 // Check that enough fee is included
1511                 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1512                 bool fAllowFree = CTransaction::AllowFree(dPriority);
1513
1514                 // Disable free transactions until 1 July 2014
1515                 if (!fTestNet && wtxNew.nTime < FEE_SWITCH_TIME)
1516                 {
1517                     fAllowFree = false;
1518                 }
1519
1520                 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1521
1522                 if (nFeeRet < max(nPayFee, nMinFee))
1523                 {
1524                     nFeeRet = max(nPayFee, nMinFee);
1525                     continue;
1526                 }
1527
1528                 // Fill vtxPrev by copying from previous transactions vtxPrev
1529                 wtxNew.AddSupportingTransactions(txdb);
1530                 wtxNew.fTimeReceivedIsTxTime = true;
1531
1532                 break;
1533             }
1534         }
1535     }
1536     return true;
1537 }
1538
1539 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1540 {
1541     vector< pair<CScript, int64> > vecSend;
1542     vecSend.push_back(make_pair(scriptPubKey, nValue));
1543     return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1544 }
1545
1546 void CWallet::GetStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight)
1547 {
1548     int64 nTimeWeight = GetWeight(nTime, (int64)GetTime());
1549
1550     // If time weight is lower or equal to zero then weight is zero.
1551     if (nTimeWeight <= 0)
1552     {
1553         nWeight = 0;
1554         return;
1555     }
1556
1557     CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1558     nWeight = bnCoinDayWeight.getuint64();
1559 }
1560
1561
1562 // NovaCoin: get current stake weight
1563 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1564 {
1565     // Choose coins to use
1566     int64 nBalance = GetBalance();
1567     int64 nReserveBalance = 0;
1568
1569     if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1570     {
1571         error("GetStakeWeight : invalid reserve balance amount");
1572         return false;
1573     }
1574
1575     if (nBalance <= nReserveBalance)
1576         return false;
1577
1578     vector<const CWalletTx*> vwtxPrev;
1579
1580 /*
1581  * TODO: performance comparison
1582
1583     static set<pair<const CWalletTx*,unsigned int> > setCoins;
1584     static uint256 hashPrevBlock;
1585     static int64 nValueIn = 0;
1586
1587     // Cache outputs unless best block changed
1588     if (hashPrevBlock != pindexBest->GetBlockHash())
1589     {
1590         if (!SelectCoinsSimple(nBalance - nReserveBalance, GetAdjustedTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1591             return false;
1592
1593         if (setCoins.empty())
1594             return false;
1595
1596         hashPrevBlock == pindexBest->GetBlockHash();
1597     }
1598 */
1599
1600     set<pair<const CWalletTx*,unsigned int> > setCoins;
1601     int64 nValueIn = 0;
1602
1603     if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1604         return false;
1605
1606     if (setCoins.empty())
1607         return false;
1608
1609     CTxDB txdb("r");
1610     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1611     {
1612         CTxIndex txindex;
1613         {
1614             LOCK2(cs_main, cs_wallet);
1615             if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1616                 continue;
1617         }
1618
1619         int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1620         CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1621
1622         // Weight is greater than zero
1623         if (nTimeWeight > 0)
1624         {
1625             nWeight += bnCoinDayWeight.getuint64();
1626         }
1627
1628         // Weight is greater than zero, but the maximum value isn't reached yet
1629         if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1630         {
1631             nMinWeight += bnCoinDayWeight.getuint64();
1632         }
1633
1634         // Maximum weight was reached
1635         if (nTimeWeight == nStakeMaxAge)
1636         {
1637             nMaxWeight += bnCoinDayWeight.getuint64();
1638         }
1639     }
1640
1641     return true;
1642 }
1643
1644 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1645 {
1646     // The following combine threshold is important to security
1647     // Should not be adjusted if you don't understand the consequences
1648     int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1649
1650     CBigNum bnTargetPerCoinDay;
1651     bnTargetPerCoinDay.SetCompact(nBits);
1652
1653     txNew.vin.clear();
1654     txNew.vout.clear();
1655
1656     // Mark coin stake transaction
1657     CScript scriptEmpty;
1658     scriptEmpty.clear();
1659     txNew.vout.push_back(CTxOut(0, scriptEmpty));
1660
1661     // Choose coins to use
1662     int64 nBalance = GetBalance();
1663     int64 nReserveBalance = 0;
1664
1665     if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1666         return error("CreateCoinStake : invalid reserve balance amount");
1667
1668     if (nBalance <= nReserveBalance)
1669         return false;
1670
1671     vector<const CWalletTx*> vwtxPrev;
1672
1673 /*
1674  * TODO: performance comparison
1675
1676     static set<pair<const CWalletTx*,unsigned int> > setCoins;
1677     static uint256 hashPrevBlock;
1678     static int64 nValueIn = 0;
1679
1680     // Cache outputs unless best block changed
1681     if (hashPrevBlock != pindexBest->GetBlockHash())
1682     {
1683         if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1684             return false;
1685
1686         if (setCoins.empty())
1687             return false;
1688
1689         hashPrevBlock == pindexBest->GetBlockHash();
1690     }
1691 */
1692
1693     set<pair<const CWalletTx*,unsigned int> > setCoins;
1694     int64 nValueIn = 0;
1695
1696     // Select coins with suitable depth
1697     if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1698         return false;
1699
1700     if (setCoins.empty())
1701         return false;
1702
1703     int64 nCredit = 0;
1704     CScript scriptPubKeyKernel;
1705     CTxDB txdb("r");
1706     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1707     {
1708         CTxIndex txindex;
1709         {
1710             LOCK2(cs_main, cs_wallet);
1711             if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1712                 continue;
1713         }
1714
1715         // Read block header
1716         CBlock block;
1717         {
1718             LOCK2(cs_main, cs_wallet);
1719             if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1720                 continue;
1721         }
1722
1723         static int nMaxStakeSearchInterval = 60;
1724         if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1725             continue; // only count coins meeting min age requirement
1726
1727         bool fKernelFound = false;
1728         for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
1729         {
1730             // Search backward in time from the given txNew timestamp 
1731             // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1732             uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1733             COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1734             if (CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake))
1735             {
1736                 // Found a kernel
1737                 if (fDebug && GetBoolArg("-printcoinstake"))
1738                     printf("CreateCoinStake : kernel found\n");
1739                 vector<valtype> vSolutions;
1740                 txnouttype whichType;
1741                 CScript scriptPubKeyOut;
1742                 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1743                 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1744                 {
1745                     if (fDebug && GetBoolArg("-printcoinstake"))
1746                         printf("CreateCoinStake : failed to parse kernel\n");
1747                     break;
1748                 }
1749                 if (fDebug && GetBoolArg("-printcoinstake"))
1750                     printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1751                 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1752                 {
1753                     if (fDebug && GetBoolArg("-printcoinstake"))
1754                         printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1755                     break;  // only support pay to public key and pay to address
1756                 }
1757                 if (whichType == TX_PUBKEYHASH) // pay to address type
1758                 {
1759                     // convert to pay to public key type
1760                     if (!keystore.GetKey(uint160(vSolutions[0]), key))
1761                     {
1762                         if (fDebug && GetBoolArg("-printcoinstake"))
1763                             printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1764                         break;  // unable to find corresponding public key
1765                     }
1766                     scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1767                 }
1768                 if (whichType == TX_PUBKEY)
1769                 {
1770                     valtype& vchPubKey = vSolutions[0];
1771                     if (!keystore.GetKey(Hash160(vchPubKey), key))
1772                     {
1773                         if (fDebug && GetBoolArg("-printcoinstake"))
1774                             printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1775                         break;  // unable to find corresponding public key
1776                     }
1777
1778                 if (key.GetPubKey() != vchPubKey)
1779                 {
1780                     if (fDebug && GetBoolArg("-printcoinstake"))
1781                         printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1782                         break; // keys mismatch
1783                     }
1784
1785                     scriptPubKeyOut = scriptPubKeyKernel;
1786                 }
1787
1788                 txNew.nTime -= n;
1789                 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1790                 nCredit += pcoin.first->vout[pcoin.second].nValue;
1791                 vwtxPrev.push_back(pcoin.first);
1792                 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1793
1794                 if (GetWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeMaxAge)
1795                     txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1796                 if (fDebug && GetBoolArg("-printcoinstake"))
1797                     printf("CreateCoinStake : added kernel type=%d\n", whichType);
1798                 fKernelFound = true;
1799                 break;
1800             }
1801         }
1802
1803         if (fKernelFound || fShutdown)
1804             break; // if kernel is found stop searching
1805     }
1806
1807     if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1808         return false;
1809
1810     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1811     {
1812         // Attempt to add more inputs
1813         // Only add coins of the same key/address as kernel
1814         if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1815             && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1816         {
1817             int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
1818
1819             // Stop adding more inputs if already too many inputs
1820             if (txNew.vin.size() >= 100)
1821                 break;
1822             // Stop adding more inputs if value is already pretty significant
1823             if (nCredit > nCombineThreshold)
1824                 break;
1825             // Stop adding inputs if reached reserve limit
1826             if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1827                 break;
1828             // Do not add additional significant input
1829             if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1830                 continue;
1831             // Do not add input that is still too young
1832             if (nTimeWeight < nStakeMaxAge)
1833                 continue;
1834
1835             txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1836             nCredit += pcoin.first->vout[pcoin.second].nValue;
1837             vwtxPrev.push_back(pcoin.first);
1838         }
1839     }
1840
1841     // Calculate coin age reward
1842     {
1843         uint64 nCoinAge;
1844         CTxDB txdb("r");
1845         if (!txNew.GetCoinAge(txdb, nCoinAge))
1846             return error("CreateCoinStake : failed to calculate coin age");
1847         nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1848     }
1849
1850     int64 nMinFee = 0;
1851     while (true)
1852     {
1853         // Set output amount
1854         if (txNew.vout.size() == 3)
1855         {
1856             txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1857             txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1858         }
1859         else
1860             txNew.vout[1].nValue = nCredit - nMinFee;
1861
1862         // Sign
1863         int nIn = 0;
1864         BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1865         {
1866             if (!SignSignature(*this, *pcoin, txNew, nIn++))
1867                 return error("CreateCoinStake : failed to sign coinstake");
1868         }
1869
1870         // Limit size
1871         unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1872         if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1873             return error("CreateCoinStake : exceeded coinstake size limit");
1874
1875         // Check enough fee is paid
1876         if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
1877         {
1878             nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
1879             continue; // try signing again
1880         }
1881         else
1882         {
1883             if (fDebug && GetBoolArg("-printfee"))
1884                 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1885             break;
1886         }
1887     }
1888
1889     // Successfully generated coinstake
1890     return true;
1891 }
1892
1893
1894 // Call after CreateTransaction unless you want to abort
1895 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1896 {
1897     {
1898         LOCK2(cs_main, cs_wallet);
1899         printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1900         {
1901             // This is only to keep the database open to defeat the auto-flush for the
1902             // duration of this scope.  This is the only place where this optimization
1903             // maybe makes sense; please don't do it anywhere else.
1904             CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1905
1906             // Take key pair from key pool so it won't be used again
1907             reservekey.KeepKey();
1908
1909             // Add tx to wallet, because if it has change it's also ours,
1910             // otherwise just for transaction history.
1911             AddToWallet(wtxNew);
1912
1913             // Mark old coins as spent
1914             set<CWalletTx*> setCoins;
1915             BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1916             {
1917                 CWalletTx &coin = mapWallet[txin.prevout.hash];
1918                 coin.BindWallet(this);
1919                 coin.MarkSpent(txin.prevout.n);
1920                 coin.WriteToDisk();
1921                 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1922             }
1923
1924             if (fFileBacked)
1925                 delete pwalletdb;
1926         }
1927
1928         // Track how many getdata requests our transaction gets
1929         mapRequestCount[wtxNew.GetHash()] = 0;
1930
1931         // Broadcast
1932         if (!wtxNew.AcceptToMemoryPool())
1933         {
1934             // This must not fail. The transaction has already been signed and recorded.
1935             printf("CommitTransaction() : Error: Transaction not valid");
1936             return false;
1937         }
1938         wtxNew.RelayWalletTransaction();
1939     }
1940     return true;
1941 }
1942
1943
1944
1945
1946 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1947 {
1948     CReserveKey reservekey(this);
1949     int64 nFeeRequired;
1950
1951     if (IsLocked())
1952     {
1953         string strError = _("Error: Wallet locked, unable to create transaction  ");
1954         printf("SendMoney() : %s", strError.c_str());
1955         return strError;
1956     }
1957     if (fWalletUnlockMintOnly)
1958     {
1959         string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1960         printf("SendMoney() : %s", strError.c_str());
1961         return strError;
1962     }
1963     if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1964     {
1965         string strError;
1966         if (nValue + nFeeRequired > GetBalance())
1967             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).c_str());
1968         else
1969             strError = _("Error: Transaction creation failed  ");
1970         printf("SendMoney() : %s", strError.c_str());
1971         return strError;
1972     }
1973
1974     if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1975         return "ABORTED";
1976
1977     if (!CommitTransaction(wtxNew, reservekey))
1978         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.");
1979
1980     return "";
1981 }
1982
1983
1984
1985 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1986 {
1987     // Check amount
1988     if (nValue <= 0)
1989         return _("Invalid amount");
1990     if (nValue + nTransactionFee > GetBalance())
1991         return _("Insufficient funds");
1992
1993     // Parse Bitcoin address
1994     CScript scriptPubKey;
1995     scriptPubKey.SetDestination(address);
1996
1997     return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1998 }
1999
2000
2001
2002
2003 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2004 {
2005     if (!fFileBacked)
2006         return DB_LOAD_OK;
2007     fFirstRunRet = false;
2008     DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2009     if (nLoadWalletRet == DB_NEED_REWRITE)
2010     {
2011         if (CDB::Rewrite(strWalletFile, "\x04pool"))
2012         {
2013             setKeyPool.clear();
2014             // Note: can't top-up keypool here, because wallet is locked.
2015             // User will be prompted to unlock wallet the next operation
2016             // the requires a new key.
2017         }
2018     }
2019
2020     if (nLoadWalletRet != DB_LOAD_OK)
2021         return nLoadWalletRet;
2022     fFirstRunRet = !vchDefaultKey.IsValid();
2023
2024     NewThread(ThreadFlushWalletDB, &strWalletFile);
2025     return DB_LOAD_OK;
2026 }
2027
2028
2029 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2030 {
2031     std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2032     mapAddressBook[address] = strName;
2033     NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2034     if (!fFileBacked)
2035         return false;
2036     return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2037 }
2038
2039 bool CWallet::DelAddressBookName(const CTxDestination& address)
2040 {
2041     mapAddressBook.erase(address);
2042     NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2043     if (!fFileBacked)
2044         return false;
2045     return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2046 }
2047
2048
2049 void CWallet::PrintWallet(const CBlock& block)
2050 {
2051     {
2052         LOCK(cs_wallet);
2053         if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
2054         {
2055             CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2056             printf("    mine:  %d  %d  %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(false));
2057         }
2058         if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2059         {
2060             CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2061             printf("    stake: %d  %d  %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit(false));
2062          }
2063
2064     }
2065     printf("\n");
2066 }
2067
2068 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2069 {
2070     {
2071         LOCK(cs_wallet);
2072         map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2073         if (mi != mapWallet.end())
2074         {
2075             wtx = (*mi).second;
2076             return true;
2077         }
2078     }
2079     return false;
2080 }
2081
2082 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2083 {
2084     if (fFileBacked)
2085     {
2086         if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2087             return false;
2088     }
2089     vchDefaultKey = vchPubKey;
2090     return true;
2091 }
2092
2093 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2094 {
2095     if (!pwallet->fFileBacked)
2096         return false;
2097     strWalletFileOut = pwallet->strWalletFile;
2098     return true;
2099 }
2100
2101 //
2102 // Mark old keypool keys as used,
2103 // and generate all new keys
2104 //
2105 bool CWallet::NewKeyPool()
2106 {
2107     {
2108         LOCK(cs_wallet);
2109         CWalletDB walletdb(strWalletFile);
2110         BOOST_FOREACH(int64 nIndex, setKeyPool)
2111             walletdb.ErasePool(nIndex);
2112         setKeyPool.clear();
2113
2114         if (IsLocked())
2115             return false;
2116
2117         int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
2118         for (int i = 0; i < nKeys; i++)
2119         {
2120             int64 nIndex = i+1;
2121             walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2122             setKeyPool.insert(nIndex);
2123         }
2124         printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
2125     }
2126     return true;
2127 }
2128
2129 bool CWallet::TopUpKeyPool(unsigned int nSize)
2130 {
2131     {
2132         LOCK(cs_wallet);
2133
2134         if (IsLocked())
2135             return false;
2136
2137         CWalletDB walletdb(strWalletFile);
2138
2139         // Top up key pool
2140         unsigned int nTargetSize;
2141         if (nSize > 0)
2142             nTargetSize = nSize;
2143         else
2144             nTargetSize = max(GetArg("-keypool", 100), 0LL);
2145
2146         while (setKeyPool.size() < (nTargetSize + 1))
2147         {
2148             int64 nEnd = 1;
2149             if (!setKeyPool.empty())
2150                 nEnd = *(--setKeyPool.end()) + 1;
2151             if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2152                 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2153             setKeyPool.insert(nEnd);
2154             printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2155         }
2156     }
2157     return true;
2158 }
2159
2160 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2161 {
2162     nIndex = -1;
2163     keypool.vchPubKey = CPubKey();
2164     {
2165         LOCK(cs_wallet);
2166
2167         if (!IsLocked())
2168             TopUpKeyPool();
2169
2170         // Get the oldest key
2171         if(setKeyPool.empty())
2172             return;
2173
2174         CWalletDB walletdb(strWalletFile);
2175
2176         nIndex = *(setKeyPool.begin());
2177         setKeyPool.erase(setKeyPool.begin());
2178         if (!walletdb.ReadPool(nIndex, keypool))
2179             throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2180         if (!HaveKey(keypool.vchPubKey.GetID()))
2181             throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2182         assert(keypool.vchPubKey.IsValid());
2183         if (fDebug && GetBoolArg("-printkeypool"))
2184             printf("keypool reserve %"PRI64d"\n", nIndex);
2185     }
2186 }
2187
2188 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2189 {
2190     {
2191         LOCK2(cs_main, cs_wallet);
2192         CWalletDB walletdb(strWalletFile);
2193
2194         int64 nIndex = 1 + *(--setKeyPool.end());
2195         if (!walletdb.WritePool(nIndex, keypool))
2196             throw runtime_error("AddReserveKey() : writing added key failed");
2197         setKeyPool.insert(nIndex);
2198         return nIndex;
2199     }
2200     return -1;
2201 }
2202
2203 void CWallet::KeepKey(int64 nIndex)
2204 {
2205     // Remove from key pool
2206     if (fFileBacked)
2207     {
2208         CWalletDB walletdb(strWalletFile);
2209         walletdb.ErasePool(nIndex);
2210     }
2211     if(fDebug)
2212         printf("keypool keep %"PRI64d"\n", nIndex);
2213 }
2214
2215 void CWallet::ReturnKey(int64 nIndex)
2216 {
2217     // Return to key pool
2218     {
2219         LOCK(cs_wallet);
2220         setKeyPool.insert(nIndex);
2221     }
2222     if(fDebug)
2223         printf("keypool return %"PRI64d"\n", nIndex);
2224 }
2225
2226 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2227 {
2228     int64 nIndex = 0;
2229     CKeyPool keypool;
2230     {
2231         LOCK(cs_wallet);
2232         ReserveKeyFromKeyPool(nIndex, keypool);
2233         if (nIndex == -1)
2234         {
2235             if (fAllowReuse && vchDefaultKey.IsValid())
2236             {
2237                 result = vchDefaultKey;
2238                 return true;
2239             }
2240             if (IsLocked()) return false;
2241             result = GenerateNewKey();
2242             return true;
2243         }
2244         KeepKey(nIndex);
2245         result = keypool.vchPubKey;
2246     }
2247     return true;
2248 }
2249
2250 int64 CWallet::GetOldestKeyPoolTime()
2251 {
2252     int64 nIndex = 0;
2253     CKeyPool keypool;
2254     ReserveKeyFromKeyPool(nIndex, keypool);
2255     if (nIndex == -1)
2256         return GetTime();
2257     ReturnKey(nIndex);
2258     return keypool.nTime;
2259 }
2260
2261 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2262 {
2263     map<CTxDestination, int64> balances;
2264
2265     {
2266         LOCK(cs_wallet);
2267         BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2268         {
2269             CWalletTx *pcoin = &walletEntry.second;
2270
2271             if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2272                 continue;
2273
2274             if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2275                 continue;
2276
2277             int nDepth = pcoin->GetDepthInMainChain();
2278             if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
2279                 continue;
2280
2281             for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2282             {
2283                 CTxDestination addr;
2284                 if (!IsMine(pcoin->vout[i]))
2285                     continue;
2286                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2287                     continue;
2288
2289                 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2290
2291                 if (!balances.count(addr))
2292                     balances[addr] = 0;
2293                 balances[addr] += n;
2294             }
2295         }
2296     }
2297
2298     return balances;
2299 }
2300
2301 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2302 {
2303     set< set<CTxDestination> > groupings;
2304     set<CTxDestination> grouping;
2305
2306     BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2307     {
2308         CWalletTx *pcoin = &walletEntry.second;
2309
2310         if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2311         {
2312             // group all input addresses with each other
2313             BOOST_FOREACH(CTxIn txin, pcoin->vin)
2314             {
2315                 CTxDestination address;
2316                 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2317                     continue;
2318                 grouping.insert(address);
2319             }
2320
2321             // group change with input addresses
2322             BOOST_FOREACH(CTxOut txout, pcoin->vout)
2323                 if (IsChange(txout))
2324                 {
2325                     CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2326                     CTxDestination txoutAddr;
2327                     if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2328                         continue;
2329                     grouping.insert(txoutAddr);
2330                 }
2331             groupings.insert(grouping);
2332             grouping.clear();
2333         }
2334
2335         // group lone addrs by themselves
2336         for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2337             if (IsMine(pcoin->vout[i]))
2338             {
2339                 CTxDestination address;
2340                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2341                     continue;
2342                 grouping.insert(address);
2343                 groupings.insert(grouping);
2344                 grouping.clear();
2345             }
2346     }
2347
2348     set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2349     map< CTxDestination, set<CTxDestination>* > setmap;  // map addresses to the unique group containing it
2350     BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2351     {
2352         // make a set of all the groups hit by this new group
2353         set< set<CTxDestination>* > hits;
2354         map< CTxDestination, set<CTxDestination>* >::iterator it;
2355         BOOST_FOREACH(CTxDestination address, grouping)
2356             if ((it = setmap.find(address)) != setmap.end())
2357                 hits.insert((*it).second);
2358
2359         // merge all hit groups into a new single group and delete old groups
2360         set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2361         BOOST_FOREACH(set<CTxDestination>* hit, hits)
2362         {
2363             merged->insert(hit->begin(), hit->end());
2364             uniqueGroupings.erase(hit);
2365             delete hit;
2366         }
2367         uniqueGroupings.insert(merged);
2368
2369         // update setmap
2370         BOOST_FOREACH(CTxDestination element, *merged)
2371             setmap[element] = merged;
2372     }
2373
2374     set< set<CTxDestination> > ret;
2375     BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2376     {
2377         ret.insert(*uniqueGrouping);
2378         delete uniqueGrouping;
2379     }
2380
2381     return ret;
2382 }
2383
2384 // ppcoin: check 'spent' consistency between wallet and txindex
2385 // ppcoin: fix wallet spent state according to txindex
2386 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2387 {
2388     nMismatchFound = 0;
2389     nBalanceInQuestion = 0;
2390
2391     LOCK(cs_wallet);
2392     vector<CWalletTx*> vCoins;
2393     vCoins.reserve(mapWallet.size());
2394     for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2395         vCoins.push_back(&(*it).second);
2396
2397     CTxDB txdb("r");
2398     BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2399     {
2400         // Find the corresponding transaction index
2401         CTxIndex txindex;
2402         if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2403             continue;
2404         for (unsigned int n=0; n < pcoin->vout.size(); n++)
2405         {
2406             if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2407             {
2408                 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2409                     FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2410                 nMismatchFound++;
2411                 nBalanceInQuestion += pcoin->vout[n].nValue;
2412                 if (!fCheckOnly)
2413                 {
2414                     pcoin->MarkUnspent(n);
2415                     pcoin->WriteToDisk();
2416                 }
2417             }
2418             else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2419             {
2420                 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2421                     FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2422                 nMismatchFound++;
2423                 nBalanceInQuestion += pcoin->vout[n].nValue;
2424                 if (!fCheckOnly)
2425                 {
2426                     pcoin->MarkSpent(n);
2427                     pcoin->WriteToDisk();
2428                 }
2429             }
2430
2431         }
2432
2433         if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2434         {
2435             printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2436             if (!fCheckOnly)
2437             {
2438                 EraseFromWallet(pcoin->GetHash());
2439             }
2440         }
2441     }
2442 }
2443
2444 // ppcoin: disable transaction (only for coinstake)
2445 void CWallet::DisableTransaction(const CTransaction &tx)
2446 {
2447     if (!tx.IsCoinStake() || !IsFromMe(tx))
2448         return; // only disconnecting coinstake requires marking input unspent
2449
2450     LOCK(cs_wallet);
2451     BOOST_FOREACH(const CTxIn& txin, tx.vin)
2452     {
2453         map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2454         if (mi != mapWallet.end())
2455         {
2456             CWalletTx& prev = (*mi).second;
2457             if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2458             {
2459                 prev.MarkUnspent(txin.prevout.n);
2460                 prev.WriteToDisk();
2461             }
2462         }
2463     }
2464 }
2465
2466 CPubKey CReserveKey::GetReservedKey()
2467 {
2468     if (nIndex == -1)
2469     {
2470         CKeyPool keypool;
2471         pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2472         if (nIndex != -1)
2473             vchPubKey = keypool.vchPubKey;
2474         else
2475         {
2476             printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2477             vchPubKey = pwallet->vchDefaultKey;
2478         }
2479     }
2480     assert(vchPubKey.IsValid());
2481     return vchPubKey;
2482 }
2483
2484 void CReserveKey::KeepKey()
2485 {
2486     if (nIndex != -1)
2487         pwallet->KeepKey(nIndex);
2488     nIndex = -1;
2489     vchPubKey = CPubKey();
2490 }
2491
2492 void CReserveKey::ReturnKey()
2493 {
2494     if (nIndex != -1)
2495         pwallet->ReturnKey(nIndex);
2496     nIndex = -1;
2497     vchPubKey = CPubKey();
2498 }
2499
2500 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2501 {
2502     setAddress.clear();
2503
2504     CWalletDB walletdb(strWalletFile);
2505
2506     LOCK2(cs_main, cs_wallet);
2507     BOOST_FOREACH(const int64& id, setKeyPool)
2508     {
2509         CKeyPool keypool;
2510         if (!walletdb.ReadPool(id, keypool))
2511             throw runtime_error("GetAllReserveKeyHashes() : read failed");
2512         assert(keypool.vchPubKey.IsValid());
2513         CKeyID keyID = keypool.vchPubKey.GetID();
2514         if (!HaveKey(keyID))
2515             throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2516         setAddress.insert(keyID);
2517     }
2518 }
2519
2520 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2521 {
2522     {
2523         LOCK(cs_wallet);
2524         // Only notify UI if this transaction is in this wallet
2525         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2526         if (mi != mapWallet.end())
2527             NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2528     }
2529 }
2530
2531 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2532     mapKeyBirth.clear();
2533
2534     // get birth times for keys with metadata
2535     for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2536         if (it->second.nCreateTime)
2537             mapKeyBirth[it->first] = it->second.nCreateTime;
2538
2539     // map in which we'll infer heights of other keys
2540     CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2541     std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2542     std::set<CKeyID> setKeys;
2543     GetKeys(setKeys);
2544     BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2545         if (mapKeyBirth.count(keyid) == 0)
2546             mapKeyFirstBlock[keyid] = pindexMax;
2547     }
2548     setKeys.clear();
2549
2550     // if there are no such keys, we're done
2551     if (mapKeyFirstBlock.empty())
2552         return;
2553
2554     // find first block that affects those keys, if there are any left
2555     std::vector<CKeyID> vAffected;
2556     for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2557         // iterate over all wallet transactions...
2558         const CWalletTx &wtx = (*it).second;
2559         std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2560         if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2561             // ... which are already in a block
2562             int nHeight = blit->second->nHeight;
2563             BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2564                 // iterate over all their outputs
2565                 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2566                 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2567                     // ... and all their affected keys
2568                     std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2569                     if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2570                         rit->second = blit->second;
2571                 }
2572                 vAffected.clear();
2573             }
2574         }
2575     }
2576
2577     // Extract block timestamps for those keys
2578     for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2579         mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off
2580 }