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