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