7045e3c42b5f88a6c2dc54665f92f6a232944893
[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         // Ignore immature coins
1419         if (pcoin->GetBlocksToMaturity() > 0)
1420             continue;
1421
1422         // Stop if we've chosen enough inputs
1423         if (nValueRet >= nTargetValue)
1424             break;
1425
1426         // Follow the timestamp rules
1427         if (pcoin->nTime > nSpendTime)
1428             continue;
1429
1430         int64 n = pcoin->vout[i].nValue;
1431
1432         pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1433
1434         if (n >= nTargetValue)
1435         {
1436             // If input value is greater or equal to target then simply insert
1437             //    it into the current subset and exit
1438             setCoinsRet.insert(coin.second);
1439             nValueRet += coin.first;
1440             break;
1441         }
1442         else if (n < nTargetValue + CENT)
1443         {
1444             setCoinsRet.insert(coin.second);
1445             nValueRet += coin.first;
1446         }
1447     }
1448
1449     return true;
1450 }
1451
1452 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1453 {
1454     int64 nValue = 0;
1455     BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1456     {
1457         if (nValue < 0)
1458             return false;
1459         nValue += s.second;
1460     }
1461     if (vecSend.empty() || nValue < 0)
1462         return false;
1463
1464     wtxNew.BindWallet(this);
1465
1466     {
1467         LOCK2(cs_main, cs_wallet);
1468         // txdb must be opened before the mapWallet lock
1469         CTxDB txdb("r");
1470         {
1471             nFeeRet = nTransactionFee;
1472             while (true)
1473             {
1474                 wtxNew.vin.clear();
1475                 wtxNew.vout.clear();
1476                 wtxNew.fFromMe = true;
1477
1478                 int64 nTotalValue = nValue + nFeeRet;
1479                 double dPriority = 0;
1480                 // vouts to the payees
1481                 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1482                     wtxNew.vout.push_back(CTxOut(s.second, s.first));
1483
1484                 // Choose coins to use
1485                 set<pair<const CWalletTx*,unsigned int> > setCoins;
1486                 int64 nValueIn = 0;
1487                 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1488                     return false;
1489                 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1490                 {
1491                     int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1492                     dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1493                 }
1494
1495                 int64 nChange = nValueIn - nValue - nFeeRet;
1496                 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1497                 // or until nChange becomes zero
1498                 // NOTE: this depends on the exact behaviour of GetMinFee
1499                 if (wtxNew.nTime < FEE_SWITCH_TIME && !fTestNet)
1500                 {
1501                     if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1502                     {
1503                         int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1504                         nChange -= nMoveToFee;
1505                         nFeeRet += nMoveToFee;
1506                     }
1507
1508                     // sub-cent change is moved to fee
1509                     if (nChange > 0 && nChange < CENT)
1510                     {
1511                         nFeeRet += nChange;
1512                         nChange = 0;
1513                     }
1514                 }
1515
1516                 if (nChange > 0)
1517                 {
1518                     // Fill a vout to ourself
1519                     // TODO: pass in scriptChange instead of reservekey so
1520                     // change transaction isn't always pay-to-bitcoin-address
1521                     CScript scriptChange;
1522
1523                     // coin control: send change to custom address
1524                     if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1525                         scriptChange.SetDestination(coinControl->destChange);
1526
1527                     // no coin control: send change to newly generated address
1528                     else
1529                     {
1530                         // Note: We use a new key here to keep it from being obvious which side is the change.
1531                         //  The drawback is that by not reusing a previous key, the change may be lost if a
1532                         //  backup is restored, if the backup doesn't have the new private key for the change.
1533                         //  If we reused the old key, it would be possible to add code to look for and
1534                         //  rediscover unknown transactions that were written with keys of ours to recover
1535                         //  post-backup change.
1536
1537                         // Reserve a new key pair from key pool
1538                         CPubKey vchPubKey = reservekey.GetReservedKey();
1539
1540                         scriptChange.SetDestination(vchPubKey.GetID());
1541                     }
1542
1543                     // Insert change txn at random position:
1544                     vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1545                     wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1546                 }
1547                 else
1548                     reservekey.ReturnKey();
1549
1550                 // Fill vin
1551                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1552                     wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1553
1554                 // Sign
1555                 int nIn = 0;
1556                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1557                     if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1558                         return false;
1559
1560                 // Limit size
1561                 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1562                 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1563                     return false;
1564                 dPriority /= nBytes;
1565
1566                 // Check that enough fee is included
1567                 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1568                 bool fAllowFree = CTransaction::AllowFree(dPriority);
1569
1570                 // Disable free transactions until 1 July 2014
1571                 if (!fTestNet && wtxNew.nTime < FEE_SWITCH_TIME)
1572                 {
1573                     fAllowFree = false;
1574                 }
1575
1576                 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1577
1578                 if (nFeeRet < max(nPayFee, nMinFee))
1579                 {
1580                     nFeeRet = max(nPayFee, nMinFee);
1581                     continue;
1582                 }
1583
1584                 // Fill vtxPrev by copying from previous transactions vtxPrev
1585                 wtxNew.AddSupportingTransactions(txdb);
1586                 wtxNew.fTimeReceivedIsTxTime = true;
1587
1588                 break;
1589             }
1590         }
1591     }
1592     return true;
1593 }
1594
1595 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1596 {
1597     vector< pair<CScript, int64> > vecSend;
1598     vecSend.push_back(make_pair(scriptPubKey, nValue));
1599     return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1600 }
1601
1602 void CWallet::GetStakeWeightFromValue(const int64& nTime, const int64& nValue, uint64& nWeight)
1603 {
1604     int64 nTimeWeight = GetWeight(nTime, (int64)GetTime());
1605
1606     // If time weight is lower or equal to zero then weight is zero.
1607     if (nTimeWeight <= 0)
1608     {
1609         nWeight = 0;
1610         return;
1611     }
1612
1613     CBigNum bnCoinDayWeight = CBigNum(nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1614     nWeight = bnCoinDayWeight.getuint64();
1615 }
1616
1617
1618 // NovaCoin: get current stake weight
1619 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1620 {
1621     // Choose coins to use
1622     int64 nBalance = GetBalance();
1623     int64 nReserveBalance = 0;
1624
1625     if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1626     {
1627         error("GetStakeWeight : invalid reserve balance amount");
1628         return false;
1629     }
1630
1631     if (nBalance <= nReserveBalance)
1632         return false;
1633
1634     vector<const CWalletTx*> vwtxPrev;
1635
1636 /*
1637  * TODO: performance comparison
1638
1639     static set<pair<const CWalletTx*,unsigned int> > setCoins;
1640     static uint256 hashPrevBlock;
1641     static int64 nValueIn = 0;
1642
1643     // Cache outputs unless best block changed
1644     if (hashPrevBlock != pindexBest->GetBlockHash())
1645     {
1646         if (!SelectCoinsSimple(nBalance - nReserveBalance, GetAdjustedTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1647             return false;
1648
1649         if (setCoins.empty())
1650             return false;
1651
1652         hashPrevBlock == pindexBest->GetBlockHash();
1653     }
1654 */
1655
1656     set<pair<const CWalletTx*,unsigned int> > setCoins;
1657     int64 nValueIn = 0;
1658
1659     // Simple coins selection - no randomization
1660     if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1661         return false;
1662
1663     if (setCoins.empty())
1664         return false;
1665
1666     CTxDB txdb("r");
1667     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1668     {
1669         CTxIndex txindex;
1670         {
1671             LOCK2(cs_main, cs_wallet);
1672             if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1673                 continue;
1674         }
1675
1676         int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1677         CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1678
1679         // Weight is greater than zero
1680         if (nTimeWeight > 0)
1681         {
1682             nWeight += bnCoinDayWeight.getuint64();
1683         }
1684
1685         // Weight is greater than zero, but the maximum value isn't reached yet
1686         if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1687         {
1688             nMinWeight += bnCoinDayWeight.getuint64();
1689         }
1690
1691         // Maximum weight was reached
1692         if (nTimeWeight == nStakeMaxAge)
1693         {
1694             nMaxWeight += bnCoinDayWeight.getuint64();
1695         }
1696     }
1697
1698     return true;
1699 }
1700
1701 bool CWallet::MergeCoins(const int64& nAmount, const int64& nMaxValue, const int64& nOutputValue, list<uint256>& listMerged)
1702 {
1703     int64 nBalance = GetBalance();
1704
1705     if (nAmount > nBalance)
1706         return false;
1707
1708     listMerged.clear();
1709     int64 nValueIn = 0;
1710     set<pair<const CWalletTx*,unsigned int> > setCoins;
1711
1712     // Simple coins selection - no randomization
1713     if (!SelectCoinsSimple(nAmount, GetTime(), 1, setCoins, nValueIn))
1714         return false;
1715
1716     if (setCoins.empty())
1717         return false;
1718
1719     CWalletTx wtxNew;
1720     vector<const CWalletTx*> vwtxPrev;
1721
1722     // Reserve a new key pair from key pool
1723     CReserveKey reservekey(this);
1724     CPubKey vchPubKey = reservekey.GetReservedKey();
1725
1726     // Output script
1727     CScript scriptOutput;
1728     scriptOutput.SetDestination(vchPubKey.GetID());
1729
1730     // Insert output
1731     wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1732
1733     double dWeight = 0;
1734     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1735     {
1736         int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1737
1738         // Ignore coin if credit is too high
1739         if (nCredit >= nMaxValue)
1740             continue;
1741
1742         // Add current coin to inputs list and add its credit to transaction output
1743         wtxNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1744         wtxNew.vout[0].nValue += nCredit;
1745         vwtxPrev.push_back(pcoin.first);
1746
1747 /*
1748         // Replaced with estimation for performance purposes
1749
1750         for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1751             const CWalletTx *txin = vwtxPrev[i];
1752
1753             // Sign scripts to get actual transaction size for fee calculation
1754             if (!SignSignature(*this, *txin, wtxNew, i))
1755                 return false;
1756         }
1757 */
1758
1759         // Assuming that average scriptsig size is 110 bytes
1760         int64 nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1761         dWeight += (double)nCredit * pcoin.first->GetDepthInMainChain();
1762
1763         double dFinalPriority = dWeight /= nBytes;
1764         bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1765
1766         // Get actual transaction fee according to its estimated size and priority
1767         int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1768
1769         // Prepare transaction for commit if sum is enough ot its size is too big
1770         if (nBytes >= MAX_BLOCK_SIZE_GEN/6 || wtxNew.vout[0].nValue >= nOutputValue)
1771         {
1772             wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1773
1774             for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1775                 const CWalletTx *txin = vwtxPrev[i];
1776
1777                 // Sign all scripts
1778                 if (!SignSignature(*this, *txin, wtxNew, i))
1779                     return false;
1780             }
1781
1782             // Try to commit, return false on failure
1783             if (!CommitTransaction(wtxNew, reservekey))
1784                 return false;
1785
1786             listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1787
1788             dWeight = 0;  // Reset all temporary values
1789             vwtxPrev.clear();
1790             wtxNew.SetNull();
1791             wtxNew.vout.push_back(CTxOut(0, scriptOutput));
1792         }
1793     }
1794
1795     // Create transactions if there are some unhandled coins left
1796     if (wtxNew.vout[0].nValue > 0) {
1797         int64 nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION) + wtxNew.vin.size() * 110;
1798
1799         double dFinalPriority = dWeight /= nBytes;
1800         bool fAllowFree = CTransaction::AllowFree(dFinalPriority);
1801
1802         // Get actual transaction fee according to its size and priority
1803         int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND, nBytes);
1804
1805         wtxNew.vout[0].nValue -= nMinFee; // Set actual fee
1806
1807         if (wtxNew.vout[0].nValue <= 0)
1808             return false;
1809
1810         for (unsigned int i = 0; i < wtxNew.vin.size(); i++) {
1811             const CWalletTx *txin = vwtxPrev[i];
1812
1813             // Sign all scripts again
1814             if (!SignSignature(*this, *txin, wtxNew, i))
1815                 return false;
1816         }
1817
1818         // Try to commit, return false on failure
1819         if (!CommitTransaction(wtxNew, reservekey))
1820             return false;
1821
1822         listMerged.push_back(wtxNew.GetHash()); // Add to hashes list
1823     }
1824
1825     return true;
1826 }
1827
1828
1829 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1830 {
1831     // The following combine threshold is important to security
1832     // Should not be adjusted if you don't understand the consequences
1833     int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1834
1835     CBigNum bnTargetPerCoinDay;
1836     bnTargetPerCoinDay.SetCompact(nBits);
1837
1838     txNew.vin.clear();
1839     txNew.vout.clear();
1840
1841     // Mark coin stake transaction
1842     CScript scriptEmpty;
1843     scriptEmpty.clear();
1844     txNew.vout.push_back(CTxOut(0, scriptEmpty));
1845
1846     // Choose coins to use
1847     int64 nBalance = GetBalance();
1848     int64 nReserveBalance = 0;
1849
1850     if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1851         return error("CreateCoinStake : invalid reserve balance amount");
1852
1853     if (nBalance <= nReserveBalance)
1854         return false;
1855
1856     vector<const CWalletTx*> vwtxPrev;
1857
1858 /*
1859  * TODO: performance comparison
1860
1861     static set<pair<const CWalletTx*,unsigned int> > setCoins;
1862     static uint256 hashPrevBlock;
1863     static int64 nValueIn = 0;
1864
1865     // Cache outputs unless best block changed
1866     if (hashPrevBlock != pindexBest->GetBlockHash())
1867     {
1868         if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1869             return false;
1870
1871         if (setCoins.empty())
1872             return false;
1873
1874         hashPrevBlock == pindexBest->GetBlockHash();
1875     }
1876 */
1877
1878     set<pair<const CWalletTx*,unsigned int> > setCoins;
1879     int64 nValueIn = 0;
1880
1881     // Select coins with suitable depth
1882     if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1883         return false;
1884
1885     if (setCoins.empty())
1886         return false;
1887
1888     int64 nCredit = 0;
1889     CScript scriptPubKeyKernel;
1890     CTxDB txdb("r");
1891     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1892     {
1893         CTxIndex txindex;
1894         {
1895             LOCK2(cs_main, cs_wallet);
1896             if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex))
1897                 continue;
1898         }
1899
1900         // Read block header
1901         CBlock block;
1902         {
1903             LOCK2(cs_main, cs_wallet);
1904             if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
1905                 continue;
1906         }
1907
1908         static int nMaxStakeSearchInterval = 60;
1909         if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1910             continue; // only count coins meeting min age requirement
1911
1912         bool fKernelFound = false;
1913         for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++)
1914         {
1915             // Search backward in time from the given txNew timestamp 
1916             // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1917             uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1918             COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1919             if (CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake))
1920             {
1921                 // Found a kernel
1922                 if (fDebug && GetBoolArg("-printcoinstake"))
1923                     printf("CreateCoinStake : kernel found\n");
1924                 vector<valtype> vSolutions;
1925                 txnouttype whichType;
1926                 CScript scriptPubKeyOut;
1927                 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1928                 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1929                 {
1930                     if (fDebug && GetBoolArg("-printcoinstake"))
1931                         printf("CreateCoinStake : failed to parse kernel\n");
1932                     break;
1933                 }
1934                 if (fDebug && GetBoolArg("-printcoinstake"))
1935                     printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1936                 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1937                 {
1938                     if (fDebug && GetBoolArg("-printcoinstake"))
1939                         printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1940                     break;  // only support pay to public key and pay to address
1941                 }
1942                 if (whichType == TX_PUBKEYHASH) // pay to address type
1943                 {
1944                     // convert to pay to public key type
1945                     if (!keystore.GetKey(uint160(vSolutions[0]), key))
1946                     {
1947                         if (fDebug && GetBoolArg("-printcoinstake"))
1948                             printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1949                         break;  // unable to find corresponding public key
1950                     }
1951                     scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1952                 }
1953                 if (whichType == TX_PUBKEY)
1954                 {
1955                     valtype& vchPubKey = vSolutions[0];
1956                     if (!keystore.GetKey(Hash160(vchPubKey), key))
1957                     {
1958                         if (fDebug && GetBoolArg("-printcoinstake"))
1959                             printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1960                         break;  // unable to find corresponding public key
1961                     }
1962
1963                 if (key.GetPubKey() != vchPubKey)
1964                 {
1965                     if (fDebug && GetBoolArg("-printcoinstake"))
1966                         printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1967                         break; // keys mismatch
1968                     }
1969
1970                     scriptPubKeyOut = scriptPubKeyKernel;
1971                 }
1972
1973                 txNew.nTime -= n;
1974                 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1975                 nCredit += pcoin.first->vout[pcoin.second].nValue;
1976                 vwtxPrev.push_back(pcoin.first);
1977                 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1978
1979                 if (GetWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeMaxAge)
1980                     txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1981                 if (fDebug && GetBoolArg("-printcoinstake"))
1982                     printf("CreateCoinStake : added kernel type=%d\n", whichType);
1983                 fKernelFound = true;
1984                 break;
1985             }
1986         }
1987
1988         if (fKernelFound || fShutdown)
1989             break; // if kernel is found stop searching
1990     }
1991
1992     if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1993         return false;
1994
1995     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1996     {
1997         // Attempt to add more inputs
1998         // Only add coins of the same key/address as kernel
1999         if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
2000             && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
2001         {
2002             int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
2003
2004             // Stop adding more inputs if already too many inputs
2005             if (txNew.vin.size() >= 100)
2006                 break;
2007             // Stop adding more inputs if value is already pretty significant
2008             if (nCredit > nCombineThreshold)
2009                 break;
2010             // Stop adding inputs if reached reserve limit
2011             if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
2012                 break;
2013             // Do not add additional significant input
2014             if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
2015                 continue;
2016             // Do not add input that is still too young
2017             if (nTimeWeight < nStakeMaxAge)
2018                 continue;
2019
2020             txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
2021             nCredit += pcoin.first->vout[pcoin.second].nValue;
2022             vwtxPrev.push_back(pcoin.first);
2023         }
2024     }
2025
2026     // Calculate coin age reward
2027     {
2028         uint64 nCoinAge;
2029         CTxDB txdb("r");
2030         if (!txNew.GetCoinAge(txdb, nCoinAge))
2031             return error("CreateCoinStake : failed to calculate coin age");
2032         nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
2033     }
2034
2035     int64 nMinFee = 0;
2036     while (true)
2037     {
2038         // Set output amount
2039         if (txNew.vout.size() == 3)
2040         {
2041             txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
2042             txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
2043         }
2044         else
2045             txNew.vout[1].nValue = nCredit - nMinFee;
2046
2047         // Sign
2048         int nIn = 0;
2049         BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
2050         {
2051             if (!SignSignature(*this, *pcoin, txNew, nIn++))
2052                 return error("CreateCoinStake : failed to sign coinstake");
2053         }
2054
2055         // Limit size
2056         unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
2057         if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
2058             return error("CreateCoinStake : exceeded coinstake size limit");
2059
2060         // Check enough fee is paid
2061         if (nMinFee < txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT)
2062         {
2063             nMinFee = txNew.GetMinFee(1, false, GMF_BLOCK, nBytes) - CENT;
2064             continue; // try signing again
2065         }
2066         else
2067         {
2068             if (fDebug && GetBoolArg("-printfee"))
2069                 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
2070             break;
2071         }
2072     }
2073
2074     // Successfully generated coinstake
2075     return true;
2076 }
2077
2078
2079 // Call after CreateTransaction unless you want to abort
2080 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2081 {
2082     {
2083         LOCK2(cs_main, cs_wallet);
2084         printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
2085         {
2086             // This is only to keep the database open to defeat the auto-flush for the
2087             // duration of this scope.  This is the only place where this optimization
2088             // maybe makes sense; please don't do it anywhere else.
2089             CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
2090
2091             // Take key pair from key pool so it won't be used again
2092             reservekey.KeepKey();
2093
2094             // Add tx to wallet, because if it has change it's also ours,
2095             // otherwise just for transaction history.
2096             AddToWallet(wtxNew);
2097
2098             // Mark old coins as spent
2099             set<CWalletTx*> setCoins;
2100             BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2101             {
2102                 CWalletTx &coin = mapWallet[txin.prevout.hash];
2103                 coin.BindWallet(this);
2104                 coin.MarkSpent(txin.prevout.n);
2105                 coin.WriteToDisk();
2106                 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2107             }
2108
2109             if (fFileBacked)
2110                 delete pwalletdb;
2111         }
2112
2113         // Track how many getdata requests our transaction gets
2114         mapRequestCount[wtxNew.GetHash()] = 0;
2115
2116         // Broadcast
2117         if (!wtxNew.AcceptToMemoryPool())
2118         {
2119             // This must not fail. The transaction has already been signed and recorded.
2120             printf("CommitTransaction() : Error: Transaction not valid");
2121             return false;
2122         }
2123         wtxNew.RelayWalletTransaction();
2124     }
2125     return true;
2126 }
2127
2128
2129
2130
2131 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
2132 {
2133     CReserveKey reservekey(this);
2134     int64 nFeeRequired;
2135
2136     if (IsLocked())
2137     {
2138         string strError = _("Error: Wallet locked, unable to create transaction  ");
2139         printf("SendMoney() : %s", strError.c_str());
2140         return strError;
2141     }
2142     if (fWalletUnlockMintOnly)
2143     {
2144         string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
2145         printf("SendMoney() : %s", strError.c_str());
2146         return strError;
2147     }
2148     if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
2149     {
2150         string strError;
2151         if (nValue + nFeeRequired > GetBalance())
2152             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());
2153         else
2154             strError = _("Error: Transaction creation failed  ");
2155         printf("SendMoney() : %s", strError.c_str());
2156         return strError;
2157     }
2158
2159     if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
2160         return "ABORTED";
2161
2162     if (!CommitTransaction(wtxNew, reservekey))
2163         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.");
2164
2165     return "";
2166 }
2167
2168
2169
2170 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
2171 {
2172     // Check amount
2173     if (nValue <= 0)
2174         return _("Invalid amount");
2175     if (nValue + nTransactionFee > GetBalance())
2176         return _("Insufficient funds");
2177
2178     // Parse Bitcoin address
2179     CScript scriptPubKey;
2180     scriptPubKey.SetDestination(address);
2181
2182     return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
2183 }
2184
2185
2186
2187
2188 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2189 {
2190     if (!fFileBacked)
2191         return DB_LOAD_OK;
2192     fFirstRunRet = false;
2193     DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2194     if (nLoadWalletRet == DB_NEED_REWRITE)
2195     {
2196         if (CDB::Rewrite(strWalletFile, "\x04pool"))
2197         {
2198             setKeyPool.clear();
2199             // Note: can't top-up keypool here, because wallet is locked.
2200             // User will be prompted to unlock wallet the next operation
2201             // the requires a new key.
2202         }
2203     }
2204
2205     if (nLoadWalletRet != DB_LOAD_OK)
2206         return nLoadWalletRet;
2207     fFirstRunRet = !vchDefaultKey.IsValid();
2208
2209     NewThread(ThreadFlushWalletDB, &strWalletFile);
2210     return DB_LOAD_OK;
2211 }
2212
2213
2214 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
2215 {
2216     std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
2217     mapAddressBook[address] = strName;
2218     NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
2219     if (!fFileBacked)
2220         return false;
2221     return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2222 }
2223
2224 bool CWallet::DelAddressBookName(const CTxDestination& address)
2225 {
2226     mapAddressBook.erase(address);
2227     NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
2228     if (!fFileBacked)
2229         return false;
2230     return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2231 }
2232
2233
2234 void CWallet::PrintWallet(const CBlock& block)
2235 {
2236     {
2237         LOCK(cs_wallet);
2238         if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
2239         {
2240             CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
2241             printf("    mine:  %d  %d  %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2242         }
2243         if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
2244         {
2245             CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
2246             printf("    stake: %d  %d  %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
2247          }
2248
2249     }
2250     printf("\n");
2251 }
2252
2253 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
2254 {
2255     {
2256         LOCK(cs_wallet);
2257         map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
2258         if (mi != mapWallet.end())
2259         {
2260             wtx = (*mi).second;
2261             return true;
2262         }
2263     }
2264     return false;
2265 }
2266
2267 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2268 {
2269     if (fFileBacked)
2270     {
2271         if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2272             return false;
2273     }
2274     vchDefaultKey = vchPubKey;
2275     return true;
2276 }
2277
2278 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
2279 {
2280     if (!pwallet->fFileBacked)
2281         return false;
2282     strWalletFileOut = pwallet->strWalletFile;
2283     return true;
2284 }
2285
2286 //
2287 // Mark old keypool keys as used,
2288 // and generate all new keys
2289 //
2290 bool CWallet::NewKeyPool()
2291 {
2292     {
2293         LOCK(cs_wallet);
2294         CWalletDB walletdb(strWalletFile);
2295         BOOST_FOREACH(int64 nIndex, setKeyPool)
2296             walletdb.ErasePool(nIndex);
2297         setKeyPool.clear();
2298
2299         if (IsLocked())
2300             return false;
2301
2302         int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
2303         for (int i = 0; i < nKeys; i++)
2304         {
2305             int64 nIndex = i+1;
2306             walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2307             setKeyPool.insert(nIndex);
2308         }
2309         printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
2310     }
2311     return true;
2312 }
2313
2314 bool CWallet::TopUpKeyPool(unsigned int nSize)
2315 {
2316     {
2317         LOCK(cs_wallet);
2318
2319         if (IsLocked())
2320             return false;
2321
2322         CWalletDB walletdb(strWalletFile);
2323
2324         // Top up key pool
2325         unsigned int nTargetSize;
2326         if (nSize > 0)
2327             nTargetSize = nSize;
2328         else
2329             nTargetSize = max(GetArg("-keypool", 100), 0LL);
2330
2331         while (setKeyPool.size() < (nTargetSize + 1))
2332         {
2333             int64 nEnd = 1;
2334             if (!setKeyPool.empty())
2335                 nEnd = *(--setKeyPool.end()) + 1;
2336             if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2337                 throw runtime_error("TopUpKeyPool() : writing generated key failed");
2338             setKeyPool.insert(nEnd);
2339             printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
2340         }
2341     }
2342     return true;
2343 }
2344
2345 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
2346 {
2347     nIndex = -1;
2348     keypool.vchPubKey = CPubKey();
2349     {
2350         LOCK(cs_wallet);
2351
2352         if (!IsLocked())
2353             TopUpKeyPool();
2354
2355         // Get the oldest key
2356         if(setKeyPool.empty())
2357             return;
2358
2359         CWalletDB walletdb(strWalletFile);
2360
2361         nIndex = *(setKeyPool.begin());
2362         setKeyPool.erase(setKeyPool.begin());
2363         if (!walletdb.ReadPool(nIndex, keypool))
2364             throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2365         if (!HaveKey(keypool.vchPubKey.GetID()))
2366             throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2367         assert(keypool.vchPubKey.IsValid());
2368         if (fDebug && GetBoolArg("-printkeypool"))
2369             printf("keypool reserve %"PRI64d"\n", nIndex);
2370     }
2371 }
2372
2373 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2374 {
2375     {
2376         LOCK2(cs_main, cs_wallet);
2377         CWalletDB walletdb(strWalletFile);
2378
2379         int64 nIndex = 1 + *(--setKeyPool.end());
2380         if (!walletdb.WritePool(nIndex, keypool))
2381             throw runtime_error("AddReserveKey() : writing added key failed");
2382         setKeyPool.insert(nIndex);
2383         return nIndex;
2384     }
2385     return -1;
2386 }
2387
2388 void CWallet::KeepKey(int64 nIndex)
2389 {
2390     // Remove from key pool
2391     if (fFileBacked)
2392     {
2393         CWalletDB walletdb(strWalletFile);
2394         walletdb.ErasePool(nIndex);
2395     }
2396     if(fDebug)
2397         printf("keypool keep %"PRI64d"\n", nIndex);
2398 }
2399
2400 void CWallet::ReturnKey(int64 nIndex)
2401 {
2402     // Return to key pool
2403     {
2404         LOCK(cs_wallet);
2405         setKeyPool.insert(nIndex);
2406     }
2407     if(fDebug)
2408         printf("keypool return %"PRI64d"\n", nIndex);
2409 }
2410
2411 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2412 {
2413     int64 nIndex = 0;
2414     CKeyPool keypool;
2415     {
2416         LOCK(cs_wallet);
2417         ReserveKeyFromKeyPool(nIndex, keypool);
2418         if (nIndex == -1)
2419         {
2420             if (fAllowReuse && vchDefaultKey.IsValid())
2421             {
2422                 result = vchDefaultKey;
2423                 return true;
2424             }
2425             if (IsLocked()) return false;
2426             result = GenerateNewKey();
2427             return true;
2428         }
2429         KeepKey(nIndex);
2430         result = keypool.vchPubKey;
2431     }
2432     return true;
2433 }
2434
2435 int64 CWallet::GetOldestKeyPoolTime()
2436 {
2437     int64 nIndex = 0;
2438     CKeyPool keypool;
2439     ReserveKeyFromKeyPool(nIndex, keypool);
2440     if (nIndex == -1)
2441         return GetTime();
2442     ReturnKey(nIndex);
2443     return keypool.nTime;
2444 }
2445
2446 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2447 {
2448     map<CTxDestination, int64> balances;
2449
2450     {
2451         LOCK(cs_wallet);
2452         BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2453         {
2454             CWalletTx *pcoin = &walletEntry.second;
2455
2456             if (!pcoin->IsFinal() || !pcoin->IsTrusted())
2457                 continue;
2458
2459             if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2460                 continue;
2461
2462             int nDepth = pcoin->GetDepthInMainChain();
2463             if (nDepth < (pcoin->IsFromMe(MINE_ALL) ? 0 : 1))
2464                 continue;
2465
2466             for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2467             {
2468                 CTxDestination addr;
2469                 if (!IsMine(pcoin->vout[i]))
2470                     continue;
2471                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2472                     continue;
2473
2474                 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2475
2476                 if (!balances.count(addr))
2477                     balances[addr] = 0;
2478                 balances[addr] += n;
2479             }
2480         }
2481     }
2482
2483     return balances;
2484 }
2485
2486 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2487 {
2488     set< set<CTxDestination> > groupings;
2489     set<CTxDestination> grouping;
2490
2491     BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2492     {
2493         CWalletTx *pcoin = &walletEntry.second;
2494
2495         if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2496         {
2497             // group all input addresses with each other
2498             BOOST_FOREACH(CTxIn txin, pcoin->vin)
2499             {
2500                 CTxDestination address;
2501                 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2502                     continue;
2503                 grouping.insert(address);
2504             }
2505
2506             // group change with input addresses
2507             BOOST_FOREACH(CTxOut txout, pcoin->vout)
2508                 if (IsChange(txout))
2509                 {
2510                     CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2511                     CTxDestination txoutAddr;
2512                     if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2513                         continue;
2514                     grouping.insert(txoutAddr);
2515                 }
2516             groupings.insert(grouping);
2517             grouping.clear();
2518         }
2519
2520         // group lone addrs by themselves
2521         for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2522             if (IsMine(pcoin->vout[i]))
2523             {
2524                 CTxDestination address;
2525                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2526                     continue;
2527                 grouping.insert(address);
2528                 groupings.insert(grouping);
2529                 grouping.clear();
2530             }
2531     }
2532
2533     set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2534     map< CTxDestination, set<CTxDestination>* > setmap;  // map addresses to the unique group containing it
2535     BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2536     {
2537         // make a set of all the groups hit by this new group
2538         set< set<CTxDestination>* > hits;
2539         map< CTxDestination, set<CTxDestination>* >::iterator it;
2540         BOOST_FOREACH(CTxDestination address, grouping)
2541             if ((it = setmap.find(address)) != setmap.end())
2542                 hits.insert((*it).second);
2543
2544         // merge all hit groups into a new single group and delete old groups
2545         set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2546         BOOST_FOREACH(set<CTxDestination>* hit, hits)
2547         {
2548             merged->insert(hit->begin(), hit->end());
2549             uniqueGroupings.erase(hit);
2550             delete hit;
2551         }
2552         uniqueGroupings.insert(merged);
2553
2554         // update setmap
2555         BOOST_FOREACH(CTxDestination element, *merged)
2556             setmap[element] = merged;
2557     }
2558
2559     set< set<CTxDestination> > ret;
2560     BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2561     {
2562         ret.insert(*uniqueGrouping);
2563         delete uniqueGrouping;
2564     }
2565
2566     return ret;
2567 }
2568
2569 // ppcoin: check 'spent' consistency between wallet and txindex
2570 // ppcoin: fix wallet spent state according to txindex
2571 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2572 {
2573     nMismatchFound = 0;
2574     nBalanceInQuestion = 0;
2575
2576     LOCK(cs_wallet);
2577     vector<CWalletTx*> vCoins;
2578     vCoins.reserve(mapWallet.size());
2579     for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2580         vCoins.push_back(&(*it).second);
2581
2582     CTxDB txdb("r");
2583     BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2584     {
2585         // Find the corresponding transaction index
2586         CTxIndex txindex;
2587         if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex))
2588             continue;
2589         for (unsigned int n=0; n < pcoin->vout.size(); n++)
2590         {
2591             if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull()))
2592             {
2593                 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2594                     FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2595                 nMismatchFound++;
2596                 nBalanceInQuestion += pcoin->vout[n].nValue;
2597                 if (!fCheckOnly)
2598                 {
2599                     pcoin->MarkUnspent(n);
2600                     pcoin->WriteToDisk();
2601                 }
2602             }
2603             else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull()))
2604             {
2605                 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2606                     FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2607                 nMismatchFound++;
2608                 nBalanceInQuestion += pcoin->vout[n].nValue;
2609                 if (!fCheckOnly)
2610                 {
2611                     pcoin->MarkSpent(n);
2612                     pcoin->WriteToDisk();
2613                 }
2614             }
2615
2616         }
2617
2618         if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2619         {
2620             printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2621             if (!fCheckOnly)
2622             {
2623                 EraseFromWallet(pcoin->GetHash());
2624             }
2625         }
2626     }
2627 }
2628
2629 // ppcoin: disable transaction (only for coinstake)
2630 void CWallet::DisableTransaction(const CTransaction &tx)
2631 {
2632     if (!tx.IsCoinStake() || !IsFromMe(tx))
2633         return; // only disconnecting coinstake requires marking input unspent
2634
2635     LOCK(cs_wallet);
2636     BOOST_FOREACH(const CTxIn& txin, tx.vin)
2637     {
2638         map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2639         if (mi != mapWallet.end())
2640         {
2641             CWalletTx& prev = (*mi).second;
2642             if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2643             {
2644                 prev.MarkUnspent(txin.prevout.n);
2645                 prev.WriteToDisk();
2646             }
2647         }
2648     }
2649 }
2650
2651 CPubKey CReserveKey::GetReservedKey()
2652 {
2653     if (nIndex == -1)
2654     {
2655         CKeyPool keypool;
2656         pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2657         if (nIndex != -1)
2658             vchPubKey = keypool.vchPubKey;
2659         else
2660         {
2661             printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2662             vchPubKey = pwallet->vchDefaultKey;
2663         }
2664     }
2665     assert(vchPubKey.IsValid());
2666     return vchPubKey;
2667 }
2668
2669 void CReserveKey::KeepKey()
2670 {
2671     if (nIndex != -1)
2672         pwallet->KeepKey(nIndex);
2673     nIndex = -1;
2674     vchPubKey = CPubKey();
2675 }
2676
2677 void CReserveKey::ReturnKey()
2678 {
2679     if (nIndex != -1)
2680         pwallet->ReturnKey(nIndex);
2681     nIndex = -1;
2682     vchPubKey = CPubKey();
2683 }
2684
2685 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2686 {
2687     setAddress.clear();
2688
2689     CWalletDB walletdb(strWalletFile);
2690
2691     LOCK2(cs_main, cs_wallet);
2692     BOOST_FOREACH(const int64& id, setKeyPool)
2693     {
2694         CKeyPool keypool;
2695         if (!walletdb.ReadPool(id, keypool))
2696             throw runtime_error("GetAllReserveKeyHashes() : read failed");
2697         assert(keypool.vchPubKey.IsValid());
2698         CKeyID keyID = keypool.vchPubKey.GetID();
2699         if (!HaveKey(keyID))
2700             throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2701         setAddress.insert(keyID);
2702     }
2703 }
2704
2705 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2706 {
2707     {
2708         LOCK(cs_wallet);
2709         // Only notify UI if this transaction is in this wallet
2710         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2711         if (mi != mapWallet.end())
2712             NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2713     }
2714 }
2715
2716 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2717     mapKeyBirth.clear();
2718
2719     // get birth times for keys with metadata
2720     for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2721         if (it->second.nCreateTime)
2722             mapKeyBirth[it->first] = it->second.nCreateTime;
2723
2724     // map in which we'll infer heights of other keys
2725     CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2726     std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2727     std::set<CKeyID> setKeys;
2728     GetKeys(setKeys);
2729     BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2730         if (mapKeyBirth.count(keyid) == 0)
2731             mapKeyFirstBlock[keyid] = pindexMax;
2732     }
2733     setKeys.clear();
2734
2735     // if there are no such keys, we're done
2736     if (mapKeyFirstBlock.empty())
2737         return;
2738
2739     // find first block that affects those keys, if there are any left
2740     std::vector<CKeyID> vAffected;
2741     for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2742         // iterate over all wallet transactions...
2743         const CWalletTx &wtx = (*it).second;
2744         std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2745         if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2746             // ... which are already in a block
2747             int nHeight = blit->second->nHeight;
2748             BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2749                 // iterate over all their outputs
2750                 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2751                 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2752                     // ... and all their affected keys
2753                     std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2754                     if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2755                         rit->second = blit->second;
2756                 }
2757                 vAffected.clear();
2758             }
2759         }
2760     }
2761
2762     // Extract block timestamps for those keys
2763     for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2764         mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off
2765 }