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