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