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