55630aff701f2d28ed1d2c938d87bf210107a947
[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 CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock)
524 {
525     uint256 hash = tx.GetHash();
526     {
527         LOCK(cs_wallet);
528         bool fExisted = mapWallet.count(hash);
529         if (fExisted && !fUpdate) return false;
530         if (fExisted || IsMine(tx) || IsFromMe(tx))
531         {
532             CWalletTx wtx(this,tx);
533             // Get merkle branch if transaction was found in a block
534             if (pblock)
535                 wtx.SetMerkleBranch(pblock);
536             return AddToWallet(wtx);
537         }
538         else
539             WalletUpdateSpent(tx);
540     }
541     return false;
542 }
543
544 bool CWallet::EraseFromWallet(uint256 hash)
545 {
546     if (!fFileBacked)
547         return false;
548     {
549         LOCK(cs_wallet);
550         if (mapWallet.erase(hash))
551             CWalletDB(strWalletFile).EraseTx(hash);
552     }
553     return true;
554 }
555
556
557 bool CWallet::IsMine(const CTxIn &txin) const
558 {
559     {
560         LOCK(cs_wallet);
561         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
562         if (mi != mapWallet.end())
563         {
564             const CWalletTx& prev = (*mi).second;
565             if (txin.prevout.n < prev.vout.size())
566                 if (IsMine(prev.vout[txin.prevout.n]))
567                     return true;
568         }
569     }
570     return false;
571 }
572
573 int64 CWallet::GetDebit(const CTxIn &txin) const
574 {
575     {
576         LOCK(cs_wallet);
577         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
578         if (mi != mapWallet.end())
579         {
580             const CWalletTx& prev = (*mi).second;
581             if (txin.prevout.n < prev.vout.size())
582                 if (IsMine(prev.vout[txin.prevout.n]))
583                     return prev.vout[txin.prevout.n].nValue;
584         }
585     }
586     return 0;
587 }
588
589 bool CWallet::IsChange(const CTxOut& txout) const
590 {
591     CTxDestination address;
592
593     // TODO: fix handling of 'change' outputs. The assumption is that any
594     // payment to a TX_PUBKEYHASH that is mine but isn't in the address book
595     // is change. That assumption is likely to break when we implement multisignature
596     // wallets that return change back into a multi-signature-protected address;
597     // a better way of identifying which outputs are 'the send' and which are
598     // 'the change' will need to be implemented (maybe extend CWalletTx to remember
599     // which output, if any, was change).
600     if (ExtractDestination(txout.scriptPubKey, address) && ::IsMine(*this, address))
601     {
602         LOCK(cs_wallet);
603         if (!mapAddressBook.count(address))
604             return true;
605     }
606     return false;
607 }
608
609 int64 CWalletTx::GetTxTime() const
610 {
611     int64 n = nTimeSmart;
612     return n ? n : nTimeReceived;
613 }
614
615 int CWalletTx::GetRequestCount() const
616 {
617     // Returns -1 if it wasn't being tracked
618     int nRequests = -1;
619     {
620         LOCK(pwallet->cs_wallet);
621         if (IsCoinBase() || IsCoinStake())
622         {
623             // Generated block
624             if (hashBlock != 0)
625             {
626                 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
627                 if (mi != pwallet->mapRequestCount.end())
628                     nRequests = (*mi).second;
629             }
630         }
631         else
632         {
633             // Did anyone request this transaction?
634             map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
635             if (mi != pwallet->mapRequestCount.end())
636             {
637                 nRequests = (*mi).second;
638
639                 // How about the block it's in?
640                 if (nRequests == 0 && hashBlock != 0)
641                 {
642                     map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
643                     if (mi != pwallet->mapRequestCount.end())
644                         nRequests = (*mi).second;
645                     else
646                         nRequests = 1; // If it's in someone else's block it must have got out
647                 }
648             }
649         }
650     }
651     return nRequests;
652 }
653
654 void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CTxDestination, int64> >& listReceived,
655                            list<pair<CTxDestination, int64> >& listSent, int64& nFee, string& strSentAccount) const
656 {
657     nGeneratedImmature = nGeneratedMature = nFee = 0;
658     listReceived.clear();
659     listSent.clear();
660     strSentAccount = strFromAccount;
661
662     if (IsCoinBase() || IsCoinStake())
663     {
664         if (GetBlocksToMaturity() > 0)
665             nGeneratedImmature = pwallet->GetCredit(*this);
666         else
667             nGeneratedMature = GetCredit();
668         return;
669     }
670
671     // Compute fee:
672     int64 nDebit = GetDebit();
673     if (nDebit > 0) // debit>0 means we signed/sent this transaction
674     {
675         int64 nValueOut = GetValueOut();
676         nFee = nDebit - nValueOut;
677     }
678
679     // Sent/received.
680     BOOST_FOREACH(const CTxOut& txout, vout)
681     {
682         CTxDestination address;
683         vector<unsigned char> vchPubKey;
684         if (!ExtractDestination(txout.scriptPubKey, address))
685         {
686             printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
687                    this->GetHash().ToString().c_str());
688         }
689
690         // Don't report 'change' txouts
691         if (nDebit > 0 && pwallet->IsChange(txout))
692             continue;
693
694         if (nDebit > 0)
695             listSent.push_back(make_pair(address, txout.nValue));
696
697         if (pwallet->IsMine(txout))
698             listReceived.push_back(make_pair(address, txout.nValue));
699     }
700
701 }
702
703 void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived,
704                                   int64& nSent, int64& nFee) const
705 {
706     nGenerated = nReceived = nSent = nFee = 0;
707
708     int64 allGeneratedImmature, allGeneratedMature, allFee;
709     allGeneratedImmature = allGeneratedMature = allFee = 0;
710     string strSentAccount;
711     list<pair<CTxDestination, int64> > listReceived;
712     list<pair<CTxDestination, int64> > listSent;
713     GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount);
714
715     if (strAccount == "")
716         nGenerated = allGeneratedMature;
717     if (strAccount == strSentAccount)
718     {
719         BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& s, listSent)
720             nSent += s.second;
721         nFee = allFee;
722     }
723     {
724         LOCK(pwallet->cs_wallet);
725         BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64)& r, listReceived)
726         {
727             if (pwallet->mapAddressBook.count(r.first))
728             {
729                 map<CTxDestination, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first);
730                 if (mi != pwallet->mapAddressBook.end() && (*mi).second == strAccount)
731                     nReceived += r.second;
732             }
733             else if (strAccount.empty())
734             {
735                 nReceived += r.second;
736             }
737         }
738     }
739 }
740
741 void CWalletTx::AddSupportingTransactions()
742 {
743     vtxPrev.clear();
744
745     const int COPY_DEPTH = 3;
746     if (SetMerkleBranch() < COPY_DEPTH)
747     {
748         vector<uint256> vWorkQueue;
749         BOOST_FOREACH(const CTxIn& txin, vin)
750             vWorkQueue.push_back(txin.prevout.hash);
751
752         {
753             LOCK(pwallet->cs_wallet);
754             map<uint256, const CMerkleTx*> mapWalletPrev;
755             set<uint256> setAlreadyDone;
756             for (unsigned int i = 0; i < vWorkQueue.size(); i++)
757             {
758                 uint256 hash = vWorkQueue[i];
759                 if (setAlreadyDone.count(hash))
760                     continue;
761                 setAlreadyDone.insert(hash);
762
763                 CMerkleTx tx;
764                 map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash);
765                 if (mi != pwallet->mapWallet.end())
766                 {
767                     tx = (*mi).second;
768                     BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev)
769                         mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev;
770                 }
771                 else if (mapWalletPrev.count(hash))
772                 {
773                     tx = *mapWalletPrev[hash];
774                 }
775
776                 int nDepth = tx.SetMerkleBranch();
777                 vtxPrev.push_back(tx);
778
779                 if (nDepth < COPY_DEPTH)
780                 {
781                     BOOST_FOREACH(const CTxIn& txin, tx.vin)
782                         vWorkQueue.push_back(txin.prevout.hash);
783                 }
784             }
785         }
786     }
787
788     reverse(vtxPrev.begin(), vtxPrev.end());
789 }
790
791 bool CWalletTx::WriteToDisk()
792 {
793     return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this);
794 }
795
796 // Scan the block chain (starting in pindexStart) for transactions
797 // from or to us. If fUpdate is true, found transactions that already
798 // exist in the wallet will be updated.
799 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
800 {
801     int ret = 0;
802
803     CBlockIndex* pindex = pindexStart;
804     {
805         LOCK(cs_wallet);
806         while (pindex)
807         {
808             CBlock block;
809             block.ReadFromDisk(pindex, true);
810             BOOST_FOREACH(CTransaction& tx, block.vtx)
811             {
812                 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
813                     ret++;
814             }
815             pindex = pindex->pnext;
816         }
817     }
818     return ret;
819 }
820
821 void CWallet::ReacceptWalletTransactions()
822 {
823     bool fRepeat = true;
824     while (fRepeat)
825     {
826         LOCK(cs_wallet);
827         fRepeat = false;
828         bool fMissing = false;
829         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
830         {
831             CWalletTx& wtx = item.second;
832             if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1)))
833                 continue;
834
835             CCoins coins;
836             bool fUpdated = false;
837             bool fNotFound = pcoinsTip->GetCoins(wtx.GetHash(), coins);
838             if (!fNotFound || wtx.GetDepthInMainChain() > 0)
839             {
840                 // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat
841                 for (unsigned int i = 0; i < wtx.vout.size(); i++)
842                 {
843                     if (wtx.IsSpent(i))
844                         continue;
845                     if ((i >= coins.vout.size() || coins.vout[i].IsNull()) && IsMine(wtx.vout[i]))
846                     {
847                         wtx.MarkSpent(i);
848                         fUpdated = true;
849                         fMissing = true;
850                     }
851                 }
852                 if (fUpdated)
853                 {
854                     printf("ReacceptWalletTransactions found spent coin %sbc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str());
855                     wtx.MarkDirty();
856                     wtx.WriteToDisk();
857                 }
858             }
859             else
860             {
861                 // Re-accept any txes of ours that aren't already in a block
862                 if (!(wtx.IsCoinBase() || wtx.IsCoinStake()))
863                     wtx.AcceptWalletTransaction(false);
864             }
865         }
866         if (fMissing)
867         {
868             // TODO: optimize this to scan just part of the block chain?
869             if (ScanForWalletTransactions(pindexGenesisBlock))
870                 fRepeat = true;  // Found missing transactions: re-do re-accept.
871         }
872     }
873 }
874
875 void CWalletTx::RelayWalletTransaction()
876 {
877     CCoinsViewCache& coins = *pcoinsTip;
878     BOOST_FOREACH(const CMerkleTx& tx, vtxPrev)
879     {
880         if (!(tx.IsCoinBase() || tx.IsCoinStake()))
881         {
882             uint256 hash = tx.GetHash();
883             if (!coins.HaveCoins(hash))
884                 RelayTransaction((CTransaction)tx, hash);
885         }
886     }
887     if (!(IsCoinBase() || IsCoinStake()))
888     {
889         uint256 hash = GetHash();
890         if (!coins.HaveCoins(hash))
891         {
892             printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str());
893             RelayTransaction((CTransaction)*this, hash);
894         }
895     }
896 }
897
898 void CWallet::ResendWalletTransactions()
899 {
900     // Do this infrequently and randomly to avoid giving away
901     // that these are our transactions.
902     static int64 nNextTime;
903     if (GetTime() < nNextTime)
904         return;
905     bool fFirst = (nNextTime == 0);
906     nNextTime = GetTime() + GetRand(30 * 60);
907     if (fFirst)
908         return;
909
910     // Only do it if there's been a new block since last time
911     static int64 nLastTime;
912     if (nTimeBestReceived < nLastTime)
913         return;
914     nLastTime = GetTime();
915
916     // Rebroadcast any of our txes that aren't in a block yet
917     printf("ResendWalletTransactions()\n");
918     {
919         LOCK(cs_wallet);
920         // Sort them in chronological order
921         multimap<unsigned int, CWalletTx*> mapSorted;
922         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
923         {
924             CWalletTx& wtx = item.second;
925             // Don't rebroadcast until it's had plenty of time that
926             // it should have gotten in already by now.
927             if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60)
928                 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
929         }
930         BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
931         {
932             CWalletTx& wtx = *item.second;
933             wtx.RelayWalletTransaction();
934         }
935     }
936 }
937
938
939
940
941
942
943 //////////////////////////////////////////////////////////////////////////////
944 //
945 // Actions
946 //
947
948
949 int64 CWallet::GetBalance() const
950 {
951     int64 nTotal = 0;
952     {
953         LOCK(cs_wallet);
954         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
955         {
956             const CWalletTx* pcoin = &(*it).second;
957             if (pcoin->IsConfirmed())
958                 nTotal += pcoin->GetAvailableCredit();
959         }
960     }
961
962     return nTotal;
963 }
964
965 int64 CWallet::GetUnconfirmedBalance() const
966 {
967     int64 nTotal = 0;
968     {
969         LOCK(cs_wallet);
970         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
971         {
972             const CWalletTx* pcoin = &(*it).second;
973             if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
974                 nTotal += pcoin->GetAvailableCredit();
975         }
976     }
977     return nTotal;
978 }
979
980 int64 CWallet::GetImmatureBalance() const
981 {
982     int64 nTotal = 0;
983     {
984         LOCK(cs_wallet);
985         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
986         {
987             const CWalletTx& pcoin = (*it).second;
988             if (pcoin.IsCoinBase() && pcoin.GetBlocksToMaturity() > 0 && pcoin.IsInMainChain())
989                 nTotal += GetCredit(pcoin);
990         }
991     }
992     return nTotal;
993 }
994
995 // populate vCoins with vector of spendable COutputs
996 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const
997 {
998     vCoins.clear();
999
1000     {
1001         LOCK(cs_wallet);
1002         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1003         {
1004             const CWalletTx* pcoin = &(*it).second;
1005
1006             if (!pcoin->IsFinal())
1007                 continue;
1008
1009             if (fOnlyConfirmed && !pcoin->IsConfirmed())
1010                 continue;
1011
1012             if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1013                 continue;
1014
1015             if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0)
1016                 continue;
1017
1018             for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1019                 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue &&
1020                 (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i)))
1021                     vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1022
1023         }
1024     }
1025 }
1026
1027 void CWallet::AvailableCoinsMinConf(vector<COutput>& vCoins, int nConf) const
1028 {
1029     vCoins.clear();
1030
1031     {
1032         LOCK(cs_wallet);
1033         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1034         {
1035             const CWalletTx* pcoin = &(*it).second;
1036
1037             if (!pcoin->IsFinal())
1038                 continue;
1039
1040             if(pcoin->GetDepthInMainChain() < nConf)
1041                 continue;
1042
1043             for (unsigned int i = 0; i < pcoin->vout.size(); i++)
1044                 if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue)
1045                     vCoins.push_back(COutput(pcoin, i, pcoin->GetDepthInMainChain()));
1046         }
1047     }
1048 }
1049
1050 static void ApproximateBestSubset(vector<pair<int64, pair<const CWalletTx*,unsigned int> > >vValue, int64 nTotalLower, int64 nTargetValue,
1051                                   vector<char>& vfBest, int64& nBest, int iterations = 1000)
1052 {
1053     vector<char> vfIncluded;
1054
1055     vfBest.assign(vValue.size(), true);
1056     nBest = nTotalLower;
1057
1058     for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1059     {
1060         vfIncluded.assign(vValue.size(), false);
1061         int64 nTotal = 0;
1062         bool fReachedTarget = false;
1063         for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1064         {
1065             for (unsigned int i = 0; i < vValue.size(); i++)
1066             {
1067                 if (nPass == 0 ? rand() % 2 : !vfIncluded[i])
1068                 {
1069                     nTotal += vValue[i].first;
1070                     vfIncluded[i] = true;
1071                     if (nTotal >= nTargetValue)
1072                     {
1073                         fReachedTarget = true;
1074                         if (nTotal < nBest)
1075                         {
1076                             nBest = nTotal;
1077                             vfBest = vfIncluded;
1078                         }
1079                         nTotal -= vValue[i].first;
1080                         vfIncluded[i] = false;
1081                     }
1082                 }
1083             }
1084         }
1085     }
1086 }
1087
1088 // ppcoin: total coins staked (non-spendable until maturity)
1089 int64 CWallet::GetStake() const
1090 {
1091     int64 nTotal = 0;
1092     LOCK(cs_wallet);
1093     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1094     {
1095         const CWalletTx* pcoin = &(*it).second;
1096         if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1097             nTotal += CWallet::GetCredit(*pcoin);
1098     }
1099     return nTotal;
1100 }
1101
1102 int64 CWallet::GetNewMint() const
1103 {
1104     int64 nTotal = 0;
1105     LOCK(cs_wallet);
1106     for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1107     {
1108         const CWalletTx* pcoin = &(*it).second;
1109         if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0)
1110             nTotal += CWallet::GetCredit(*pcoin);
1111     }
1112     return nTotal;
1113 }
1114
1115 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
1116 {
1117     setCoinsRet.clear();
1118     nValueRet = 0;
1119
1120     // List of values less than target
1121     pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1122     coinLowestLarger.first = std::numeric_limits<int64>::max();
1123     coinLowestLarger.second.first = NULL;
1124     vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue;
1125     int64 nTotalLower = 0;
1126
1127     random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1128
1129     BOOST_FOREACH(COutput output, vCoins)
1130     {
1131         const CWalletTx *pcoin = output.tx;
1132
1133         if (output.nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs))
1134             continue;
1135
1136         int i = output.i;
1137
1138         // Follow the timestamp rules
1139         if (pcoin->nTime > nSpendTime)
1140             continue;
1141
1142         int64 n = pcoin->vout[i].nValue;
1143
1144         pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1145
1146         if (n == nTargetValue)
1147         {
1148             setCoinsRet.insert(coin.second);
1149             nValueRet += coin.first;
1150             return true;
1151         }
1152         else if (n < nTargetValue + CENT)
1153         {
1154             vValue.push_back(coin);
1155             nTotalLower += n;
1156         }
1157         else if (n < coinLowestLarger.first)
1158         {
1159             coinLowestLarger = coin;
1160         }
1161     }
1162
1163     if (nTotalLower == nTargetValue)
1164     {
1165         for (unsigned int i = 0; i < vValue.size(); ++i)
1166         {
1167             setCoinsRet.insert(vValue[i].second);
1168             nValueRet += vValue[i].first;
1169         }
1170         return true;
1171     }
1172
1173     if (nTotalLower < nTargetValue)
1174     {
1175         if (coinLowestLarger.second.first == NULL)
1176             return false;
1177         setCoinsRet.insert(coinLowestLarger.second);
1178         nValueRet += coinLowestLarger.first;
1179         return true;
1180     }
1181
1182     // Solve subset sum by stochastic approximation
1183     sort(vValue.rbegin(), vValue.rend(), CompareValueOnly());
1184     vector<char> vfBest;
1185     int64 nBest;
1186
1187     ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000);
1188     if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT)
1189         ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000);
1190
1191     // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
1192     //                                   or the next bigger coin is closer), return the bigger coin
1193     if (coinLowestLarger.second.first &&
1194         ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest))
1195     {
1196         setCoinsRet.insert(coinLowestLarger.second);
1197         nValueRet += coinLowestLarger.first;
1198     }
1199     else {
1200         for (unsigned int i = 0; i < vValue.size(); i++)
1201             if (vfBest[i])
1202             {
1203                 setCoinsRet.insert(vValue[i].second);
1204                 nValueRet += vValue[i].first;
1205             }
1206
1207         if (fDebug && GetBoolArg("-printpriority"))
1208         {
1209             //// debug print
1210             printf("SelectCoins() best subset: ");
1211             for (unsigned int i = 0; i < vValue.size(); i++)
1212                 if (vfBest[i])
1213                     printf("%s ", FormatMoney(vValue[i].first).c_str());
1214             printf("total %s\n", FormatMoney(nBest).c_str());
1215         }
1216     }
1217
1218     return true;
1219 }
1220
1221 bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet, const CCoinControl* coinControl) const
1222 {
1223     vector<COutput> vCoins;
1224     AvailableCoins(vCoins, true, coinControl);
1225
1226     // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
1227     if (coinControl && coinControl->HasSelected())
1228     {
1229         BOOST_FOREACH(const COutput& out, vCoins)
1230         {
1231             nValueRet += out.tx->vout[out.i].nValue;
1232             setCoinsRet.insert(make_pair(out.tx, out.i));
1233         }
1234         return (nValueRet >= nTargetValue);
1235     }
1236
1237     return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, vCoins, setCoinsRet, nValueRet) ||
1238             SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, vCoins, setCoinsRet, nValueRet) ||
1239             SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, vCoins, setCoinsRet, nValueRet));
1240 }
1241
1242 // Select some coins without random shuffle or best subset approximation
1243 bool CWallet::SelectCoinsSimple(int64 nTargetValue, unsigned int nSpendTime, int nMinConf, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const
1244 {
1245     vector<COutput> vCoins;
1246     AvailableCoinsMinConf(vCoins, nMinConf);
1247
1248     setCoinsRet.clear();
1249     nValueRet = 0;
1250
1251     BOOST_FOREACH(COutput output, vCoins)
1252     {
1253         const CWalletTx *pcoin = output.tx;
1254         int i = output.i;
1255
1256         // Stop if we've chosen enough inputs
1257         if (nValueRet >= nTargetValue)
1258             break;
1259
1260         // Follow the timestamp rules
1261         if (pcoin->nTime > nSpendTime)
1262             continue;
1263
1264         int64 n = pcoin->vout[i].nValue;
1265
1266         pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1267
1268         if (n >= nTargetValue)
1269         {
1270             // If input value is greater or equal to target then simply insert
1271             //    it into the current subset and exit
1272             setCoinsRet.insert(coin.second);
1273             nValueRet += coin.first;
1274             break;
1275         }
1276         else if (n < nTargetValue + CENT)
1277         {
1278             setCoinsRet.insert(coin.second);
1279             nValueRet += coin.first;
1280         }
1281     }
1282
1283     return true;
1284 }
1285
1286 bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1287 {
1288     int64 nValue = 0;
1289     BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1290     {
1291         if (nValue < 0)
1292             return false;
1293         nValue += s.second;
1294     }
1295     if (vecSend.empty() || nValue < 0)
1296         return false;
1297
1298     wtxNew.BindWallet(this);
1299
1300     {
1301         LOCK2(cs_main, cs_wallet);
1302         {
1303             nFeeRet = nTransactionFee;
1304             while (true)
1305             {
1306                 wtxNew.vin.clear();
1307                 wtxNew.vout.clear();
1308                 wtxNew.fFromMe = true;
1309
1310                 int64 nTotalValue = nValue + nFeeRet;
1311                 double dPriority = 0;
1312                 // vouts to the payees
1313                 BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend)
1314                     wtxNew.vout.push_back(CTxOut(s.second, s.first));
1315
1316                 // Choose coins to use
1317                 set<pair<const CWalletTx*,unsigned int> > setCoins;
1318                 int64 nValueIn = 0;
1319                 if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl))
1320                     return false;
1321                 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1322                 {
1323                     int64 nCredit = pcoin.first->vout[pcoin.second].nValue;
1324                     dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain();
1325                 }
1326
1327                 int64 nChange = nValueIn - nValue - nFeeRet;
1328                 // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE
1329                 // or until nChange becomes zero
1330                 // NOTE: this depends on the exact behaviour of GetMinFee
1331                 if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT)
1332                 {
1333                     int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet);
1334                     nChange -= nMoveToFee;
1335                     nFeeRet += nMoveToFee;
1336                 }
1337
1338                 // sub-cent change is moved to fee
1339                 if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT)
1340                 {
1341                     nFeeRet += nChange;
1342                     nChange = 0;
1343                 }
1344
1345                 if (nChange > 0)
1346                 {
1347                     // Fill a vout to ourself
1348                     // TODO: pass in scriptChange instead of reservekey so
1349                     // change transaction isn't always pay-to-bitcoin-address
1350                     CScript scriptChange;
1351
1352                     // coin control: send change to custom address
1353                     if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
1354                         scriptChange.SetDestination(coinControl->destChange);
1355
1356                     // no coin control: send change to newly generated address
1357                     else
1358                     {
1359                         // Note: We use a new key here to keep it from being obvious which side is the change.
1360                         //  The drawback is that by not reusing a previous key, the change may be lost if a
1361                         //  backup is restored, if the backup doesn't have the new private key for the change.
1362                         //  If we reused the old key, it would be possible to add code to look for and
1363                         //  rediscover unknown transactions that were written with keys of ours to recover
1364                         //  post-backup change.
1365
1366                         // Reserve a new key pair from key pool
1367                         CPubKey vchPubKey = reservekey.GetReservedKey();
1368
1369                         scriptChange.SetDestination(vchPubKey.GetID());
1370                     }
1371
1372                     // Insert change txn at random position:
1373                     vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size());
1374                     wtxNew.vout.insert(position, CTxOut(nChange, scriptChange));
1375                 }
1376                 else
1377                     reservekey.ReturnKey();
1378
1379                 // Fill vin
1380                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1381                     wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second));
1382
1383                 // Sign
1384                 int nIn = 0;
1385                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
1386                     if (!SignSignature(*this, *coin.first, wtxNew, nIn++))
1387                         return false;
1388
1389                 // Limit size
1390                 unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION);
1391                 if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1392                     return false;
1393                 dPriority /= nBytes;
1394
1395                 // Check that enough fee is included
1396                 int64 nPayFee = nTransactionFee * (1 + (int64)nBytes / 1000);
1397                 bool fAllowFree = CTransaction::AllowFree(dPriority);
1398                 int64 nMinFee = wtxNew.GetMinFee(1, fAllowFree, GMF_SEND);
1399                 if (nFeeRet < max(nPayFee, nMinFee))
1400                 {
1401                     nFeeRet = max(nPayFee, nMinFee);
1402                     continue;
1403                 }
1404
1405                 // Fill vtxPrev by copying from previous transactions vtxPrev
1406                 wtxNew.AddSupportingTransactions();
1407                 wtxNew.fTimeReceivedIsTxTime = true;
1408
1409                 break;
1410             }
1411         }
1412     }
1413     return true;
1414 }
1415
1416 bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, const CCoinControl* coinControl)
1417 {
1418     vector< pair<CScript, int64> > vecSend;
1419     vecSend.push_back(make_pair(scriptPubKey, nValue));
1420     return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl);
1421 }
1422
1423 // NovaCoin: get current stake weight
1424 bool CWallet::GetStakeWeight(const CKeyStore& keystore, uint64& nMinWeight, uint64& nMaxWeight, uint64& nWeight)
1425 {
1426     // Choose coins to use
1427     int64 nBalance = GetBalance();
1428     int64 nReserveBalance = 0;
1429
1430     if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1431     {
1432         error("GetStakeWeight : invalid reserve balance amount");
1433         return false;
1434     }
1435
1436     if (nBalance <= nReserveBalance)
1437         return false;
1438
1439     vector<const CWalletTx*> vwtxPrev;
1440     set<pair<const CWalletTx*,unsigned int> > setCoins;
1441     int64 nValueIn = 0;
1442
1443     if (!SelectCoinsSimple(nBalance - nReserveBalance, GetTime(), nCoinbaseMaturity * 10, setCoins, nValueIn))
1444         return false;
1445
1446     if (setCoins.empty())
1447         return false;
1448
1449     CCoinsViewCache &view = *pcoinsTip;
1450     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1451     {
1452         CCoins coins;
1453         {
1454             LOCK2(cs_main, cs_wallet);
1455             if (!view.GetCoinsReadOnly(pcoin.first->GetHash(), coins))
1456                 continue;
1457         }
1458
1459         int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)GetTime());
1460         CBigNum bnCoinDayWeight = CBigNum(pcoin.first->vout[pcoin.second].nValue) * nTimeWeight / COIN / (24 * 60 * 60);
1461
1462         // Weight is greater than zero
1463         if (nTimeWeight > 0)
1464         {
1465             nWeight += bnCoinDayWeight.getuint64();
1466         }
1467
1468         // Weight is greater than zero, but the maximum value isn't reached yet
1469         if (nTimeWeight > 0 && nTimeWeight < nStakeMaxAge)
1470         {
1471             nMinWeight += bnCoinDayWeight.getuint64();
1472         }
1473
1474         // Maximum weight was reached
1475         if (nTimeWeight == nStakeMaxAge)
1476         {
1477             nMaxWeight += bnCoinDayWeight.getuint64();
1478         }
1479     }
1480
1481     return true;
1482 }
1483
1484 bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, CKey& key)
1485 {
1486     // The following combine threshold is important to security
1487     // Should not be adjusted if you don't understand the consequences
1488     int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3;
1489     CBlockIndex* pindexPrev = pindexBest;
1490     CBigNum bnTargetPerCoinDay;
1491     bnTargetPerCoinDay.SetCompact(nBits);
1492
1493     txNew.vin.clear();
1494     txNew.vout.clear();
1495
1496     // Mark coin stake transaction
1497     CScript scriptEmpty;
1498     scriptEmpty.clear();
1499     txNew.vout.push_back(CTxOut(0, scriptEmpty));
1500
1501     // Choose coins to use
1502     int64 nBalance = GetBalance();
1503     int64 nReserveBalance = 0;
1504
1505     if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance))
1506         return error("CreateCoinStake : invalid reserve balance amount");
1507
1508     if (nBalance <= nReserveBalance)
1509         return false;
1510
1511     vector<const CWalletTx*> vwtxPrev;
1512     set<pair<const CWalletTx*,unsigned int> > setCoins;
1513     int64 nValueIn = 0;
1514
1515     // Select coins with suitable depth
1516     if (!SelectCoinsSimple(nBalance - nReserveBalance, txNew.nTime, nCoinbaseMaturity * 10, setCoins, nValueIn))
1517         return false;
1518
1519     if (setCoins.empty())
1520         return false;
1521
1522     int64 nCredit = 0;
1523     CScript scriptPubKeyKernel;
1524
1525     CCoinsViewCache &view = *pcoinsTip;
1526     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1527     {
1528         CCoins coins;
1529         {
1530             LOCK2(cs_main, cs_wallet);
1531             if (!view.GetCoinsReadOnly(pcoin.first->GetHash(), coins))
1532                 continue;
1533         }
1534
1535         static int nMaxStakeSearchInterval = 60;
1536         if (coins.nBlockTime + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval)
1537             continue; // only count coins meeting min age requirement
1538
1539         // Read block header
1540         CBlock block;
1541         unsigned int nTxPos = 0;
1542         {
1543             LOCK2(cs_main, cs_wallet);
1544             CBlockIndex *pindex = FindBlockByHeight(coins.nHeight);
1545
1546             if (!block.ReadFromDisk(pindex))
1547                 continue;
1548
1549             BOOST_FOREACH(const CTransaction &tx, block.vtx) {
1550                 if (tx.GetHash() == pcoin.first->GetHash()) {
1551                     break;
1552                 }
1553                 nTxPos += tx.GetSerializeSize(SER_DISK, CLIENT_VERSION);
1554             }
1555             nTxPos += GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - (2 * GetSizeOfCompactSize(0)) + GetSizeOfCompactSize(block.vtx.size());
1556         }
1557
1558
1559         bool fFatal = false;
1560         bool fKernelFound = false;
1561         for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown && pindexPrev == pindexBest; n++)
1562         {
1563             // Search backward in time from the given txNew timestamp 
1564             // Search nSearchInterval seconds back up to nMaxStakeSearchInterval
1565             uint256 hashProofOfStake = 0, targetProofOfStake = 0;
1566             COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second);
1567             if (CheckStakeKernelHash(nBits, block, nTxPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake, targetProofOfStake, fFatal, true))
1568             {
1569                 // Found a kernel
1570                 if (fDebug && GetBoolArg("-printcoinstake"))
1571                     printf("CreateCoinStake : kernel found\n");
1572                 vector<valtype> vSolutions;
1573                 txnouttype whichType;
1574                 CScript scriptPubKeyOut;
1575                 scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey;
1576                 if (!Solver(scriptPubKeyKernel, whichType, vSolutions))
1577                 {
1578                     if (fDebug && GetBoolArg("-printcoinstake"))
1579                         printf("CreateCoinStake : failed to parse kernel\n");
1580                     break;
1581                 }
1582                 if (fDebug && GetBoolArg("-printcoinstake"))
1583                     printf("CreateCoinStake : parsed kernel type=%d\n", whichType);
1584                 if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH)
1585                 {
1586                     if (fDebug && GetBoolArg("-printcoinstake"))
1587                         printf("CreateCoinStake : no support for kernel type=%d\n", whichType);
1588                     break;  // only support pay to public key and pay to address
1589                 }
1590                 if (whichType == TX_PUBKEYHASH) // pay to address type
1591                 {
1592                     // convert to pay to public key type
1593                     if (!keystore.GetKey(uint160(vSolutions[0]), key))
1594                     {
1595                         if (fDebug && GetBoolArg("-printcoinstake"))
1596                             printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1597                         break;  // unable to find corresponding public key
1598                     }
1599                     scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG;
1600                 }
1601                 if (whichType == TX_PUBKEY)
1602                 {
1603                     valtype& vchPubKey = vSolutions[0];
1604                     if (!keystore.GetKey(Hash160(vchPubKey), key))
1605                     {
1606                         if (fDebug && GetBoolArg("-printcoinstake"))
1607                             printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType);
1608                         break;  // unable to find corresponding public key
1609                     }
1610
1611                 if (key.GetPubKey() != vchPubKey)
1612                 {
1613                     if (fDebug && GetBoolArg("-printcoinstake"))
1614                         printf("CreateCoinStake : invalid key for kernel type=%d\n", whichType);
1615                         break; // keys mismatch
1616                     }
1617
1618                     scriptPubKeyOut = scriptPubKeyKernel;
1619                 }
1620
1621                 txNew.nTime -= n;
1622                 txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1623                 nCredit += pcoin.first->vout[pcoin.second].nValue;
1624                 vwtxPrev.push_back(pcoin.first);
1625                 txNew.vout.push_back(CTxOut(0, scriptPubKeyOut));
1626
1627                 if (GetWeight(block.GetBlockTime(), (int64)txNew.nTime) < nStakeMaxAge)
1628                     txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake
1629                 if (fDebug && GetBoolArg("-printcoinstake"))
1630                     printf("CreateCoinStake : added kernel type=%d\n", whichType);
1631                 fKernelFound = true;
1632                 break;
1633             }
1634         }
1635
1636         if (fKernelFound || fShutdown)
1637             break; // if kernel is found stop searching
1638     }
1639
1640     if (nCredit == 0 || nCredit > nBalance - nReserveBalance)
1641         return false;
1642
1643     BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
1644     {
1645         // Attempt to add more inputs
1646         // Only add coins of the same key/address as kernel
1647         if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey))
1648             && pcoin.first->GetHash() != txNew.vin[0].prevout.hash)
1649         {
1650             int64 nTimeWeight = GetWeight((int64)pcoin.first->nTime, (int64)txNew.nTime);
1651
1652             // Stop adding more inputs if already too many inputs
1653             if (txNew.vin.size() >= 100)
1654                 break;
1655             // Stop adding more inputs if value is already pretty significant
1656             if (nCredit > nCombineThreshold)
1657                 break;
1658             // Stop adding inputs if reached reserve limit
1659             if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance)
1660                 break;
1661             // Do not add additional significant input
1662             if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold)
1663                 continue;
1664             // Do not add input that is still too young
1665             if (nTimeWeight < nStakeMaxAge)
1666                 continue;
1667
1668             txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second));
1669             nCredit += pcoin.first->vout[pcoin.second].nValue;
1670             vwtxPrev.push_back(pcoin.first);
1671         }
1672     }
1673
1674     // Calculate coin age reward
1675     {
1676         uint64 nCoinAge;
1677
1678         if (!txNew.GetCoinAge(nCoinAge))
1679             return error("CreateCoinStake : failed to calculate coin age");
1680         nCredit += GetProofOfStakeReward(nCoinAge, nBits, txNew.nTime);
1681     }
1682
1683     int64 nMinFee = 0;
1684     while (true)
1685     {
1686         // Set output amount
1687         if (txNew.vout.size() == 3)
1688         {
1689             txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT;
1690             txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue;
1691         }
1692         else
1693             txNew.vout[1].nValue = nCredit - nMinFee;
1694
1695         // Sign
1696         int nIn = 0;
1697         BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev)
1698         {
1699             if (!SignSignature(*this, *pcoin, txNew, nIn++))
1700                 return error("CreateCoinStake : failed to sign coinstake");
1701         }
1702
1703         // Limit size
1704         unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION);
1705         if (nBytes >= MAX_BLOCK_SIZE_GEN/5)
1706             return error("CreateCoinStake : exceeded coinstake size limit");
1707
1708         // Check enough fee is paid
1709         if (nMinFee < txNew.GetMinFee() - MIN_TX_FEE)
1710         {
1711             nMinFee = txNew.GetMinFee() - MIN_TX_FEE;
1712             continue; // try signing again
1713         }
1714         else
1715         {
1716             if (fDebug && GetBoolArg("-printfee"))
1717                 printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str());
1718             break;
1719         }
1720     }
1721
1722     // Successfully generated coinstake
1723     return true;
1724 }
1725
1726
1727 // Call after CreateTransaction unless you want to abort
1728 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
1729 {
1730     {
1731         LOCK2(cs_main, cs_wallet);
1732         printf("CommitTransaction:\n%s", wtxNew.ToString().c_str());
1733         {
1734             // This is only to keep the database open to defeat the auto-flush for the
1735             // duration of this scope.  This is the only place where this optimization
1736             // maybe makes sense; please don't do it anywhere else.
1737             CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL;
1738
1739             // Take key pair from key pool so it won't be used again
1740             reservekey.KeepKey();
1741
1742             // Add tx to wallet, because if it has change it's also ours,
1743             // otherwise just for transaction history.
1744             AddToWallet(wtxNew);
1745
1746             // Mark old coins as spent
1747             set<CWalletTx*> setCoins;
1748             BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
1749             {
1750                 CWalletTx &coin = mapWallet[txin.prevout.hash];
1751                 coin.BindWallet(this);
1752                 coin.MarkSpent(txin.prevout.n);
1753                 coin.WriteToDisk();
1754                 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
1755             }
1756
1757             if (fFileBacked)
1758                 delete pwalletdb;
1759         }
1760
1761         // Track how many getdata requests our transaction gets
1762         mapRequestCount[wtxNew.GetHash()] = 0;
1763
1764         // Broadcast
1765         if (!wtxNew.AcceptToMemoryPool())
1766         {
1767             // This must not fail. The transaction has already been signed and recorded.
1768             printf("CommitTransaction() : Error: Transaction not valid");
1769             return false;
1770         }
1771         wtxNew.RelayWalletTransaction();
1772     }
1773     return true;
1774 }
1775
1776
1777
1778
1779 string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1780 {
1781     CReserveKey reservekey(this);
1782     int64 nFeeRequired;
1783
1784     if (IsLocked())
1785     {
1786         string strError = _("Error: Wallet locked, unable to create transaction  ");
1787         printf("SendMoney() : %s", strError.c_str());
1788         return strError;
1789     }
1790     if (fWalletUnlockMintOnly)
1791     {
1792         string strError = _("Error: Wallet unlocked for block minting only, unable to create transaction.");
1793         printf("SendMoney() : %s", strError.c_str());
1794         return strError;
1795     }
1796     if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired))
1797     {
1798         string strError;
1799         if (nValue + nFeeRequired > GetBalance())
1800             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());
1801         else
1802             strError = _("Error: Transaction creation failed  ");
1803         printf("SendMoney() : %s", strError.c_str());
1804         return strError;
1805     }
1806
1807     if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending...")))
1808         return "ABORTED";
1809
1810     if (!CommitTransaction(wtxNew, reservekey))
1811         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.");
1812
1813     return "";
1814 }
1815
1816
1817
1818 string CWallet::SendMoneyToDestination(const CTxDestination& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee)
1819 {
1820     // Check amount
1821     if (nValue <= 0)
1822         return _("Invalid amount");
1823     if (nValue + nTransactionFee > GetBalance())
1824         return _("Insufficient funds");
1825
1826     // Parse Bitcoin address
1827     CScript scriptPubKey;
1828     scriptPubKey.SetDestination(address);
1829
1830     return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee);
1831 }
1832
1833
1834
1835
1836 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
1837 {
1838     if (!fFileBacked)
1839         return DB_LOAD_OK;
1840     fFirstRunRet = false;
1841     DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
1842     if (nLoadWalletRet == DB_NEED_REWRITE)
1843     {
1844         if (CDB::Rewrite(strWalletFile, "\x04pool"))
1845         {
1846             setKeyPool.clear();
1847             // Note: can't top-up keypool here, because wallet is locked.
1848             // User will be prompted to unlock wallet the next operation
1849             // the requires a new key.
1850         }
1851     }
1852
1853     if (nLoadWalletRet != DB_LOAD_OK)
1854         return nLoadWalletRet;
1855     fFirstRunRet = !vchDefaultKey.IsValid();
1856
1857     NewThread(ThreadFlushWalletDB, &strWalletFile);
1858     return DB_LOAD_OK;
1859 }
1860
1861
1862 bool CWallet::SetAddressBookName(const CTxDestination& address, const string& strName)
1863 {
1864     std::map<CTxDestination, std::string>::iterator mi = mapAddressBook.find(address);
1865     mapAddressBook[address] = strName;
1866     NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address), (mi == mapAddressBook.end()) ? CT_NEW : CT_UPDATED);
1867     if (!fFileBacked)
1868         return false;
1869     return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
1870 }
1871
1872 bool CWallet::DelAddressBookName(const CTxDestination& address)
1873 {
1874     mapAddressBook.erase(address);
1875     NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address), CT_DELETED);
1876     if (!fFileBacked)
1877         return false;
1878     return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
1879 }
1880
1881
1882 void CWallet::PrintWallet(const CBlock& block)
1883 {
1884     {
1885         LOCK(cs_wallet);
1886         if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash()))
1887         {
1888             CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
1889             printf("    mine:  %d  %d  %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1890         }
1891         if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash()))
1892         {
1893             CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()];
1894             printf("    stake: %d  %d  %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
1895          }
1896
1897     }
1898     printf("\n");
1899 }
1900
1901 bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx)
1902 {
1903     {
1904         LOCK(cs_wallet);
1905         map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx);
1906         if (mi != mapWallet.end())
1907         {
1908             wtx = (*mi).second;
1909             return true;
1910         }
1911     }
1912     return false;
1913 }
1914
1915 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
1916 {
1917     if (fFileBacked)
1918     {
1919         if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
1920             return false;
1921     }
1922     vchDefaultKey = vchPubKey;
1923     return true;
1924 }
1925
1926 bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut)
1927 {
1928     if (!pwallet->fFileBacked)
1929         return false;
1930     strWalletFileOut = pwallet->strWalletFile;
1931     return true;
1932 }
1933
1934 //
1935 // Mark old keypool keys as used,
1936 // and generate all new keys
1937 //
1938 bool CWallet::NewKeyPool()
1939 {
1940     {
1941         LOCK(cs_wallet);
1942         CWalletDB walletdb(strWalletFile);
1943         BOOST_FOREACH(int64 nIndex, setKeyPool)
1944             walletdb.ErasePool(nIndex);
1945         setKeyPool.clear();
1946
1947         if (IsLocked())
1948             return false;
1949
1950         int64 nKeys = max(GetArg("-keypool", 100), (int64)0);
1951         for (int i = 0; i < nKeys; i++)
1952         {
1953             int64 nIndex = i+1;
1954             walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
1955             setKeyPool.insert(nIndex);
1956         }
1957         printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
1958     }
1959     return true;
1960 }
1961
1962 bool CWallet::TopUpKeyPool(unsigned int nSize)
1963 {
1964     {
1965         LOCK(cs_wallet);
1966
1967         if (IsLocked())
1968             return false;
1969
1970         CWalletDB walletdb(strWalletFile);
1971
1972         // Top up key pool
1973         unsigned int nTargetSize;
1974         if (nSize > 0)
1975             nTargetSize = nSize;
1976         else
1977             nTargetSize = max(GetArg("-keypool", 100), 0LL);
1978
1979         while (setKeyPool.size() < (nTargetSize + 1))
1980         {
1981             int64 nEnd = 1;
1982             if (!setKeyPool.empty())
1983                 nEnd = *(--setKeyPool.end()) + 1;
1984             if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
1985                 throw runtime_error("TopUpKeyPool() : writing generated key failed");
1986             setKeyPool.insert(nEnd);
1987             printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
1988         }
1989     }
1990     return true;
1991 }
1992
1993 void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
1994 {
1995     nIndex = -1;
1996     keypool.vchPubKey = CPubKey();
1997     {
1998         LOCK(cs_wallet);
1999
2000         if (!IsLocked())
2001             TopUpKeyPool();
2002
2003         // Get the oldest key
2004         if(setKeyPool.empty())
2005             return;
2006
2007         CWalletDB walletdb(strWalletFile);
2008
2009         nIndex = *(setKeyPool.begin());
2010         setKeyPool.erase(setKeyPool.begin());
2011         if (!walletdb.ReadPool(nIndex, keypool))
2012             throw runtime_error("ReserveKeyFromKeyPool() : read failed");
2013         if (!HaveKey(keypool.vchPubKey.GetID()))
2014             throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
2015         assert(keypool.vchPubKey.IsValid());
2016         if (fDebug && GetBoolArg("-printkeypool"))
2017             printf("keypool reserve %"PRI64d"\n", nIndex);
2018     }
2019 }
2020
2021 int64 CWallet::AddReserveKey(const CKeyPool& keypool)
2022 {
2023     {
2024         LOCK2(cs_main, cs_wallet);
2025         CWalletDB walletdb(strWalletFile);
2026
2027         int64 nIndex = 1 + *(--setKeyPool.end());
2028         if (!walletdb.WritePool(nIndex, keypool))
2029             throw runtime_error("AddReserveKey() : writing added key failed");
2030         setKeyPool.insert(nIndex);
2031         return nIndex;
2032     }
2033     return -1;
2034 }
2035
2036 void CWallet::KeepKey(int64 nIndex)
2037 {
2038     // Remove from key pool
2039     if (fFileBacked)
2040     {
2041         CWalletDB walletdb(strWalletFile);
2042         walletdb.ErasePool(nIndex);
2043     }
2044     if(fDebug)
2045         printf("keypool keep %"PRI64d"\n", nIndex);
2046 }
2047
2048 void CWallet::ReturnKey(int64 nIndex)
2049 {
2050     // Return to key pool
2051     {
2052         LOCK(cs_wallet);
2053         setKeyPool.insert(nIndex);
2054     }
2055     if(fDebug)
2056         printf("keypool return %"PRI64d"\n", nIndex);
2057 }
2058
2059 bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)
2060 {
2061     int64 nIndex = 0;
2062     CKeyPool keypool;
2063     {
2064         LOCK(cs_wallet);
2065         ReserveKeyFromKeyPool(nIndex, keypool);
2066         if (nIndex == -1)
2067         {
2068             if (fAllowReuse && vchDefaultKey.IsValid())
2069             {
2070                 result = vchDefaultKey;
2071                 return true;
2072             }
2073             if (IsLocked()) return false;
2074             result = GenerateNewKey();
2075             return true;
2076         }
2077         KeepKey(nIndex);
2078         result = keypool.vchPubKey;
2079     }
2080     return true;
2081 }
2082
2083 int64 CWallet::GetOldestKeyPoolTime()
2084 {
2085     int64 nIndex = 0;
2086     CKeyPool keypool;
2087     ReserveKeyFromKeyPool(nIndex, keypool);
2088     if (nIndex == -1)
2089         return GetTime();
2090     ReturnKey(nIndex);
2091     return keypool.nTime;
2092 }
2093
2094 std::map<CTxDestination, int64> CWallet::GetAddressBalances()
2095 {
2096     map<CTxDestination, int64> balances;
2097
2098     {
2099         LOCK(cs_wallet);
2100         BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2101         {
2102             CWalletTx *pcoin = &walletEntry.second;
2103
2104             if (!pcoin->IsFinal() || !pcoin->IsConfirmed())
2105                 continue;
2106
2107             if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0)
2108                 continue;
2109
2110             int nDepth = pcoin->GetDepthInMainChain();
2111             if (nDepth < (pcoin->IsFromMe() ? 0 : 1))
2112                 continue;
2113
2114             for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2115             {
2116                 CTxDestination addr;
2117                 if (!IsMine(pcoin->vout[i]))
2118                     continue;
2119                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2120                     continue;
2121
2122                 int64 n = pcoin->IsSpent(i) ? 0 : pcoin->vout[i].nValue;
2123
2124                 if (!balances.count(addr))
2125                     balances[addr] = 0;
2126                 balances[addr] += n;
2127             }
2128         }
2129     }
2130
2131     return balances;
2132 }
2133
2134 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2135 {
2136     set< set<CTxDestination> > groupings;
2137     set<CTxDestination> grouping;
2138
2139     BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2140     {
2141         CWalletTx *pcoin = &walletEntry.second;
2142
2143         if (pcoin->vin.size() > 0 && IsMine(pcoin->vin[0]))
2144         {
2145             // group all input addresses with each other
2146             BOOST_FOREACH(CTxIn txin, pcoin->vin)
2147             {
2148                 CTxDestination address;
2149                 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2150                     continue;
2151                 grouping.insert(address);
2152             }
2153
2154             // group change with input addresses
2155             BOOST_FOREACH(CTxOut txout, pcoin->vout)
2156                 if (IsChange(txout))
2157                 {
2158                     CWalletTx tx = mapWallet[pcoin->vin[0].prevout.hash];
2159                     CTxDestination txoutAddr;
2160                     if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2161                         continue;
2162                     grouping.insert(txoutAddr);
2163                 }
2164             groupings.insert(grouping);
2165             grouping.clear();
2166         }
2167
2168         // group lone addrs by themselves
2169         for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2170             if (IsMine(pcoin->vout[i]))
2171             {
2172                 CTxDestination address;
2173                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2174                     continue;
2175                 grouping.insert(address);
2176                 groupings.insert(grouping);
2177                 grouping.clear();
2178             }
2179     }
2180
2181     set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2182     map< CTxDestination, set<CTxDestination>* > setmap;  // map addresses to the unique group containing it
2183     BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2184     {
2185         // make a set of all the groups hit by this new group
2186         set< set<CTxDestination>* > hits;
2187         map< CTxDestination, set<CTxDestination>* >::iterator it;
2188         BOOST_FOREACH(CTxDestination address, grouping)
2189             if ((it = setmap.find(address)) != setmap.end())
2190                 hits.insert((*it).second);
2191
2192         // merge all hit groups into a new single group and delete old groups
2193         set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2194         BOOST_FOREACH(set<CTxDestination>* hit, hits)
2195         {
2196             merged->insert(hit->begin(), hit->end());
2197             uniqueGroupings.erase(hit);
2198             delete hit;
2199         }
2200         uniqueGroupings.insert(merged);
2201
2202         // update setmap
2203         BOOST_FOREACH(CTxDestination element, *merged)
2204             setmap[element] = merged;
2205     }
2206
2207     set< set<CTxDestination> > ret;
2208     BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2209     {
2210         ret.insert(*uniqueGrouping);
2211         delete uniqueGrouping;
2212     }
2213
2214     return ret;
2215 }
2216
2217 // ppcoin: check 'spent' consistency between wallet and txindex
2218 // ppcoin: fix wallet spent state according to txindex
2219 void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly)
2220 {
2221     nMismatchFound = 0;
2222     nBalanceInQuestion = 0;
2223
2224     LOCK(cs_wallet);
2225     vector<CWalletTx*> vCoins;
2226     vCoins.reserve(mapWallet.size());
2227     for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2228         vCoins.push_back(&(*it).second);
2229
2230     CCoinsViewCache &view = *pcoinsTip;
2231     BOOST_FOREACH(CWalletTx* pcoin, vCoins)
2232     {
2233         // Find the corresponding transaction index
2234         CCoins coins;
2235
2236         bool fNotFound = view.GetCoins(pcoin->GetHash(), coins);
2237
2238         for (unsigned int n=0; n < pcoin->vout.size(); n++)
2239         {
2240             if (!fNotFound && IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && coins.IsAvailable(n))
2241             {
2242                 printf("FixSpentCoins found lost coin %sppc %s[%d], %s\n",
2243                     FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2244                 nMismatchFound++;
2245                 nBalanceInQuestion += pcoin->vout[n].nValue;
2246                 if (!fCheckOnly)
2247                 {
2248                     pcoin->MarkUnspent(n);
2249                     pcoin->WriteToDisk();
2250                 }
2251             }
2252             else if (!fNotFound && IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && coins.IsAvailable(n))
2253             {
2254                 printf("FixSpentCoins found spent coin %sppc %s[%d], %s\n",
2255                     FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing");
2256                 nMismatchFound++;
2257                 nBalanceInQuestion += pcoin->vout[n].nValue;
2258                 if (!fCheckOnly)
2259                 {
2260                     pcoin->MarkSpent(n);
2261                     pcoin->WriteToDisk();
2262                 }
2263             }
2264
2265         }
2266
2267         if(IsMine((CTransaction)*pcoin) && (pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetDepthInMainChain() == 0)
2268         {
2269             printf("FixSpentCoins %s tx %s\n", fCheckOnly ? "found" : "removed", pcoin->GetHash().ToString().c_str());
2270             if (!fCheckOnly)
2271             {
2272                 EraseFromWallet(pcoin->GetHash());
2273             }
2274         }
2275     }
2276 }
2277
2278 // ppcoin: disable transaction (only for coinstake)
2279 void CWallet::DisableTransaction(const CTransaction &tx)
2280 {
2281     if (!tx.IsCoinStake() || !IsFromMe(tx))
2282         return; // only disconnecting coinstake requires marking input unspent
2283
2284     LOCK(cs_wallet);
2285     BOOST_FOREACH(const CTxIn& txin, tx.vin)
2286     {
2287         map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash);
2288         if (mi != mapWallet.end())
2289         {
2290             CWalletTx& prev = (*mi).second;
2291             if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n]))
2292             {
2293                 prev.MarkUnspent(txin.prevout.n);
2294                 prev.WriteToDisk();
2295             }
2296         }
2297     }
2298 }
2299
2300 CPubKey CReserveKey::GetReservedKey()
2301 {
2302     if (nIndex == -1)
2303     {
2304         CKeyPool keypool;
2305         pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
2306         if (nIndex != -1)
2307             vchPubKey = keypool.vchPubKey;
2308         else
2309         {
2310             printf("CReserveKey::GetReservedKey(): Warning: Using default key instead of a new key, top up your keypool!");
2311             vchPubKey = pwallet->vchDefaultKey;
2312         }
2313     }
2314     assert(vchPubKey.IsValid());
2315     return vchPubKey;
2316 }
2317
2318 void CReserveKey::KeepKey()
2319 {
2320     if (nIndex != -1)
2321         pwallet->KeepKey(nIndex);
2322     nIndex = -1;
2323     vchPubKey = CPubKey();
2324 }
2325
2326 void CReserveKey::ReturnKey()
2327 {
2328     if (nIndex != -1)
2329         pwallet->ReturnKey(nIndex);
2330     nIndex = -1;
2331     vchPubKey = CPubKey();
2332 }
2333
2334 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
2335 {
2336     setAddress.clear();
2337
2338     CWalletDB walletdb(strWalletFile);
2339
2340     LOCK2(cs_main, cs_wallet);
2341     BOOST_FOREACH(const int64& id, setKeyPool)
2342     {
2343         CKeyPool keypool;
2344         if (!walletdb.ReadPool(id, keypool))
2345             throw runtime_error("GetAllReserveKeyHashes() : read failed");
2346         assert(keypool.vchPubKey.IsValid());
2347         CKeyID keyID = keypool.vchPubKey.GetID();
2348         if (!HaveKey(keyID))
2349             throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool");
2350         setAddress.insert(keyID);
2351     }
2352 }
2353
2354 void CWallet::UpdatedTransaction(const uint256 &hashTx)
2355 {
2356     {
2357         LOCK(cs_wallet);
2358         // Only notify UI if this transaction is in this wallet
2359         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
2360         if (mi != mapWallet.end())
2361             NotifyTransactionChanged(this, hashTx, CT_UPDATED);
2362     }
2363 }
2364
2365 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64> &mapKeyBirth) const {
2366     mapKeyBirth.clear();
2367
2368     // get birth times for keys with metadata
2369     for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
2370         if (it->second.nCreateTime)
2371             mapKeyBirth[it->first] = it->second.nCreateTime;
2372
2373     // map in which we'll infer heights of other keys
2374     CBlockIndex *pindexMax = FindBlockByHeight(std::max(0, nBestHeight - 144)); // the tip can be reorganised; use a 144-block safety margin
2375     std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
2376     std::set<CKeyID> setKeys;
2377     GetKeys(setKeys);
2378     BOOST_FOREACH(const CKeyID &keyid, setKeys) {
2379         if (mapKeyBirth.count(keyid) == 0)
2380             mapKeyFirstBlock[keyid] = pindexMax;
2381     }
2382     setKeys.clear();
2383
2384     // if there are no such keys, we're done
2385     if (mapKeyFirstBlock.empty())
2386         return;
2387
2388     // find first block that affects those keys, if there are any left
2389     std::vector<CKeyID> vAffected;
2390     for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
2391         // iterate over all wallet transactions...
2392         const CWalletTx &wtx = (*it).second;
2393         std::map<uint256, CBlockIndex*>::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
2394         if (blit != mapBlockIndex.end() && blit->second->IsInMainChain()) {
2395             // ... which are already in a block
2396             int nHeight = blit->second->nHeight;
2397             BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
2398                 // iterate over all their outputs
2399                 ::ExtractAffectedKeys(*this, txout.scriptPubKey, vAffected);
2400                 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
2401                     // ... and all their affected keys
2402                     std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
2403                     if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
2404                         rit->second = blit->second;
2405                 }
2406                 vAffected.clear();
2407             }
2408         }
2409     }
2410
2411     // Extract block timestamps for those keys
2412     for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
2413         mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off
2414 }