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