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