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