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