1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include "wallet/wallet.h"
7 
8 #include "base58.h"
9 #include "checkpoints.h"
10 #include "chain.h"
11 #include "coincontrol.h"
12 #include "consensus/consensus.h"
13 #include "consensus/validation.h"
14 #include "key.h"
15 #include "keystore.h"
16 #include "main.h"
17 #include "net.h"
18 #include "policy/policy.h"
19 #include "primitives/block.h"
20 #include "primitives/transaction.h"
21 #include "script/script.h"
22 #include "script/sign.h"
23 #include "timedata.h"
24 #include "txmempool.h"
25 #include "util.h"
26 #include "ui_interface.h"
27 #include "utilmoneystr.h"
28 
29 #include <assert.h>
30 
31 #include <boost/algorithm/string/replace.hpp>
32 #include <boost/filesystem.hpp>
33 #include <boost/thread.hpp>
34 
35 using namespace std;
36 
37 CWallet* pwalletMain = NULL;
38 /** Transaction fee set by the user */
39 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
40 unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
41 bool bSpendZeroConfChange = DEFAULT_SPEND_ZEROCONF_CHANGE;
42 bool fSendFreeTransactions = DEFAULT_SEND_FREE_TRANSACTIONS;
43 
44 const char * DEFAULT_WALLET_DAT = "wallet.dat";
45 const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
46 
47 /**
48  * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
49  * Override with -mintxfee
50  */
51 CFeeRate CWallet::minTxFee = CFeeRate(DEFAULT_TRANSACTION_MINFEE);
52 /**
53  * If fee estimation does not have enough data to provide estimates, use this fee instead.
54  * Has no effect if not using fee estimation
55  * Override with -fallbackfee
56  */
57 CFeeRate CWallet::fallbackFee = CFeeRate(DEFAULT_FALLBACK_FEE);
58 
59 const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
60 
61 /** @defgroup mapWallet
62  *
63  * @{
64  */
65 
66 struct CompareValueOnly
67 {
operator ()CompareValueOnly68     bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
69                     const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
70     {
71         return t1.first < t2.first;
72     }
73 };
74 
ToString() const75 std::string COutput::ToString() const
76 {
77     return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue));
78 }
79 
GetWalletTx(const uint256 & hash) const80 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
81 {
82     LOCK(cs_wallet);
83     std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
84     if (it == mapWallet.end())
85         return NULL;
86     return &(it->second);
87 }
88 
GenerateNewKey()89 CPubKey CWallet::GenerateNewKey()
90 {
91     AssertLockHeld(cs_wallet); // mapKeyMetadata
92     bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
93 
94     CKey secret;
95 
96     // Create new metadata
97     int64_t nCreationTime = GetTime();
98     CKeyMetadata metadata(nCreationTime);
99 
100     // use HD key derivation if HD was enabled during wallet creation
101     if (!hdChain.masterKeyID.IsNull()) {
102         // for now we use a fixed keypath scheme of m/0'/0'/k
103         CKey key;                      //master key seed (256bit)
104         CExtKey masterKey;             //hd master key
105         CExtKey accountKey;            //key at m/0'
106         CExtKey externalChainChildKey; //key at m/0'/0'
107         CExtKey childKey;              //key at m/0'/0'/<n>'
108 
109         // try to get the master key
110         if (!GetKey(hdChain.masterKeyID, key))
111             throw std::runtime_error(std::string(__func__) + ": Master key not found");
112 
113         masterKey.SetMaster(key.begin(), key.size());
114 
115         // derive m/0'
116         // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
117         masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
118 
119         // derive m/0'/0'
120         accountKey.Derive(externalChainChildKey, BIP32_HARDENED_KEY_LIMIT);
121 
122         // derive child key at next index, skip keys already known to the wallet
123         do
124         {
125             // always derive hardened keys
126             // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
127             // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
128             externalChainChildKey.Derive(childKey, hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
129             metadata.hdKeypath     = "m/0'/0'/"+std::to_string(hdChain.nExternalChainCounter)+"'";
130             metadata.hdMasterKeyID = hdChain.masterKeyID;
131             // increment childkey index
132             hdChain.nExternalChainCounter++;
133         } while(HaveKey(childKey.key.GetPubKey().GetID()));
134         secret = childKey.key;
135 
136         // update the chain model in the database
137         if (!CWalletDB(strWalletFile).WriteHDChain(hdChain))
138             throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
139     } else {
140         secret.MakeNewKey(fCompressed);
141     }
142 
143     // Compressed public keys were introduced in version 0.6.0
144     if (fCompressed)
145         SetMinVersion(FEATURE_COMPRPUBKEY);
146 
147     CPubKey pubkey = secret.GetPubKey();
148     assert(secret.VerifyPubKey(pubkey));
149 
150     mapKeyMetadata[pubkey.GetID()] = metadata;
151     if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
152         nTimeFirstKey = nCreationTime;
153 
154     if (!AddKeyPubKey(secret, pubkey))
155         throw std::runtime_error(std::string(__func__) + ": AddKey failed");
156     return pubkey;
157 }
158 
AddKeyPubKey(const CKey & secret,const CPubKey & pubkey)159 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
160 {
161     AssertLockHeld(cs_wallet); // mapKeyMetadata
162     if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
163         return false;
164 
165     // check if we need to remove from watch-only
166     CScript script;
167     script = GetScriptForDestination(pubkey.GetID());
168     if (HaveWatchOnly(script))
169         RemoveWatchOnly(script);
170     script = GetScriptForRawPubKey(pubkey);
171     if (HaveWatchOnly(script))
172         RemoveWatchOnly(script);
173 
174     if (!fFileBacked)
175         return true;
176     if (!IsCrypted()) {
177         return CWalletDB(strWalletFile).WriteKey(pubkey,
178                                                  secret.GetPrivKey(),
179                                                  mapKeyMetadata[pubkey.GetID()]);
180     }
181     return true;
182 }
183 
AddCryptedKey(const CPubKey & vchPubKey,const vector<unsigned char> & vchCryptedSecret)184 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
185                             const vector<unsigned char> &vchCryptedSecret)
186 {
187     if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
188         return false;
189     if (!fFileBacked)
190         return true;
191     {
192         LOCK(cs_wallet);
193         if (pwalletdbEncryption)
194             return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
195                                                         vchCryptedSecret,
196                                                         mapKeyMetadata[vchPubKey.GetID()]);
197         else
198             return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
199                                                             vchCryptedSecret,
200                                                             mapKeyMetadata[vchPubKey.GetID()]);
201     }
202     return false;
203 }
204 
LoadKeyMetadata(const CPubKey & pubkey,const CKeyMetadata & meta)205 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
206 {
207     AssertLockHeld(cs_wallet); // mapKeyMetadata
208     if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
209         nTimeFirstKey = meta.nCreateTime;
210 
211     mapKeyMetadata[pubkey.GetID()] = meta;
212     return true;
213 }
214 
LoadCryptedKey(const CPubKey & vchPubKey,const std::vector<unsigned char> & vchCryptedSecret)215 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
216 {
217     return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
218 }
219 
AddCScript(const CScript & redeemScript)220 bool CWallet::AddCScript(const CScript& redeemScript)
221 {
222     if (!CCryptoKeyStore::AddCScript(redeemScript))
223         return false;
224     if (!fFileBacked)
225         return true;
226     return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
227 }
228 
LoadCScript(const CScript & redeemScript)229 bool CWallet::LoadCScript(const CScript& redeemScript)
230 {
231     /* A sanity check was added in pull #3843 to avoid adding redeemScripts
232      * that never can be redeemed. However, old wallets may still contain
233      * these. Do not add them to the wallet and warn. */
234     if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
235     {
236         std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
237         LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
238             __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
239         return true;
240     }
241 
242     return CCryptoKeyStore::AddCScript(redeemScript);
243 }
244 
AddWatchOnly(const CScript & dest)245 bool CWallet::AddWatchOnly(const CScript &dest)
246 {
247     if (!CCryptoKeyStore::AddWatchOnly(dest))
248         return false;
249     nTimeFirstKey = 1; // No birthday information for watch-only keys.
250     NotifyWatchonlyChanged(true);
251     if (!fFileBacked)
252         return true;
253     return CWalletDB(strWalletFile).WriteWatchOnly(dest);
254 }
255 
RemoveWatchOnly(const CScript & dest)256 bool CWallet::RemoveWatchOnly(const CScript &dest)
257 {
258     AssertLockHeld(cs_wallet);
259     if (!CCryptoKeyStore::RemoveWatchOnly(dest))
260         return false;
261     if (!HaveWatchOnly())
262         NotifyWatchonlyChanged(false);
263     if (fFileBacked)
264         if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
265             return false;
266 
267     return true;
268 }
269 
LoadWatchOnly(const CScript & dest)270 bool CWallet::LoadWatchOnly(const CScript &dest)
271 {
272     return CCryptoKeyStore::AddWatchOnly(dest);
273 }
274 
Unlock(const SecureString & strWalletPassphrase)275 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
276 {
277     CCrypter crypter;
278     CKeyingMaterial vMasterKey;
279 
280     {
281         LOCK(cs_wallet);
282         BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
283         {
284             if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
285                 return false;
286             if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
287                 continue; // try another master key
288             if (CCryptoKeyStore::Unlock(vMasterKey))
289                 return true;
290         }
291     }
292     return false;
293 }
294 
ChangeWalletPassphrase(const SecureString & strOldWalletPassphrase,const SecureString & strNewWalletPassphrase)295 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
296 {
297     bool fWasLocked = IsLocked();
298 
299     {
300         LOCK(cs_wallet);
301         Lock();
302 
303         CCrypter crypter;
304         CKeyingMaterial vMasterKey;
305         BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
306         {
307             if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
308                 return false;
309             if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
310                 return false;
311             if (CCryptoKeyStore::Unlock(vMasterKey))
312             {
313                 int64_t nStartTime = GetTimeMillis();
314                 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
315                 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
316 
317                 nStartTime = GetTimeMillis();
318                 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
319                 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
320 
321                 if (pMasterKey.second.nDeriveIterations < 25000)
322                     pMasterKey.second.nDeriveIterations = 25000;
323 
324                 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
325 
326                 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
327                     return false;
328                 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
329                     return false;
330                 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
331                 if (fWasLocked)
332                     Lock();
333                 return true;
334             }
335         }
336     }
337 
338     return false;
339 }
340 
SetBestChain(const CBlockLocator & loc)341 void CWallet::SetBestChain(const CBlockLocator& loc)
342 {
343     CWalletDB walletdb(strWalletFile);
344     walletdb.WriteBestBlock(loc);
345 }
346 
SetMinVersion(enum WalletFeature nVersion,CWalletDB * pwalletdbIn,bool fExplicit)347 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
348 {
349     LOCK(cs_wallet); // nWalletVersion
350     if (nWalletVersion >= nVersion)
351         return true;
352 
353     // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
354     if (fExplicit && nVersion > nWalletMaxVersion)
355             nVersion = FEATURE_LATEST;
356 
357     nWalletVersion = nVersion;
358 
359     if (nVersion > nWalletMaxVersion)
360         nWalletMaxVersion = nVersion;
361 
362     if (fFileBacked)
363     {
364         CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
365         if (nWalletVersion > 40000)
366             pwalletdb->WriteMinVersion(nWalletVersion);
367         if (!pwalletdbIn)
368             delete pwalletdb;
369     }
370 
371     return true;
372 }
373 
SetMaxVersion(int nVersion)374 bool CWallet::SetMaxVersion(int nVersion)
375 {
376     LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
377     // cannot downgrade below current version
378     if (nWalletVersion > nVersion)
379         return false;
380 
381     nWalletMaxVersion = nVersion;
382 
383     return true;
384 }
385 
GetConflicts(const uint256 & txid) const386 set<uint256> CWallet::GetConflicts(const uint256& txid) const
387 {
388     set<uint256> result;
389     AssertLockHeld(cs_wallet);
390 
391     std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
392     if (it == mapWallet.end())
393         return result;
394     const CWalletTx& wtx = it->second;
395 
396     std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
397 
398     BOOST_FOREACH(const CTxIn& txin, wtx.vin)
399     {
400         if (mapTxSpends.count(txin.prevout) <= 1)
401             continue;  // No conflict if zero or one spends
402         range = mapTxSpends.equal_range(txin.prevout);
403         for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
404             result.insert(it->second);
405     }
406     return result;
407 }
408 
Flush(bool shutdown)409 void CWallet::Flush(bool shutdown)
410 {
411     bitdb.Flush(shutdown);
412 }
413 
Verify()414 bool CWallet::Verify()
415 {
416     LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
417     std::string walletFile = GetArg("-wallet", DEFAULT_WALLET_DAT);
418 
419     LogPrintf("Using wallet %s\n", walletFile);
420     uiInterface.InitMessage(_("Verifying wallet..."));
421 
422     // Wallet file must be a plain filename without a directory
423     if (walletFile != boost::filesystem::basename(walletFile) + boost::filesystem::extension(walletFile))
424         return InitError(strprintf(_("Wallet %s resides outside data directory %s"), walletFile, GetDataDir().string()));
425 
426     if (!bitdb.Open(GetDataDir()))
427     {
428         // try moving the database env out of the way
429         boost::filesystem::path pathDatabase = GetDataDir() / "database";
430         boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
431         try {
432             boost::filesystem::rename(pathDatabase, pathDatabaseBak);
433             LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
434         } catch (const boost::filesystem::filesystem_error&) {
435             // failure is ok (well, not really, but it's not worse than what we started with)
436         }
437 
438         // try again
439         if (!bitdb.Open(GetDataDir())) {
440             // if it still fails, it probably means we can't even create the database env
441             return InitError(strprintf(_("Error initializing wallet database environment %s!"), GetDataDir()));
442         }
443     }
444 
445     if (GetBoolArg("-salvagewallet", false))
446     {
447         // Recover readable keypairs:
448         if (!CWalletDB::Recover(bitdb, walletFile, true))
449             return false;
450     }
451 
452     if (boost::filesystem::exists(GetDataDir() / walletFile))
453     {
454         CDBEnv::VerifyResult r = bitdb.Verify(walletFile, CWalletDB::Recover);
455         if (r == CDBEnv::RECOVER_OK)
456         {
457             InitWarning(strprintf(_("Warning: Wallet file corrupt, data salvaged!"
458                                          " Original %s saved as %s in %s; if"
459                                          " your balance or transactions are incorrect you should"
460                                          " restore from a backup."),
461                 walletFile, "wallet.{timestamp}.bak", GetDataDir()));
462         }
463         if (r == CDBEnv::RECOVER_FAIL)
464             return InitError(strprintf(_("%s corrupt, salvage failed"), walletFile));
465     }
466 
467     return true;
468 }
469 
SyncMetaData(pair<TxSpends::iterator,TxSpends::iterator> range)470 void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range)
471 {
472     // We want all the wallet transactions in range to have the same metadata as
473     // the oldest (smallest nOrderPos).
474     // So: find smallest nOrderPos:
475 
476     int nMinOrderPos = std::numeric_limits<int>::max();
477     const CWalletTx* copyFrom = NULL;
478     for (TxSpends::iterator it = range.first; it != range.second; ++it)
479     {
480         const uint256& hash = it->second;
481         int n = mapWallet[hash].nOrderPos;
482         if (n < nMinOrderPos)
483         {
484             nMinOrderPos = n;
485             copyFrom = &mapWallet[hash];
486         }
487     }
488     // Now copy data from copyFrom to rest:
489     for (TxSpends::iterator it = range.first; it != range.second; ++it)
490     {
491         const uint256& hash = it->second;
492         CWalletTx* copyTo = &mapWallet[hash];
493         if (copyFrom == copyTo) continue;
494         if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
495         copyTo->mapValue = copyFrom->mapValue;
496         copyTo->vOrderForm = copyFrom->vOrderForm;
497         // fTimeReceivedIsTxTime not copied on purpose
498         // nTimeReceived not copied on purpose
499         copyTo->nTimeSmart = copyFrom->nTimeSmart;
500         copyTo->fFromMe = copyFrom->fFromMe;
501         copyTo->strFromAccount = copyFrom->strFromAccount;
502         // nOrderPos not copied on purpose
503         // cached members not copied on purpose
504     }
505 }
506 
507 /**
508  * Outpoint is spent if any non-conflicted transaction
509  * spends it:
510  */
IsSpent(const uint256 & hash,unsigned int n) const511 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
512 {
513     const COutPoint outpoint(hash, n);
514     pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
515     range = mapTxSpends.equal_range(outpoint);
516 
517     for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
518     {
519         const uint256& wtxid = it->second;
520         std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
521         if (mit != mapWallet.end()) {
522             int depth = mit->second.GetDepthInMainChain();
523             if (depth > 0  || (depth == 0 && !mit->second.isAbandoned()))
524                 return true; // Spent
525         }
526     }
527     return false;
528 }
529 
AddToSpends(const COutPoint & outpoint,const uint256 & wtxid)530 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
531 {
532     mapTxSpends.insert(make_pair(outpoint, wtxid));
533 
534     pair<TxSpends::iterator, TxSpends::iterator> range;
535     range = mapTxSpends.equal_range(outpoint);
536     SyncMetaData(range);
537 }
538 
539 
AddToSpends(const uint256 & wtxid)540 void CWallet::AddToSpends(const uint256& wtxid)
541 {
542     assert(mapWallet.count(wtxid));
543     CWalletTx& thisTx = mapWallet[wtxid];
544     if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
545         return;
546 
547     BOOST_FOREACH(const CTxIn& txin, thisTx.vin)
548         AddToSpends(txin.prevout, wtxid);
549 }
550 
EncryptWallet(const SecureString & strWalletPassphrase)551 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
552 {
553     if (IsCrypted())
554         return false;
555 
556     CKeyingMaterial vMasterKey;
557 
558     vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
559     GetStrongRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
560 
561     CMasterKey kMasterKey;
562 
563     kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
564     GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
565 
566     CCrypter crypter;
567     int64_t nStartTime = GetTimeMillis();
568     crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
569     kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
570 
571     nStartTime = GetTimeMillis();
572     crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
573     kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
574 
575     if (kMasterKey.nDeriveIterations < 25000)
576         kMasterKey.nDeriveIterations = 25000;
577 
578     LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
579 
580     if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
581         return false;
582     if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
583         return false;
584 
585     {
586         LOCK(cs_wallet);
587         mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
588         if (fFileBacked)
589         {
590             assert(!pwalletdbEncryption);
591             pwalletdbEncryption = new CWalletDB(strWalletFile);
592             if (!pwalletdbEncryption->TxnBegin()) {
593                 delete pwalletdbEncryption;
594                 pwalletdbEncryption = NULL;
595                 return false;
596             }
597             pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
598         }
599 
600         if (!EncryptKeys(vMasterKey))
601         {
602             if (fFileBacked) {
603                 pwalletdbEncryption->TxnAbort();
604                 delete pwalletdbEncryption;
605             }
606             // We now probably have half of our keys encrypted in memory, and half not...
607             // die and let the user reload the unencrypted wallet.
608             assert(false);
609         }
610 
611         // Encryption was introduced in version 0.4.0
612         SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
613 
614         if (fFileBacked)
615         {
616             if (!pwalletdbEncryption->TxnCommit()) {
617                 delete pwalletdbEncryption;
618                 // We now have keys encrypted in memory, but not on disk...
619                 // die to avoid confusion and let the user reload the unencrypted wallet.
620                 assert(false);
621             }
622 
623             delete pwalletdbEncryption;
624             pwalletdbEncryption = NULL;
625         }
626 
627         Lock();
628         Unlock(strWalletPassphrase);
629 
630         // if we are using HD, replace the HD master key (seed) with a new one
631         if (!hdChain.masterKeyID.IsNull()) {
632             CKey key;
633             CPubKey masterPubKey = GenerateNewHDMasterKey();
634             if (!SetHDMasterKey(masterPubKey))
635                 return false;
636         }
637 
638         NewKeyPool();
639         Lock();
640 
641         // Need to completely rewrite the wallet file; if we don't, bdb might keep
642         // bits of the unencrypted private key in slack space in the database file.
643         CDB::Rewrite(strWalletFile);
644 
645     }
646     NotifyStatusChanged(this);
647 
648     return true;
649 }
650 
IncOrderPosNext(CWalletDB * pwalletdb)651 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
652 {
653     AssertLockHeld(cs_wallet); // nOrderPosNext
654     int64_t nRet = nOrderPosNext++;
655     if (pwalletdb) {
656         pwalletdb->WriteOrderPosNext(nOrderPosNext);
657     } else {
658         CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
659     }
660     return nRet;
661 }
662 
AccountMove(std::string strFrom,std::string strTo,CAmount nAmount,std::string strComment)663 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
664 {
665     CWalletDB walletdb(strWalletFile);
666     if (!walletdb.TxnBegin())
667         return false;
668 
669     int64_t nNow = GetAdjustedTime();
670 
671     // Debit
672     CAccountingEntry debit;
673     debit.nOrderPos = IncOrderPosNext(&walletdb);
674     debit.strAccount = strFrom;
675     debit.nCreditDebit = -nAmount;
676     debit.nTime = nNow;
677     debit.strOtherAccount = strTo;
678     debit.strComment = strComment;
679     AddAccountingEntry(debit, walletdb);
680 
681     // Credit
682     CAccountingEntry credit;
683     credit.nOrderPos = IncOrderPosNext(&walletdb);
684     credit.strAccount = strTo;
685     credit.nCreditDebit = nAmount;
686     credit.nTime = nNow;
687     credit.strOtherAccount = strFrom;
688     credit.strComment = strComment;
689     AddAccountingEntry(credit, walletdb);
690 
691     if (!walletdb.TxnCommit())
692         return false;
693 
694     return true;
695 }
696 
GetAccountPubkey(CPubKey & pubKey,std::string strAccount,bool bForceNew)697 bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
698 {
699     CWalletDB walletdb(strWalletFile);
700 
701     CAccount account;
702     walletdb.ReadAccount(strAccount, account);
703 
704     if (!bForceNew) {
705         if (!account.vchPubKey.IsValid())
706             bForceNew = true;
707         else {
708             // Check if the current key has been used
709             CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
710             for (map<uint256, CWalletTx>::iterator it = mapWallet.begin();
711                  it != mapWallet.end() && account.vchPubKey.IsValid();
712                  ++it)
713                 BOOST_FOREACH(const CTxOut& txout, (*it).second.vout)
714                     if (txout.scriptPubKey == scriptPubKey) {
715                         bForceNew = true;
716                         break;
717                     }
718         }
719     }
720 
721     // Generate a new key
722     if (bForceNew) {
723         if (!GetKeyFromPool(account.vchPubKey))
724             return false;
725 
726         SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
727         walletdb.WriteAccount(strAccount, account);
728     }
729 
730     pubKey = account.vchPubKey;
731 
732     return true;
733 }
734 
MarkDirty()735 void CWallet::MarkDirty()
736 {
737     {
738         LOCK(cs_wallet);
739         BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
740             item.second.MarkDirty();
741     }
742 }
743 
AddToWallet(const CWalletTx & wtxIn,bool fFromLoadWallet,CWalletDB * pwalletdb)744 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet, CWalletDB* pwalletdb)
745 {
746     uint256 hash = wtxIn.GetHash();
747 
748     if (fFromLoadWallet)
749     {
750         mapWallet[hash] = wtxIn;
751         CWalletTx& wtx = mapWallet[hash];
752         wtx.BindWallet(this);
753         wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
754         AddToSpends(hash);
755         BOOST_FOREACH(const CTxIn& txin, wtx.vin) {
756             if (mapWallet.count(txin.prevout.hash)) {
757                 CWalletTx& prevtx = mapWallet[txin.prevout.hash];
758                 if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
759                     MarkConflicted(prevtx.hashBlock, wtx.GetHash());
760                 }
761             }
762         }
763     }
764     else
765     {
766         LOCK(cs_wallet);
767         // Inserts only if not already there, returns tx inserted or tx found
768         pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
769         CWalletTx& wtx = (*ret.first).second;
770         wtx.BindWallet(this);
771         bool fInsertedNew = ret.second;
772         if (fInsertedNew)
773         {
774             wtx.nTimeReceived = GetAdjustedTime();
775             wtx.nOrderPos = IncOrderPosNext(pwalletdb);
776             wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
777 
778             wtx.nTimeSmart = wtx.nTimeReceived;
779             if (!wtxIn.hashUnset())
780             {
781                 if (mapBlockIndex.count(wtxIn.hashBlock))
782                 {
783                     int64_t latestNow = wtx.nTimeReceived;
784                     int64_t latestEntry = 0;
785                     {
786                         // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
787                         int64_t latestTolerated = latestNow + 300;
788                         const TxItems & txOrdered = wtxOrdered;
789                         for (TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
790                         {
791                             CWalletTx *const pwtx = (*it).second.first;
792                             if (pwtx == &wtx)
793                                 continue;
794                             CAccountingEntry *const pacentry = (*it).second.second;
795                             int64_t nSmartTime;
796                             if (pwtx)
797                             {
798                                 nSmartTime = pwtx->nTimeSmart;
799                                 if (!nSmartTime)
800                                     nSmartTime = pwtx->nTimeReceived;
801                             }
802                             else
803                                 nSmartTime = pacentry->nTime;
804                             if (nSmartTime <= latestTolerated)
805                             {
806                                 latestEntry = nSmartTime;
807                                 if (nSmartTime > latestNow)
808                                     latestNow = nSmartTime;
809                                 break;
810                             }
811                         }
812                     }
813 
814                     int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
815                     wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
816                 }
817                 else
818                     LogPrintf("AddToWallet(): found %s in block %s not in index\n",
819                              wtxIn.GetHash().ToString(),
820                              wtxIn.hashBlock.ToString());
821             }
822             AddToSpends(hash);
823         }
824 
825         bool fUpdated = false;
826         if (!fInsertedNew)
827         {
828             // Merge
829             if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
830             {
831                 wtx.hashBlock = wtxIn.hashBlock;
832                 fUpdated = true;
833             }
834             // If no longer abandoned, update
835             if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
836             {
837                 wtx.hashBlock = wtxIn.hashBlock;
838                 fUpdated = true;
839             }
840             if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
841             {
842                 wtx.nIndex = wtxIn.nIndex;
843                 fUpdated = true;
844             }
845             if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
846             {
847                 wtx.fFromMe = wtxIn.fFromMe;
848                 fUpdated = true;
849             }
850         }
851 
852         //// debug print
853         LogPrintf("AddToWallet %s  %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
854 
855         // Write to disk
856         if (fInsertedNew || fUpdated)
857             if (!pwalletdb->WriteTx(wtx))
858                 return false;
859 
860         // Break debit/credit balance caches:
861         wtx.MarkDirty();
862 
863         // Notify UI of new or updated transaction
864         NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
865 
866         // notify an external script when a wallet transaction comes in or is updated
867         std::string strCmd = GetArg("-walletnotify", "");
868 
869         if ( !strCmd.empty())
870         {
871             boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
872             boost::thread t(runCommand, strCmd); // thread runs free
873         }
874 
875     }
876     return true;
877 }
878 
879 /**
880  * Add a transaction to the wallet, or update it.
881  * pblock is optional, but should be provided if the transaction is known to be in a block.
882  * If fUpdate is true, existing transactions will be updated.
883  */
AddToWalletIfInvolvingMe(const CTransaction & tx,const CBlock * pblock,bool fUpdate)884 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
885 {
886     {
887         AssertLockHeld(cs_wallet);
888 
889         if (pblock) {
890             BOOST_FOREACH(const CTxIn& txin, tx.vin) {
891                 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
892                 while (range.first != range.second) {
893                     if (range.first->second != tx.GetHash()) {
894                         LogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), pblock->GetHash().ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
895                         MarkConflicted(pblock->GetHash(), range.first->second);
896                     }
897                     range.first++;
898                 }
899             }
900         }
901 
902         bool fExisted = mapWallet.count(tx.GetHash()) != 0;
903         if (fExisted && !fUpdate) return false;
904         if (fExisted || IsMine(tx) || IsFromMe(tx))
905         {
906             CWalletTx wtx(this,tx);
907 
908             // Get merkle branch if transaction was found in a block
909             if (pblock)
910                 wtx.SetMerkleBranch(*pblock);
911 
912             // Do not flush the wallet here for performance reasons
913             // this is safe, as in case of a crash, we rescan the necessary blocks on startup through our SetBestChain-mechanism
914             CWalletDB walletdb(strWalletFile, "r+", false);
915 
916             return AddToWallet(wtx, false, &walletdb);
917         }
918     }
919     return false;
920 }
921 
AbandonTransaction(const uint256 & hashTx)922 bool CWallet::AbandonTransaction(const uint256& hashTx)
923 {
924     LOCK2(cs_main, cs_wallet);
925 
926     // Do not flush the wallet here for performance reasons
927     CWalletDB walletdb(strWalletFile, "r+", false);
928 
929     std::set<uint256> todo;
930     std::set<uint256> done;
931 
932     // Can't mark abandoned if confirmed or in mempool
933     assert(mapWallet.count(hashTx));
934     CWalletTx& origtx = mapWallet[hashTx];
935     if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
936         return false;
937     }
938 
939     todo.insert(hashTx);
940 
941     while (!todo.empty()) {
942         uint256 now = *todo.begin();
943         todo.erase(now);
944         done.insert(now);
945         assert(mapWallet.count(now));
946         CWalletTx& wtx = mapWallet[now];
947         int currentconfirm = wtx.GetDepthInMainChain();
948         // If the orig tx was not in block, none of its spends can be
949         assert(currentconfirm <= 0);
950         // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
951         if (currentconfirm == 0 && !wtx.isAbandoned()) {
952             // If the orig tx was not in block/mempool, none of its spends can be in mempool
953             assert(!wtx.InMempool());
954             wtx.nIndex = -1;
955             wtx.setAbandoned();
956             wtx.MarkDirty();
957             walletdb.WriteTx(wtx);
958             NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
959             // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
960             TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
961             while (iter != mapTxSpends.end() && iter->first.hash == now) {
962                 if (!done.count(iter->second)) {
963                     todo.insert(iter->second);
964                 }
965                 iter++;
966             }
967             // If a transaction changes 'conflicted' state, that changes the balance
968             // available of the outputs it spends. So force those to be recomputed
969             BOOST_FOREACH(const CTxIn& txin, wtx.vin)
970             {
971                 if (mapWallet.count(txin.prevout.hash))
972                     mapWallet[txin.prevout.hash].MarkDirty();
973             }
974         }
975     }
976 
977     return true;
978 }
979 
MarkConflicted(const uint256 & hashBlock,const uint256 & hashTx)980 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
981 {
982     LOCK2(cs_main, cs_wallet);
983 
984     int conflictconfirms = 0;
985     if (mapBlockIndex.count(hashBlock)) {
986         CBlockIndex* pindex = mapBlockIndex[hashBlock];
987         if (chainActive.Contains(pindex)) {
988             conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
989         }
990     }
991     // If number of conflict confirms cannot be determined, this means
992     // that the block is still unknown or not yet part of the main chain,
993     // for example when loading the wallet during a reindex. Do nothing in that
994     // case.
995     if (conflictconfirms >= 0)
996         return;
997 
998     // Do not flush the wallet here for performance reasons
999     CWalletDB walletdb(strWalletFile, "r+", false);
1000 
1001     std::set<uint256> todo;
1002     std::set<uint256> done;
1003 
1004     todo.insert(hashTx);
1005 
1006     while (!todo.empty()) {
1007         uint256 now = *todo.begin();
1008         todo.erase(now);
1009         done.insert(now);
1010         assert(mapWallet.count(now));
1011         CWalletTx& wtx = mapWallet[now];
1012         int currentconfirm = wtx.GetDepthInMainChain();
1013         if (conflictconfirms < currentconfirm) {
1014             // Block is 'more conflicted' than current confirm; update.
1015             // Mark transaction as conflicted with this block.
1016             wtx.nIndex = -1;
1017             wtx.hashBlock = hashBlock;
1018             wtx.MarkDirty();
1019             walletdb.WriteTx(wtx);
1020             // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1021             TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1022             while (iter != mapTxSpends.end() && iter->first.hash == now) {
1023                  if (!done.count(iter->second)) {
1024                      todo.insert(iter->second);
1025                  }
1026                  iter++;
1027             }
1028             // If a transaction changes 'conflicted' state, that changes the balance
1029             // available of the outputs it spends. So force those to be recomputed
1030             BOOST_FOREACH(const CTxIn& txin, wtx.vin)
1031             {
1032                 if (mapWallet.count(txin.prevout.hash))
1033                     mapWallet[txin.prevout.hash].MarkDirty();
1034             }
1035         }
1036     }
1037 }
1038 
SyncTransaction(const CTransaction & tx,const CBlockIndex * pindex,const CBlock * pblock)1039 void CWallet::SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, const CBlock* pblock)
1040 {
1041     LOCK2(cs_main, cs_wallet);
1042 
1043     if (!AddToWalletIfInvolvingMe(tx, pblock, true))
1044         return; // Not one of ours
1045 
1046     // If a transaction changes 'conflicted' state, that changes the balance
1047     // available of the outputs it spends. So force those to be
1048     // recomputed, also:
1049     BOOST_FOREACH(const CTxIn& txin, tx.vin)
1050     {
1051         if (mapWallet.count(txin.prevout.hash))
1052             mapWallet[txin.prevout.hash].MarkDirty();
1053     }
1054 }
1055 
1056 
IsMine(const CTxIn & txin) const1057 isminetype CWallet::IsMine(const CTxIn &txin) const
1058 {
1059     {
1060         LOCK(cs_wallet);
1061         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1062         if (mi != mapWallet.end())
1063         {
1064             const CWalletTx& prev = (*mi).second;
1065             if (txin.prevout.n < prev.vout.size())
1066                 return IsMine(prev.vout[txin.prevout.n]);
1067         }
1068     }
1069     return ISMINE_NO;
1070 }
1071 
GetDebit(const CTxIn & txin,const isminefilter & filter) const1072 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1073 {
1074     {
1075         LOCK(cs_wallet);
1076         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1077         if (mi != mapWallet.end())
1078         {
1079             const CWalletTx& prev = (*mi).second;
1080             if (txin.prevout.n < prev.vout.size())
1081                 if (IsMine(prev.vout[txin.prevout.n]) & filter)
1082                     return prev.vout[txin.prevout.n].nValue;
1083         }
1084     }
1085     return 0;
1086 }
1087 
IsMine(const CTxOut & txout) const1088 isminetype CWallet::IsMine(const CTxOut& txout) const
1089 {
1090     return ::IsMine(*this, txout.scriptPubKey);
1091 }
1092 
GetCredit(const CTxOut & txout,const isminefilter & filter) const1093 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1094 {
1095     if (!MoneyRange(txout.nValue))
1096         throw std::runtime_error(std::string(__func__) + ": value out of range");
1097     return ((IsMine(txout) & filter) ? txout.nValue : 0);
1098 }
1099 
IsChange(const CTxOut & txout) const1100 bool CWallet::IsChange(const CTxOut& txout) const
1101 {
1102     // TODO: fix handling of 'change' outputs. The assumption is that any
1103     // payment to a script that is ours, but is not in the address book
1104     // is change. That assumption is likely to break when we implement multisignature
1105     // wallets that return change back into a multi-signature-protected address;
1106     // a better way of identifying which outputs are 'the send' and which are
1107     // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1108     // which output, if any, was change).
1109     if (::IsMine(*this, txout.scriptPubKey))
1110     {
1111         CTxDestination address;
1112         if (!ExtractDestination(txout.scriptPubKey, address))
1113             return true;
1114 
1115         LOCK(cs_wallet);
1116         if (!mapAddressBook.count(address))
1117             return true;
1118     }
1119     return false;
1120 }
1121 
GetChange(const CTxOut & txout) const1122 CAmount CWallet::GetChange(const CTxOut& txout) const
1123 {
1124     if (!MoneyRange(txout.nValue))
1125         throw std::runtime_error(std::string(__func__) + ": value out of range");
1126     return (IsChange(txout) ? txout.nValue : 0);
1127 }
1128 
IsMine(const CTransaction & tx) const1129 bool CWallet::IsMine(const CTransaction& tx) const
1130 {
1131     BOOST_FOREACH(const CTxOut& txout, tx.vout)
1132         if (IsMine(txout))
1133             return true;
1134     return false;
1135 }
1136 
IsFromMe(const CTransaction & tx) const1137 bool CWallet::IsFromMe(const CTransaction& tx) const
1138 {
1139     return (GetDebit(tx, ISMINE_ALL) > 0);
1140 }
1141 
GetDebit(const CTransaction & tx,const isminefilter & filter) const1142 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1143 {
1144     CAmount nDebit = 0;
1145     BOOST_FOREACH(const CTxIn& txin, tx.vin)
1146     {
1147         nDebit += GetDebit(txin, filter);
1148         if (!MoneyRange(nDebit))
1149             throw std::runtime_error(std::string(__func__) + ": value out of range");
1150     }
1151     return nDebit;
1152 }
1153 
GetCredit(const CTransaction & tx,const isminefilter & filter) const1154 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1155 {
1156     CAmount nCredit = 0;
1157     BOOST_FOREACH(const CTxOut& txout, tx.vout)
1158     {
1159         nCredit += GetCredit(txout, filter);
1160         if (!MoneyRange(nCredit))
1161             throw std::runtime_error(std::string(__func__) + ": value out of range");
1162     }
1163     return nCredit;
1164 }
1165 
GetChange(const CTransaction & tx) const1166 CAmount CWallet::GetChange(const CTransaction& tx) const
1167 {
1168     CAmount nChange = 0;
1169     BOOST_FOREACH(const CTxOut& txout, tx.vout)
1170     {
1171         nChange += GetChange(txout);
1172         if (!MoneyRange(nChange))
1173             throw std::runtime_error(std::string(__func__) + ": value out of range");
1174     }
1175     return nChange;
1176 }
1177 
GenerateNewHDMasterKey()1178 CPubKey CWallet::GenerateNewHDMasterKey()
1179 {
1180     CKey key;
1181     key.MakeNewKey(true);
1182 
1183     int64_t nCreationTime = GetTime();
1184     CKeyMetadata metadata(nCreationTime);
1185 
1186     // calculate the pubkey
1187     CPubKey pubkey = key.GetPubKey();
1188     assert(key.VerifyPubKey(pubkey));
1189 
1190     // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1191     metadata.hdKeypath     = "m";
1192     metadata.hdMasterKeyID = pubkey.GetID();
1193 
1194     {
1195         LOCK(cs_wallet);
1196 
1197         // mem store the metadata
1198         mapKeyMetadata[pubkey.GetID()] = metadata;
1199 
1200         // write the key&metadata to the database
1201         if (!AddKeyPubKey(key, pubkey))
1202             throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1203     }
1204 
1205     return pubkey;
1206 }
1207 
SetHDMasterKey(const CPubKey & pubkey)1208 bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
1209 {
1210     LOCK(cs_wallet);
1211 
1212     // ensure this wallet.dat can only be opened by clients supporting HD
1213     SetMinVersion(FEATURE_HD);
1214 
1215     // store the keyid (hash160) together with
1216     // the child index counter in the database
1217     // as a hdchain object
1218     CHDChain newHdChain;
1219     newHdChain.masterKeyID = pubkey.GetID();
1220     SetHDChain(newHdChain, false);
1221 
1222     return true;
1223 }
1224 
SetHDChain(const CHDChain & chain,bool memonly)1225 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1226 {
1227     LOCK(cs_wallet);
1228     if (!memonly && !CWalletDB(strWalletFile).WriteHDChain(chain))
1229         throw runtime_error(std::string(__func__) + ": writing chain failed");
1230 
1231     hdChain = chain;
1232     return true;
1233 }
1234 
GetTxTime() const1235 int64_t CWalletTx::GetTxTime() const
1236 {
1237     int64_t n = nTimeSmart;
1238     return n ? n : nTimeReceived;
1239 }
1240 
GetRequestCount() const1241 int CWalletTx::GetRequestCount() const
1242 {
1243     // Returns -1 if it wasn't being tracked
1244     int nRequests = -1;
1245     {
1246         LOCK(pwallet->cs_wallet);
1247         if (IsCoinBase())
1248         {
1249             // Generated block
1250             if (!hashUnset())
1251             {
1252                 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1253                 if (mi != pwallet->mapRequestCount.end())
1254                     nRequests = (*mi).second;
1255             }
1256         }
1257         else
1258         {
1259             // Did anyone request this transaction?
1260             map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1261             if (mi != pwallet->mapRequestCount.end())
1262             {
1263                 nRequests = (*mi).second;
1264 
1265                 // How about the block it's in?
1266                 if (nRequests == 0 && !hashUnset())
1267                 {
1268                     map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1269                     if (mi != pwallet->mapRequestCount.end())
1270                         nRequests = (*mi).second;
1271                     else
1272                         nRequests = 1; // If it's in someone else's block it must have got out
1273                 }
1274             }
1275         }
1276     }
1277     return nRequests;
1278 }
1279 
GetAmounts(list<COutputEntry> & listReceived,list<COutputEntry> & listSent,CAmount & nFee,string & strSentAccount,const isminefilter & filter) const1280 void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
1281                            list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
1282 {
1283     nFee = 0;
1284     listReceived.clear();
1285     listSent.clear();
1286     strSentAccount = strFromAccount;
1287 
1288     // Compute fee:
1289     CAmount nDebit = GetDebit(filter);
1290     if (nDebit > 0) // debit>0 means we signed/sent this transaction
1291     {
1292         CAmount nValueOut = GetValueOut();
1293         nFee = nDebit - nValueOut;
1294     }
1295 
1296     // Sent/received.
1297     for (unsigned int i = 0; i < vout.size(); ++i)
1298     {
1299         const CTxOut& txout = vout[i];
1300         isminetype fIsMine = pwallet->IsMine(txout);
1301         // Only need to handle txouts if AT LEAST one of these is true:
1302         //   1) they debit from us (sent)
1303         //   2) the output is to us (received)
1304         if (nDebit > 0)
1305         {
1306             // Don't report 'change' txouts
1307             if (pwallet->IsChange(txout))
1308                 continue;
1309         }
1310         else if (!(fIsMine & filter))
1311             continue;
1312 
1313         // In either case, we need to get the destination address
1314         CTxDestination address;
1315 
1316         if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1317         {
1318             LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1319                      this->GetHash().ToString());
1320             address = CNoDestination();
1321         }
1322 
1323         COutputEntry output = {address, txout.nValue, (int)i};
1324 
1325         // If we are debited by the transaction, add the output as a "sent" entry
1326         if (nDebit > 0)
1327             listSent.push_back(output);
1328 
1329         // If we are receiving the output, add it as a "received" entry
1330         if (fIsMine & filter)
1331             listReceived.push_back(output);
1332     }
1333 
1334 }
1335 
GetAccountAmounts(const string & strAccount,CAmount & nReceived,CAmount & nSent,CAmount & nFee,const isminefilter & filter) const1336 void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
1337                                   CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
1338 {
1339     nReceived = nSent = nFee = 0;
1340 
1341     CAmount allFee;
1342     string strSentAccount;
1343     list<COutputEntry> listReceived;
1344     list<COutputEntry> listSent;
1345     GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
1346 
1347     if (strAccount == strSentAccount)
1348     {
1349         BOOST_FOREACH(const COutputEntry& s, listSent)
1350             nSent += s.amount;
1351         nFee = allFee;
1352     }
1353     {
1354         LOCK(pwallet->cs_wallet);
1355         BOOST_FOREACH(const COutputEntry& r, listReceived)
1356         {
1357             if (pwallet->mapAddressBook.count(r.destination))
1358             {
1359                 map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
1360                 if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
1361                     nReceived += r.amount;
1362             }
1363             else if (strAccount.empty())
1364             {
1365                 nReceived += r.amount;
1366             }
1367         }
1368     }
1369 }
1370 
1371 /**
1372  * Scan the block chain (starting in pindexStart) for transactions
1373  * from or to us. If fUpdate is true, found transactions that already
1374  * exist in the wallet will be updated.
1375  */
ScanForWalletTransactions(CBlockIndex * pindexStart,bool fUpdate)1376 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1377 {
1378     int ret = 0;
1379     int64_t nNow = GetTime();
1380     const CChainParams& chainParams = Params();
1381 
1382     CBlockIndex* pindex = pindexStart;
1383     {
1384         LOCK2(cs_main, cs_wallet);
1385 
1386         // no need to read and scan block, if block was created before
1387         // our wallet birthday (as adjusted for block time variability)
1388         while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
1389             pindex = chainActive.Next(pindex);
1390 
1391         ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1392         double dProgressStart = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false);
1393         double dProgressTip = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip(), false);
1394         while (pindex)
1395         {
1396             if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1397                 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1398 
1399             CBlock block;
1400             ReadBlockFromDisk(block, pindex, Params().GetConsensus());
1401             BOOST_FOREACH(CTransaction& tx, block.vtx)
1402             {
1403                 if (AddToWalletIfInvolvingMe(tx, &block, fUpdate))
1404                     ret++;
1405             }
1406             pindex = chainActive.Next(pindex);
1407             if (GetTime() >= nNow + 60) {
1408                 nNow = GetTime();
1409                 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex));
1410             }
1411         }
1412         ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1413     }
1414     return ret;
1415 }
1416 
ReacceptWalletTransactions()1417 void CWallet::ReacceptWalletTransactions()
1418 {
1419     // If transactions aren't being broadcasted, don't let them into local mempool either
1420     if (!fBroadcastTransactions)
1421         return;
1422     LOCK2(cs_main, cs_wallet);
1423     std::map<int64_t, CWalletTx*> mapSorted;
1424 
1425     // Sort pending wallet transactions based on their initial wallet insertion order
1426     BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1427     {
1428         const uint256& wtxid = item.first;
1429         CWalletTx& wtx = item.second;
1430         assert(wtx.GetHash() == wtxid);
1431 
1432         int nDepth = wtx.GetDepthInMainChain();
1433 
1434         if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1435             mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1436         }
1437     }
1438 
1439     // Try to add wallet transactions to memory pool
1440     BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
1441     {
1442         CWalletTx& wtx = *(item.second);
1443 
1444         LOCK(mempool.cs);
1445         CValidationState state;
1446         wtx.AcceptToMemoryPool(false, maxTxFee, state);
1447     }
1448 }
1449 
RelayWalletTransaction()1450 bool CWalletTx::RelayWalletTransaction()
1451 {
1452     assert(pwallet->GetBroadcastTransactions());
1453     if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1454     {
1455         CValidationState state;
1456         /* GetDepthInMainChain already catches known conflicts. */
1457         if (InMempool() || AcceptToMemoryPool(false, maxTxFee, state)) {
1458             LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1459             RelayTransaction((CTransaction)*this);
1460             return true;
1461         }
1462     }
1463     return false;
1464 }
1465 
GetConflicts() const1466 set<uint256> CWalletTx::GetConflicts() const
1467 {
1468     set<uint256> result;
1469     if (pwallet != NULL)
1470     {
1471         uint256 myHash = GetHash();
1472         result = pwallet->GetConflicts(myHash);
1473         result.erase(myHash);
1474     }
1475     return result;
1476 }
1477 
GetDebit(const isminefilter & filter) const1478 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1479 {
1480     if (vin.empty())
1481         return 0;
1482 
1483     CAmount debit = 0;
1484     if(filter & ISMINE_SPENDABLE)
1485     {
1486         if (fDebitCached)
1487             debit += nDebitCached;
1488         else
1489         {
1490             nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1491             fDebitCached = true;
1492             debit += nDebitCached;
1493         }
1494     }
1495     if(filter & ISMINE_WATCH_ONLY)
1496     {
1497         if(fWatchDebitCached)
1498             debit += nWatchDebitCached;
1499         else
1500         {
1501             nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1502             fWatchDebitCached = true;
1503             debit += nWatchDebitCached;
1504         }
1505     }
1506     return debit;
1507 }
1508 
GetCredit(const isminefilter & filter) const1509 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1510 {
1511     // Must wait until coinbase is safely deep enough in the chain before valuing it
1512     if (IsCoinBase() && GetBlocksToMaturity() > 0)
1513         return 0;
1514 
1515     int64_t credit = 0;
1516     if (filter & ISMINE_SPENDABLE)
1517     {
1518         // GetBalance can assume transactions in mapWallet won't change
1519         if (fCreditCached)
1520             credit += nCreditCached;
1521         else
1522         {
1523             nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1524             fCreditCached = true;
1525             credit += nCreditCached;
1526         }
1527     }
1528     if (filter & ISMINE_WATCH_ONLY)
1529     {
1530         if (fWatchCreditCached)
1531             credit += nWatchCreditCached;
1532         else
1533         {
1534             nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1535             fWatchCreditCached = true;
1536             credit += nWatchCreditCached;
1537         }
1538     }
1539     return credit;
1540 }
1541 
GetImmatureCredit(bool fUseCache) const1542 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1543 {
1544     if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1545     {
1546         if (fUseCache && fImmatureCreditCached)
1547             return nImmatureCreditCached;
1548         nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1549         fImmatureCreditCached = true;
1550         return nImmatureCreditCached;
1551     }
1552 
1553     return 0;
1554 }
1555 
GetAvailableCredit(bool fUseCache) const1556 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1557 {
1558     if (pwallet == 0)
1559         return 0;
1560 
1561     // Must wait until coinbase is safely deep enough in the chain before valuing it
1562     if (IsCoinBase() && GetBlocksToMaturity() > 0)
1563         return 0;
1564 
1565     if (fUseCache && fAvailableCreditCached)
1566         return nAvailableCreditCached;
1567 
1568     CAmount nCredit = 0;
1569     uint256 hashTx = GetHash();
1570     for (unsigned int i = 0; i < vout.size(); i++)
1571     {
1572         if (!pwallet->IsSpent(hashTx, i))
1573         {
1574             const CTxOut &txout = vout[i];
1575             nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1576             if (!MoneyRange(nCredit))
1577                 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1578         }
1579     }
1580 
1581     nAvailableCreditCached = nCredit;
1582     fAvailableCreditCached = true;
1583     return nCredit;
1584 }
1585 
GetImmatureWatchOnlyCredit(const bool & fUseCache) const1586 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1587 {
1588     if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1589     {
1590         if (fUseCache && fImmatureWatchCreditCached)
1591             return nImmatureWatchCreditCached;
1592         nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1593         fImmatureWatchCreditCached = true;
1594         return nImmatureWatchCreditCached;
1595     }
1596 
1597     return 0;
1598 }
1599 
GetAvailableWatchOnlyCredit(const bool & fUseCache) const1600 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1601 {
1602     if (pwallet == 0)
1603         return 0;
1604 
1605     // Must wait until coinbase is safely deep enough in the chain before valuing it
1606     if (IsCoinBase() && GetBlocksToMaturity() > 0)
1607         return 0;
1608 
1609     if (fUseCache && fAvailableWatchCreditCached)
1610         return nAvailableWatchCreditCached;
1611 
1612     CAmount nCredit = 0;
1613     for (unsigned int i = 0; i < vout.size(); i++)
1614     {
1615         if (!pwallet->IsSpent(GetHash(), i))
1616         {
1617             const CTxOut &txout = vout[i];
1618             nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1619             if (!MoneyRange(nCredit))
1620                 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1621         }
1622     }
1623 
1624     nAvailableWatchCreditCached = nCredit;
1625     fAvailableWatchCreditCached = true;
1626     return nCredit;
1627 }
1628 
GetChange() const1629 CAmount CWalletTx::GetChange() const
1630 {
1631     if (fChangeCached)
1632         return nChangeCached;
1633     nChangeCached = pwallet->GetChange(*this);
1634     fChangeCached = true;
1635     return nChangeCached;
1636 }
1637 
InMempool() const1638 bool CWalletTx::InMempool() const
1639 {
1640     LOCK(mempool.cs);
1641     if (mempool.exists(GetHash())) {
1642         return true;
1643     }
1644     return false;
1645 }
1646 
IsTrusted() const1647 bool CWalletTx::IsTrusted() const
1648 {
1649     // Quick answer in most cases
1650     if (!CheckFinalTx(*this))
1651         return false;
1652     int nDepth = GetDepthInMainChain();
1653     if (nDepth >= 1)
1654         return true;
1655     if (nDepth < 0)
1656         return false;
1657     if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1658         return false;
1659 
1660     // Don't trust unconfirmed transactions from us unless they are in the mempool.
1661     if (!InMempool())
1662         return false;
1663 
1664     // Trusted if all inputs are from us and are in the mempool:
1665     BOOST_FOREACH(const CTxIn& txin, vin)
1666     {
1667         // Transactions not sent by us: not trusted
1668         const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1669         if (parent == NULL)
1670             return false;
1671         const CTxOut& parentOut = parent->vout[txin.prevout.n];
1672         if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1673             return false;
1674     }
1675     return true;
1676 }
1677 
IsEquivalentTo(const CWalletTx & tx) const1678 bool CWalletTx::IsEquivalentTo(const CWalletTx& tx) const
1679 {
1680         CMutableTransaction tx1 = *this;
1681         CMutableTransaction tx2 = tx;
1682         for (unsigned int i = 0; i < tx1.vin.size(); i++) tx1.vin[i].scriptSig = CScript();
1683         for (unsigned int i = 0; i < tx2.vin.size(); i++) tx2.vin[i].scriptSig = CScript();
1684         return CTransaction(tx1) == CTransaction(tx2);
1685 }
1686 
ResendWalletTransactionsBefore(int64_t nTime)1687 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime)
1688 {
1689     std::vector<uint256> result;
1690 
1691     LOCK(cs_wallet);
1692     // Sort them in chronological order
1693     multimap<unsigned int, CWalletTx*> mapSorted;
1694     BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1695     {
1696         CWalletTx& wtx = item.second;
1697         // Don't rebroadcast if newer than nTime:
1698         if (wtx.nTimeReceived > nTime)
1699             continue;
1700         mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1701     }
1702     BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1703     {
1704         CWalletTx& wtx = *item.second;
1705         if (wtx.RelayWalletTransaction())
1706             result.push_back(wtx.GetHash());
1707     }
1708     return result;
1709 }
1710 
ResendWalletTransactions(int64_t nBestBlockTime)1711 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime)
1712 {
1713     // Do this infrequently and randomly to avoid giving away
1714     // that these are our transactions.
1715     if (GetTime() < nNextResend || !fBroadcastTransactions)
1716         return;
1717     bool fFirst = (nNextResend == 0);
1718     nNextResend = GetTime() + GetRand(30 * 60);
1719     if (fFirst)
1720         return;
1721 
1722     // Only do it if there's been a new block since last time
1723     if (nBestBlockTime < nLastResend)
1724         return;
1725     nLastResend = GetTime();
1726 
1727     // Rebroadcast unconfirmed txes older than 5 minutes before the last
1728     // block was found:
1729     std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60);
1730     if (!relayed.empty())
1731         LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
1732 }
1733 
1734 /** @} */ // end of mapWallet
1735 
1736 
1737 
1738 
1739 /** @defgroup Actions
1740  *
1741  * @{
1742  */
1743 
1744 
GetBalance() const1745 CAmount CWallet::GetBalance() const
1746 {
1747     CAmount nTotal = 0;
1748     {
1749         LOCK2(cs_main, cs_wallet);
1750         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1751         {
1752             const CWalletTx* pcoin = &(*it).second;
1753             if (pcoin->IsTrusted())
1754                 nTotal += pcoin->GetAvailableCredit();
1755         }
1756     }
1757 
1758     return nTotal;
1759 }
1760 
GetUnconfirmedBalance() const1761 CAmount CWallet::GetUnconfirmedBalance() const
1762 {
1763     CAmount nTotal = 0;
1764     {
1765         LOCK2(cs_main, cs_wallet);
1766         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1767         {
1768             const CWalletTx* pcoin = &(*it).second;
1769             if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1770                 nTotal += pcoin->GetAvailableCredit();
1771         }
1772     }
1773     return nTotal;
1774 }
1775 
GetImmatureBalance() const1776 CAmount CWallet::GetImmatureBalance() const
1777 {
1778     CAmount nTotal = 0;
1779     {
1780         LOCK2(cs_main, cs_wallet);
1781         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1782         {
1783             const CWalletTx* pcoin = &(*it).second;
1784             nTotal += pcoin->GetImmatureCredit();
1785         }
1786     }
1787     return nTotal;
1788 }
1789 
GetWatchOnlyBalance() const1790 CAmount CWallet::GetWatchOnlyBalance() const
1791 {
1792     CAmount nTotal = 0;
1793     {
1794         LOCK2(cs_main, cs_wallet);
1795         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1796         {
1797             const CWalletTx* pcoin = &(*it).second;
1798             if (pcoin->IsTrusted())
1799                 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1800         }
1801     }
1802 
1803     return nTotal;
1804 }
1805 
GetUnconfirmedWatchOnlyBalance() const1806 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
1807 {
1808     CAmount nTotal = 0;
1809     {
1810         LOCK2(cs_main, cs_wallet);
1811         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1812         {
1813             const CWalletTx* pcoin = &(*it).second;
1814             if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1815                 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1816         }
1817     }
1818     return nTotal;
1819 }
1820 
GetImmatureWatchOnlyBalance() const1821 CAmount CWallet::GetImmatureWatchOnlyBalance() const
1822 {
1823     CAmount nTotal = 0;
1824     {
1825         LOCK2(cs_main, cs_wallet);
1826         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1827         {
1828             const CWalletTx* pcoin = &(*it).second;
1829             nTotal += pcoin->GetImmatureWatchOnlyCredit();
1830         }
1831     }
1832     return nTotal;
1833 }
1834 
AvailableCoins(vector<COutput> & vCoins,bool fOnlyConfirmed,const CCoinControl * coinControl,bool fIncludeZeroValue) const1835 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, bool fIncludeZeroValue) const
1836 {
1837     vCoins.clear();
1838 
1839     {
1840         LOCK2(cs_main, cs_wallet);
1841         for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1842         {
1843             const uint256& wtxid = it->first;
1844             const CWalletTx* pcoin = &(*it).second;
1845 
1846             if (!CheckFinalTx(*pcoin))
1847                 continue;
1848 
1849             if (fOnlyConfirmed && !pcoin->IsTrusted())
1850                 continue;
1851 
1852             if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1853                 continue;
1854 
1855             int nDepth = pcoin->GetDepthInMainChain();
1856             if (nDepth < 0)
1857                 continue;
1858 
1859             // We should not consider coins which aren't at least in our mempool
1860             // It's possible for these to be conflicted via ancestors which we may never be able to detect
1861             if (nDepth == 0 && !pcoin->InMempool())
1862                 continue;
1863 
1864             for (unsigned int i = 0; i < pcoin->vout.size(); i++) {
1865                 isminetype mine = IsMine(pcoin->vout[i]);
1866                 if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
1867                     !IsLockedCoin((*it).first, i) && (pcoin->vout[i].nValue > 0 || fIncludeZeroValue) &&
1868                     (!coinControl || !coinControl->HasSelected() || coinControl->fAllowOtherInputs || coinControl->IsSelected(COutPoint((*it).first, i))))
1869                         vCoins.push_back(COutput(pcoin, i, nDepth,
1870                                                  ((mine & ISMINE_SPENDABLE) != ISMINE_NO) ||
1871                                                   (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO),
1872                                                  (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO));
1873             }
1874         }
1875     }
1876 }
1877 
ApproximateBestSubset(vector<pair<CAmount,pair<const CWalletTx *,unsigned int>>> vValue,const CAmount & nTotalLower,const CAmount & nTargetValue,vector<char> & vfBest,CAmount & nBest,int iterations=1000)1878 static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
1879                                   vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
1880 {
1881     vector<char> vfIncluded;
1882 
1883     vfBest.assign(vValue.size(), true);
1884     nBest = nTotalLower;
1885 
1886     seed_insecure_rand();
1887 
1888     for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1889     {
1890         vfIncluded.assign(vValue.size(), false);
1891         CAmount nTotal = 0;
1892         bool fReachedTarget = false;
1893         for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1894         {
1895             for (unsigned int i = 0; i < vValue.size(); i++)
1896             {
1897                 //The solver here uses a randomized algorithm,
1898                 //the randomness serves no real security purpose but is just
1899                 //needed to prevent degenerate behavior and it is important
1900                 //that the rng is fast. We do not use a constant random sequence,
1901                 //because there may be some privacy improvement by making
1902                 //the selection random.
1903                 if (nPass == 0 ? insecure_rand()&1 : !vfIncluded[i])
1904                 {
1905                     nTotal += vValue[i].first;
1906                     vfIncluded[i] = true;
1907                     if (nTotal >= nTargetValue)
1908                     {
1909                         fReachedTarget = true;
1910                         if (nTotal < nBest)
1911                         {
1912                             nBest = nTotal;
1913                             vfBest = vfIncluded;
1914                         }
1915                         nTotal -= vValue[i].first;
1916                         vfIncluded[i] = false;
1917                     }
1918                 }
1919             }
1920         }
1921     }
1922 
1923     //Reduces the approximate best subset by removing any inputs that are smaller than the surplus of nTotal beyond nTargetValue.
1924     for (unsigned int i = 0; i < vValue.size(); i++)
1925     {
1926         if (vfBest[i] && (nBest - vValue[i].first) >= nTargetValue )
1927         {
1928             vfBest[i] = false;
1929             nBest -= vValue[i].first;
1930         }
1931     }
1932 }
1933 
SelectCoinsMinConf(const CAmount & nTargetValue,const int nConfMine,const int nConfTheirs,const uint64_t nMaxAncestors,vector<COutput> vCoins,set<pair<const CWalletTx *,unsigned int>> & setCoinsRet,CAmount & nValueRet) const1934 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, vector<COutput> vCoins,
1935                                  set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
1936 {
1937     setCoinsRet.clear();
1938     nValueRet = 0;
1939 
1940     // List of values less than target
1941     pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
1942     coinLowestLarger.first = std::numeric_limits<CAmount>::max();
1943     coinLowestLarger.second.first = NULL;
1944     vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
1945     CAmount nTotalLower = 0;
1946 
1947     random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
1948 
1949     BOOST_FOREACH(const COutput &output, vCoins)
1950     {
1951         if (!output.fSpendable)
1952             continue;
1953 
1954         const CWalletTx *pcoin = output.tx;
1955 
1956         if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
1957             continue;
1958 
1959         if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
1960             continue;
1961 
1962         int i = output.i;
1963         CAmount n = pcoin->vout[i].nValue;
1964 
1965         pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
1966 
1967         if (n == nTargetValue)
1968         {
1969             setCoinsRet.insert(coin.second);
1970             nValueRet += coin.first;
1971             return true;
1972         }
1973         else if (n < nTargetValue + MIN_CHANGE)
1974         {
1975             vValue.push_back(coin);
1976             nTotalLower += n;
1977         }
1978         else if (n < coinLowestLarger.first)
1979         {
1980             coinLowestLarger = coin;
1981         }
1982     }
1983 
1984     if (nTotalLower == nTargetValue)
1985     {
1986         for (unsigned int i = 0; i < vValue.size(); ++i)
1987         {
1988             setCoinsRet.insert(vValue[i].second);
1989             nValueRet += vValue[i].first;
1990         }
1991         return true;
1992     }
1993 
1994     if (nTotalLower < nTargetValue)
1995     {
1996         if (coinLowestLarger.second.first == NULL)
1997             return false;
1998         setCoinsRet.insert(coinLowestLarger.second);
1999         nValueRet += coinLowestLarger.first;
2000         return true;
2001     }
2002 
2003     // Solve subset sum by stochastic approximation
2004     std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2005     std::reverse(vValue.begin(), vValue.end());
2006     vector<char> vfBest;
2007     CAmount nBest;
2008 
2009     ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2010     if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2011         ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2012 
2013     // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2014     //                                   or the next bigger coin is closer), return the bigger coin
2015     if (coinLowestLarger.second.first &&
2016         ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger.first <= nBest))
2017     {
2018         setCoinsRet.insert(coinLowestLarger.second);
2019         nValueRet += coinLowestLarger.first;
2020     }
2021     else {
2022         for (unsigned int i = 0; i < vValue.size(); i++)
2023             if (vfBest[i])
2024             {
2025                 setCoinsRet.insert(vValue[i].second);
2026                 nValueRet += vValue[i].first;
2027             }
2028 
2029         LogPrint("selectcoins", "SelectCoins() best subset: ");
2030         for (unsigned int i = 0; i < vValue.size(); i++)
2031             if (vfBest[i])
2032                 LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first));
2033         LogPrint("selectcoins", "total %s\n", FormatMoney(nBest));
2034     }
2035 
2036     return true;
2037 }
2038 
SelectCoins(const vector<COutput> & vAvailableCoins,const CAmount & nTargetValue,set<pair<const CWalletTx *,unsigned int>> & setCoinsRet,CAmount & nValueRet,const CCoinControl * coinControl) const2039 bool CWallet::SelectCoins(const vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2040 {
2041     vector<COutput> vCoins(vAvailableCoins);
2042 
2043     // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2044     if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2045     {
2046         BOOST_FOREACH(const COutput& out, vCoins)
2047         {
2048             if (!out.fSpendable)
2049                  continue;
2050             nValueRet += out.tx->vout[out.i].nValue;
2051             setCoinsRet.insert(make_pair(out.tx, out.i));
2052         }
2053         return (nValueRet >= nTargetValue);
2054     }
2055 
2056     // calculate value from preset inputs and store them
2057     set<pair<const CWalletTx*, uint32_t> > setPresetCoins;
2058     CAmount nValueFromPresetInputs = 0;
2059 
2060     std::vector<COutPoint> vPresetInputs;
2061     if (coinControl)
2062         coinControl->ListSelected(vPresetInputs);
2063     BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
2064     {
2065         map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2066         if (it != mapWallet.end())
2067         {
2068             const CWalletTx* pcoin = &it->second;
2069             // Clearly invalid input, fail
2070             if (pcoin->vout.size() <= outpoint.n)
2071                 return false;
2072             nValueFromPresetInputs += pcoin->vout[outpoint.n].nValue;
2073             setPresetCoins.insert(make_pair(pcoin, outpoint.n));
2074         } else
2075             return false; // TODO: Allow non-wallet inputs
2076     }
2077 
2078     // remove preset inputs from vCoins
2079     for (vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2080     {
2081         if (setPresetCoins.count(make_pair(it->tx, it->i)))
2082             it = vCoins.erase(it);
2083         else
2084             ++it;
2085     }
2086 
2087     size_t nMaxChainLength = std::min(GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2088     bool fRejectLongChains = GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2089 
2090     bool res = nTargetValue <= nValueFromPresetInputs ||
2091         SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2092         SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2093         (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2094         (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2095         (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2096         (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2097         (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2098 
2099     // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2100     setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2101 
2102     // add preset inputs to the total value selected
2103     nValueRet += nValueFromPresetInputs;
2104 
2105     return res;
2106 }
2107 
FundTransaction(CMutableTransaction & tx,CAmount & nFeeRet,bool overrideEstimatedFeeRate,const CFeeRate & specificFeeRate,int & nChangePosInOut,std::string & strFailReason,bool includeWatching,bool lockUnspents,const CTxDestination & destChange)2108 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, bool overrideEstimatedFeeRate, const CFeeRate& specificFeeRate, int& nChangePosInOut, std::string& strFailReason, bool includeWatching, bool lockUnspents, const CTxDestination& destChange)
2109 {
2110     vector<CRecipient> vecSend;
2111 
2112     // Turn the txout set into a CRecipient vector
2113     BOOST_FOREACH(const CTxOut& txOut, tx.vout)
2114     {
2115         CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, false};
2116         vecSend.push_back(recipient);
2117     }
2118 
2119     CCoinControl coinControl;
2120     coinControl.destChange = destChange;
2121     coinControl.fAllowOtherInputs = true;
2122     coinControl.fAllowWatchOnly = includeWatching;
2123     coinControl.fOverrideFeeRate = overrideEstimatedFeeRate;
2124     coinControl.nFeeRate = specificFeeRate;
2125 
2126     BOOST_FOREACH(const CTxIn& txin, tx.vin)
2127         coinControl.Select(txin.prevout);
2128 
2129     CReserveKey reservekey(this);
2130     CWalletTx wtx;
2131     if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, &coinControl, false))
2132         return false;
2133 
2134     if (nChangePosInOut != -1)
2135         tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.vout[nChangePosInOut]);
2136 
2137     // Add new txins (keeping original txin scriptSig/order)
2138     BOOST_FOREACH(const CTxIn& txin, wtx.vin)
2139     {
2140         if (!coinControl.IsSelected(txin.prevout))
2141         {
2142             tx.vin.push_back(txin);
2143 
2144             if (lockUnspents)
2145             {
2146               LOCK2(cs_main, cs_wallet);
2147               LockCoin(txin.prevout);
2148             }
2149         }
2150     }
2151 
2152     return true;
2153 }
2154 
CreateTransaction(const vector<CRecipient> & vecSend,CWalletTx & wtxNew,CReserveKey & reservekey,CAmount & nFeeRet,int & nChangePosInOut,std::string & strFailReason,const CCoinControl * coinControl,bool sign)2155 bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2156                                 int& nChangePosInOut, std::string& strFailReason, const CCoinControl* coinControl, bool sign)
2157 {
2158     CAmount nValue = 0;
2159     int nChangePosRequest = nChangePosInOut;
2160     unsigned int nSubtractFeeFromAmount = 0;
2161     BOOST_FOREACH (const CRecipient& recipient, vecSend)
2162     {
2163         if (nValue < 0 || recipient.nAmount < 0)
2164         {
2165             strFailReason = _("Transaction amounts must be positive");
2166             return false;
2167         }
2168         nValue += recipient.nAmount;
2169 
2170         if (recipient.fSubtractFeeFromAmount)
2171             nSubtractFeeFromAmount++;
2172     }
2173     if (vecSend.empty() || nValue < 0)
2174     {
2175         strFailReason = _("Transaction amounts must be positive");
2176         return false;
2177     }
2178 
2179     wtxNew.fTimeReceivedIsTxTime = true;
2180     wtxNew.BindWallet(this);
2181     CMutableTransaction txNew;
2182 
2183     // Discourage fee sniping.
2184     //
2185     // For a large miner the value of the transactions in the best block and
2186     // the mempool can exceed the cost of deliberately attempting to mine two
2187     // blocks to orphan the current best block. By setting nLockTime such that
2188     // only the next block can include the transaction, we discourage this
2189     // practice as the height restricted and limited blocksize gives miners
2190     // considering fee sniping fewer options for pulling off this attack.
2191     //
2192     // A simple way to think about this is from the wallet's point of view we
2193     // always want the blockchain to move forward. By setting nLockTime this
2194     // way we're basically making the statement that we only want this
2195     // transaction to appear in the next block; we don't want to potentially
2196     // encourage reorgs by allowing transactions to appear at lower heights
2197     // than the next block in forks of the best chain.
2198     //
2199     // Of course, the subsidy is high enough, and transaction volume low
2200     // enough, that fee sniping isn't a problem yet, but by implementing a fix
2201     // now we ensure code won't be written that makes assumptions about
2202     // nLockTime that preclude a fix later.
2203     txNew.nLockTime = chainActive.Height();
2204 
2205     // Secondly occasionally randomly pick a nLockTime even further back, so
2206     // that transactions that are delayed after signing for whatever reason,
2207     // e.g. high-latency mix networks and some CoinJoin implementations, have
2208     // better privacy.
2209     if (GetRandInt(10) == 0)
2210         txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2211 
2212     assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2213     assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2214 
2215     {
2216         LOCK2(cs_main, cs_wallet);
2217         {
2218             std::vector<COutput> vAvailableCoins;
2219             AvailableCoins(vAvailableCoins, true, coinControl);
2220 
2221             nFeeRet = 0;
2222             // Start with no fee and loop until there is enough fee
2223             while (true)
2224             {
2225                 nChangePosInOut = nChangePosRequest;
2226                 txNew.vin.clear();
2227                 txNew.vout.clear();
2228                 txNew.wit.SetNull();
2229                 wtxNew.fFromMe = true;
2230                 bool fFirst = true;
2231 
2232                 CAmount nValueToSelect = nValue;
2233                 if (nSubtractFeeFromAmount == 0)
2234                     nValueToSelect += nFeeRet;
2235                 double dPriority = 0;
2236                 // vouts to the payees
2237                 BOOST_FOREACH (const CRecipient& recipient, vecSend)
2238                 {
2239                     CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2240 
2241                     if (recipient.fSubtractFeeFromAmount)
2242                     {
2243                         txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2244 
2245                         if (fFirst) // first receiver pays the remainder not divisible by output count
2246                         {
2247                             fFirst = false;
2248                             txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2249                         }
2250                     }
2251 
2252                     if (txout.IsDust(::minRelayTxFee))
2253                     {
2254                         if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2255                         {
2256                             if (txout.nValue < 0)
2257                                 strFailReason = _("The transaction amount is too small to pay the fee");
2258                             else
2259                                 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2260                         }
2261                         else
2262                             strFailReason = _("Transaction amount too small");
2263                         return false;
2264                     }
2265                     txNew.vout.push_back(txout);
2266                 }
2267 
2268                 // Choose coins to use
2269                 set<pair<const CWalletTx*,unsigned int> > setCoins;
2270                 CAmount nValueIn = 0;
2271                 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, coinControl))
2272                 {
2273                     strFailReason = _("Insufficient funds");
2274                     return false;
2275                 }
2276                 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
2277                 {
2278                     CAmount nCredit = pcoin.first->vout[pcoin.second].nValue;
2279                     //The coin age after the next block (depth+1) is used instead of the current,
2280                     //reflecting an assumption the user would accept a bit more delay for
2281                     //a chance at a free transaction.
2282                     //But mempool inputs might still be in the mempool, so their age stays 0
2283                     int age = pcoin.first->GetDepthInMainChain();
2284                     assert(age >= 0);
2285                     if (age != 0)
2286                         age += 1;
2287                     dPriority += (double)nCredit * age;
2288                 }
2289 
2290                 const CAmount nChange = nValueIn - nValueToSelect;
2291                 if (nChange > 0)
2292                 {
2293                     // Fill a vout to ourself
2294                     // TODO: pass in scriptChange instead of reservekey so
2295                     // change transaction isn't always pay-to-bitcoin-address
2296                     CScript scriptChange;
2297 
2298                     // coin control: send change to custom address
2299                     if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
2300                         scriptChange = GetScriptForDestination(coinControl->destChange);
2301 
2302                     // no coin control: send change to newly generated address
2303                     else
2304                     {
2305                         // Note: We use a new key here to keep it from being obvious which side is the change.
2306                         //  The drawback is that by not reusing a previous key, the change may be lost if a
2307                         //  backup is restored, if the backup doesn't have the new private key for the change.
2308                         //  If we reused the old key, it would be possible to add code to look for and
2309                         //  rediscover unknown transactions that were written with keys of ours to recover
2310                         //  post-backup change.
2311 
2312                         // Reserve a new key pair from key pool
2313                         CPubKey vchPubKey;
2314                         bool ret;
2315                         ret = reservekey.GetReservedKey(vchPubKey);
2316                         if (!ret)
2317                         {
2318                             strFailReason = _("Keypool ran out, please call keypoolrefill first");
2319                             return false;
2320                         }
2321 
2322                         scriptChange = GetScriptForDestination(vchPubKey.GetID());
2323                     }
2324 
2325                     CTxOut newTxOut(nChange, scriptChange);
2326 
2327                     // We do not move dust-change to fees, because the sender would end up paying more than requested.
2328                     // This would be against the purpose of the all-inclusive feature.
2329                     // So instead we raise the change and deduct from the recipient.
2330                     if (nSubtractFeeFromAmount > 0 && newTxOut.IsDust(::minRelayTxFee))
2331                     {
2332                         CAmount nDust = newTxOut.GetDustThreshold(::minRelayTxFee) - newTxOut.nValue;
2333                         newTxOut.nValue += nDust; // raise change until no more dust
2334                         for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
2335                         {
2336                             if (vecSend[i].fSubtractFeeFromAmount)
2337                             {
2338                                 txNew.vout[i].nValue -= nDust;
2339                                 if (txNew.vout[i].IsDust(::minRelayTxFee))
2340                                 {
2341                                     strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2342                                     return false;
2343                                 }
2344                                 break;
2345                             }
2346                         }
2347                     }
2348 
2349                     // Never create dust outputs; if we would, just
2350                     // add the dust to the fee.
2351                     if (newTxOut.IsDust(::minRelayTxFee))
2352                     {
2353                         nChangePosInOut = -1;
2354                         nFeeRet += nChange;
2355                         reservekey.ReturnKey();
2356                     }
2357                     else
2358                     {
2359                         if (nChangePosInOut == -1)
2360                         {
2361                             // Insert change txn at random position:
2362                             nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2363                         }
2364                         else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2365                         {
2366                             strFailReason = _("Change index out of range");
2367                             return false;
2368                         }
2369 
2370                         vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2371                         txNew.vout.insert(position, newTxOut);
2372                     }
2373                 }
2374                 else
2375                     reservekey.ReturnKey();
2376 
2377                 // Fill vin
2378                 //
2379                 // Note how the sequence number is set to max()-1 so that the
2380                 // nLockTime set above actually works.
2381                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2382                     txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
2383                                               std::numeric_limits<unsigned int>::max()-1));
2384 
2385                 // Sign
2386                 int nIn = 0;
2387                 CTransaction txNewConst(txNew);
2388                 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2389                 {
2390                     bool signSuccess;
2391                     const CScript& scriptPubKey = coin.first->vout[coin.second].scriptPubKey;
2392                     SignatureData sigdata;
2393                     if (sign)
2394                         signSuccess = ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.first->vout[coin.second].nValue, SIGHASH_ALL), scriptPubKey, sigdata);
2395                     else
2396                         signSuccess = ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata);
2397 
2398                     if (!signSuccess)
2399                     {
2400                         strFailReason = _("Signing transaction failed");
2401                         return false;
2402                     } else {
2403                         UpdateTransaction(txNew, nIn, sigdata);
2404                     }
2405 
2406                     nIn++;
2407                 }
2408 
2409                 unsigned int nBytes = GetVirtualTransactionSize(txNew);
2410 
2411                 // Remove scriptSigs if we used dummy signatures for fee calculation
2412                 if (!sign) {
2413                     BOOST_FOREACH (CTxIn& vin, txNew.vin)
2414                         vin.scriptSig = CScript();
2415                     txNew.wit.SetNull();
2416                 }
2417 
2418                 // Embed the constructed transaction data in wtxNew.
2419                 *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew);
2420 
2421                 // Limit size
2422                 if (GetTransactionWeight(txNew) >= MAX_STANDARD_TX_WEIGHT)
2423                 {
2424                     strFailReason = _("Transaction too large");
2425                     return false;
2426                 }
2427 
2428                 dPriority = wtxNew.ComputePriority(dPriority, nBytes);
2429 
2430                 // Can we complete this as a free transaction?
2431                 if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
2432                 {
2433                     // Not enough fee: enough priority?
2434                     double dPriorityNeeded = mempool.estimateSmartPriority(nTxConfirmTarget);
2435                     // Require at least hard-coded AllowFree.
2436                     if (dPriority >= dPriorityNeeded && AllowFree(dPriority))
2437                         break;
2438                 }
2439 
2440                 CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool);
2441                 if (coinControl && nFeeNeeded > 0 && coinControl->nMinimumTotalFee > nFeeNeeded) {
2442                     nFeeNeeded = coinControl->nMinimumTotalFee;
2443                 }
2444                 if (coinControl && coinControl->fOverrideFeeRate)
2445                     nFeeNeeded = coinControl->nFeeRate.GetFee(nBytes);
2446 
2447                 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2448                 // because we must be at the maximum allowed fee.
2449                 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2450                 {
2451                     strFailReason = _("Transaction too large for fee policy");
2452                     return false;
2453                 }
2454 
2455                 if (nFeeRet >= nFeeNeeded)
2456                     break; // Done, enough fee included.
2457 
2458                 // Include more fee and try again.
2459                 nFeeRet = nFeeNeeded;
2460                 continue;
2461             }
2462         }
2463     }
2464 
2465     if (GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2466         // Lastly, ensure this tx will pass the mempool's chain limits
2467         LockPoints lp;
2468         CTxMemPoolEntry entry(txNew, 0, 0, 0, 0, false, 0, false, 0, lp);
2469         CTxMemPool::setEntries setAncestors;
2470         size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2471         size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2472         size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2473         size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2474         std::string errString;
2475         if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2476             strFailReason = _("Transaction has too long of a mempool chain");
2477             return false;
2478         }
2479     }
2480     return true;
2481 }
2482 
2483 /**
2484  * Call after CreateTransaction unless you want to abort
2485  */
CommitTransaction(CWalletTx & wtxNew,CReserveKey & reservekey)2486 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey)
2487 {
2488     {
2489         LOCK2(cs_main, cs_wallet);
2490         LogPrintf("CommitTransaction:\n%s", wtxNew.ToString());
2491         {
2492             // This is only to keep the database open to defeat the auto-flush for the
2493             // duration of this scope.  This is the only place where this optimization
2494             // maybe makes sense; please don't do it anywhere else.
2495             CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r+") : NULL;
2496 
2497             // Take key pair from key pool so it won't be used again
2498             reservekey.KeepKey();
2499 
2500             // Add tx to wallet, because if it has change it's also ours,
2501             // otherwise just for transaction history.
2502             AddToWallet(wtxNew, false, pwalletdb);
2503 
2504             // Notify that old coins are spent
2505             set<CWalletTx*> setCoins;
2506             BOOST_FOREACH(const CTxIn& txin, wtxNew.vin)
2507             {
2508                 CWalletTx &coin = mapWallet[txin.prevout.hash];
2509                 coin.BindWallet(this);
2510                 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2511             }
2512 
2513             if (fFileBacked)
2514                 delete pwalletdb;
2515         }
2516 
2517         // Track how many getdata requests our transaction gets
2518         mapRequestCount[wtxNew.GetHash()] = 0;
2519 
2520         if (fBroadcastTransactions)
2521         {
2522             CValidationState state;
2523             // Broadcast
2524             if (!wtxNew.AcceptToMemoryPool(false, maxTxFee, state)) {
2525                 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
2526                 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2527             } else {
2528                 wtxNew.RelayWalletTransaction();
2529             }
2530         }
2531     }
2532     return true;
2533 }
2534 
AddAccountingEntry(const CAccountingEntry & acentry,CWalletDB & pwalletdb)2535 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB & pwalletdb)
2536 {
2537     if (!pwalletdb.WriteAccountingEntry_Backend(acentry))
2538         return false;
2539 
2540     laccentries.push_back(acentry);
2541     CAccountingEntry & entry = laccentries.back();
2542     wtxOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
2543 
2544     return true;
2545 }
2546 
GetRequiredFee(unsigned int nTxBytes)2547 CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
2548 {
2549     return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
2550 }
2551 
GetMinimumFee(unsigned int nTxBytes,unsigned int nConfirmTarget,const CTxMemPool & pool)2552 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
2553 {
2554     // payTxFee is user-set "I want to pay this much"
2555     CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
2556     // User didn't set: use -txconfirmtarget to estimate...
2557     if (nFeeNeeded == 0) {
2558         int estimateFoundTarget = nConfirmTarget;
2559         nFeeNeeded = pool.estimateSmartFee(nConfirmTarget, &estimateFoundTarget).GetFee(nTxBytes);
2560         // ... unless we don't have enough mempool data for estimatefee, then use fallbackFee
2561         if (nFeeNeeded == 0)
2562             nFeeNeeded = fallbackFee.GetFee(nTxBytes);
2563     }
2564     // prevent user from paying a fee below minRelayTxFee or minTxFee
2565     nFeeNeeded = std::max(nFeeNeeded, GetRequiredFee(nTxBytes));
2566     // But always obey the maximum
2567     if (nFeeNeeded > maxTxFee)
2568         nFeeNeeded = maxTxFee;
2569     return nFeeNeeded;
2570 }
2571 
2572 
2573 
2574 
LoadWallet(bool & fFirstRunRet)2575 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2576 {
2577     if (!fFileBacked)
2578         return DB_LOAD_OK;
2579     fFirstRunRet = false;
2580     DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2581     if (nLoadWalletRet == DB_NEED_REWRITE)
2582     {
2583         if (CDB::Rewrite(strWalletFile, "\x04pool"))
2584         {
2585             LOCK(cs_wallet);
2586             setKeyPool.clear();
2587             // Note: can't top-up keypool here, because wallet is locked.
2588             // User will be prompted to unlock wallet the next operation
2589             // that requires a new key.
2590         }
2591     }
2592 
2593     if (nLoadWalletRet != DB_LOAD_OK)
2594         return nLoadWalletRet;
2595     fFirstRunRet = !vchDefaultKey.IsValid();
2596 
2597     uiInterface.LoadWallet(this);
2598 
2599     return DB_LOAD_OK;
2600 }
2601 
ZapSelectTx(vector<uint256> & vHashIn,vector<uint256> & vHashOut)2602 DBErrors CWallet::ZapSelectTx(vector<uint256>& vHashIn, vector<uint256>& vHashOut)
2603 {
2604     if (!fFileBacked)
2605         return DB_LOAD_OK;
2606     DBErrors nZapSelectTxRet = CWalletDB(strWalletFile,"cr+").ZapSelectTx(this, vHashIn, vHashOut);
2607     if (nZapSelectTxRet == DB_NEED_REWRITE)
2608     {
2609         if (CDB::Rewrite(strWalletFile, "\x04pool"))
2610         {
2611             LOCK(cs_wallet);
2612             setKeyPool.clear();
2613             // Note: can't top-up keypool here, because wallet is locked.
2614             // User will be prompted to unlock wallet the next operation
2615             // that requires a new key.
2616         }
2617     }
2618 
2619     if (nZapSelectTxRet != DB_LOAD_OK)
2620         return nZapSelectTxRet;
2621 
2622     MarkDirty();
2623 
2624     return DB_LOAD_OK;
2625 
2626 }
2627 
ZapWalletTx(std::vector<CWalletTx> & vWtx)2628 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
2629 {
2630     if (!fFileBacked)
2631         return DB_LOAD_OK;
2632     DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
2633     if (nZapWalletTxRet == DB_NEED_REWRITE)
2634     {
2635         if (CDB::Rewrite(strWalletFile, "\x04pool"))
2636         {
2637             LOCK(cs_wallet);
2638             setKeyPool.clear();
2639             // Note: can't top-up keypool here, because wallet is locked.
2640             // User will be prompted to unlock wallet the next operation
2641             // that requires a new key.
2642         }
2643     }
2644 
2645     if (nZapWalletTxRet != DB_LOAD_OK)
2646         return nZapWalletTxRet;
2647 
2648     return DB_LOAD_OK;
2649 }
2650 
2651 
SetAddressBook(const CTxDestination & address,const string & strName,const string & strPurpose)2652 bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
2653 {
2654     bool fUpdated = false;
2655     {
2656         LOCK(cs_wallet); // mapAddressBook
2657         std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
2658         fUpdated = mi != mapAddressBook.end();
2659         mapAddressBook[address].name = strName;
2660         if (!strPurpose.empty()) /* update purpose only if requested */
2661             mapAddressBook[address].purpose = strPurpose;
2662     }
2663     NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
2664                              strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
2665     if (!fFileBacked)
2666         return false;
2667     if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
2668         return false;
2669     return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2670 }
2671 
DelAddressBook(const CTxDestination & address)2672 bool CWallet::DelAddressBook(const CTxDestination& address)
2673 {
2674     {
2675         LOCK(cs_wallet); // mapAddressBook
2676 
2677         if(fFileBacked)
2678         {
2679             // Delete destdata tuples associated with address
2680             std::string strAddress = CBitcoinAddress(address).ToString();
2681             BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
2682             {
2683                 CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
2684             }
2685         }
2686         mapAddressBook.erase(address);
2687     }
2688 
2689     NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
2690 
2691     if (!fFileBacked)
2692         return false;
2693     CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
2694     return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2695 }
2696 
SetDefaultKey(const CPubKey & vchPubKey)2697 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2698 {
2699     if (fFileBacked)
2700     {
2701         if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2702             return false;
2703     }
2704     vchDefaultKey = vchPubKey;
2705     return true;
2706 }
2707 
2708 /**
2709  * Mark old keypool keys as used,
2710  * and generate all new keys
2711  */
NewKeyPool()2712 bool CWallet::NewKeyPool()
2713 {
2714     {
2715         LOCK(cs_wallet);
2716         CWalletDB walletdb(strWalletFile);
2717         BOOST_FOREACH(int64_t nIndex, setKeyPool)
2718             walletdb.ErasePool(nIndex);
2719         setKeyPool.clear();
2720 
2721         if (IsLocked())
2722             return false;
2723 
2724         int64_t nKeys = max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t)0);
2725         for (int i = 0; i < nKeys; i++)
2726         {
2727             int64_t nIndex = i+1;
2728             walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2729             setKeyPool.insert(nIndex);
2730         }
2731         LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
2732     }
2733     return true;
2734 }
2735 
TopUpKeyPool(unsigned int kpSize)2736 bool CWallet::TopUpKeyPool(unsigned int kpSize)
2737 {
2738     {
2739         LOCK(cs_wallet);
2740 
2741         if (IsLocked())
2742             return false;
2743 
2744         CWalletDB walletdb(strWalletFile);
2745 
2746         // Top up key pool
2747         unsigned int nTargetSize;
2748         if (kpSize > 0)
2749             nTargetSize = kpSize;
2750         else
2751             nTargetSize = max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
2752 
2753         while (setKeyPool.size() < (nTargetSize + 1))
2754         {
2755             int64_t nEnd = 1;
2756             if (!setKeyPool.empty())
2757                 nEnd = *(--setKeyPool.end()) + 1;
2758             if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2759                 throw runtime_error(std::string(__func__) + ": writing generated key failed");
2760             setKeyPool.insert(nEnd);
2761             LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
2762         }
2763     }
2764     return true;
2765 }
2766 
ReserveKeyFromKeyPool(int64_t & nIndex,CKeyPool & keypool)2767 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2768 {
2769     nIndex = -1;
2770     keypool.vchPubKey = CPubKey();
2771     {
2772         LOCK(cs_wallet);
2773 
2774         if (!IsLocked())
2775             TopUpKeyPool();
2776 
2777         // Get the oldest key
2778         if(setKeyPool.empty())
2779             return;
2780 
2781         CWalletDB walletdb(strWalletFile);
2782 
2783         nIndex = *(setKeyPool.begin());
2784         setKeyPool.erase(setKeyPool.begin());
2785         if (!walletdb.ReadPool(nIndex, keypool))
2786             throw runtime_error(std::string(__func__) + ": read failed");
2787         if (!HaveKey(keypool.vchPubKey.GetID()))
2788             throw runtime_error(std::string(__func__) + ": unknown key in key pool");
2789         assert(keypool.vchPubKey.IsValid());
2790         LogPrintf("keypool reserve %d\n", nIndex);
2791     }
2792 }
2793 
KeepKey(int64_t nIndex)2794 void CWallet::KeepKey(int64_t nIndex)
2795 {
2796     // Remove from key pool
2797     if (fFileBacked)
2798     {
2799         CWalletDB walletdb(strWalletFile);
2800         walletdb.ErasePool(nIndex);
2801     }
2802     LogPrintf("keypool keep %d\n", nIndex);
2803 }
2804 
ReturnKey(int64_t nIndex)2805 void CWallet::ReturnKey(int64_t nIndex)
2806 {
2807     // Return to key pool
2808     {
2809         LOCK(cs_wallet);
2810         setKeyPool.insert(nIndex);
2811     }
2812     LogPrintf("keypool return %d\n", nIndex);
2813 }
2814 
GetKeyFromPool(CPubKey & result)2815 bool CWallet::GetKeyFromPool(CPubKey& result)
2816 {
2817     int64_t nIndex = 0;
2818     CKeyPool keypool;
2819     {
2820         LOCK(cs_wallet);
2821         ReserveKeyFromKeyPool(nIndex, keypool);
2822         if (nIndex == -1)
2823         {
2824             if (IsLocked()) return false;
2825             result = GenerateNewKey();
2826             return true;
2827         }
2828         KeepKey(nIndex);
2829         result = keypool.vchPubKey;
2830     }
2831     return true;
2832 }
2833 
GetOldestKeyPoolTime()2834 int64_t CWallet::GetOldestKeyPoolTime()
2835 {
2836     LOCK(cs_wallet);
2837 
2838     // if the keypool is empty, return <NOW>
2839     if (setKeyPool.empty())
2840         return GetTime();
2841 
2842     // load oldest key from keypool, get time and return
2843     CKeyPool keypool;
2844     CWalletDB walletdb(strWalletFile);
2845     int64_t nIndex = *(setKeyPool.begin());
2846     if (!walletdb.ReadPool(nIndex, keypool))
2847         throw runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
2848     assert(keypool.vchPubKey.IsValid());
2849     return keypool.nTime;
2850 }
2851 
GetAddressBalances()2852 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
2853 {
2854     map<CTxDestination, CAmount> balances;
2855 
2856     {
2857         LOCK(cs_wallet);
2858         BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2859         {
2860             CWalletTx *pcoin = &walletEntry.second;
2861 
2862             if (!CheckFinalTx(*pcoin) || !pcoin->IsTrusted())
2863                 continue;
2864 
2865             if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2866                 continue;
2867 
2868             int nDepth = pcoin->GetDepthInMainChain();
2869             if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
2870                 continue;
2871 
2872             for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2873             {
2874                 CTxDestination addr;
2875                 if (!IsMine(pcoin->vout[i]))
2876                     continue;
2877                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, addr))
2878                     continue;
2879 
2880                 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue;
2881 
2882                 if (!balances.count(addr))
2883                     balances[addr] = 0;
2884                 balances[addr] += n;
2885             }
2886         }
2887     }
2888 
2889     return balances;
2890 }
2891 
GetAddressGroupings()2892 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2893 {
2894     AssertLockHeld(cs_wallet); // mapWallet
2895     set< set<CTxDestination> > groupings;
2896     set<CTxDestination> grouping;
2897 
2898     BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2899     {
2900         CWalletTx *pcoin = &walletEntry.second;
2901 
2902         if (pcoin->vin.size() > 0)
2903         {
2904             bool any_mine = false;
2905             // group all input addresses with each other
2906             BOOST_FOREACH(CTxIn txin, pcoin->vin)
2907             {
2908                 CTxDestination address;
2909                 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
2910                     continue;
2911                 if(!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address))
2912                     continue;
2913                 grouping.insert(address);
2914                 any_mine = true;
2915             }
2916 
2917             // group change with input addresses
2918             if (any_mine)
2919             {
2920                BOOST_FOREACH(CTxOut txout, pcoin->vout)
2921                    if (IsChange(txout))
2922                    {
2923                        CTxDestination txoutAddr;
2924                        if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2925                            continue;
2926                        grouping.insert(txoutAddr);
2927                    }
2928             }
2929             if (grouping.size() > 0)
2930             {
2931                 groupings.insert(grouping);
2932                 grouping.clear();
2933             }
2934         }
2935 
2936         // group lone addrs by themselves
2937         for (unsigned int i = 0; i < pcoin->vout.size(); i++)
2938             if (IsMine(pcoin->vout[i]))
2939             {
2940                 CTxDestination address;
2941                 if(!ExtractDestination(pcoin->vout[i].scriptPubKey, address))
2942                     continue;
2943                 grouping.insert(address);
2944                 groupings.insert(grouping);
2945                 grouping.clear();
2946             }
2947     }
2948 
2949     set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
2950     map< CTxDestination, set<CTxDestination>* > setmap;  // map addresses to the unique group containing it
2951     BOOST_FOREACH(set<CTxDestination> grouping, groupings)
2952     {
2953         // make a set of all the groups hit by this new group
2954         set< set<CTxDestination>* > hits;
2955         map< CTxDestination, set<CTxDestination>* >::iterator it;
2956         BOOST_FOREACH(CTxDestination address, grouping)
2957             if ((it = setmap.find(address)) != setmap.end())
2958                 hits.insert((*it).second);
2959 
2960         // merge all hit groups into a new single group and delete old groups
2961         set<CTxDestination>* merged = new set<CTxDestination>(grouping);
2962         BOOST_FOREACH(set<CTxDestination>* hit, hits)
2963         {
2964             merged->insert(hit->begin(), hit->end());
2965             uniqueGroupings.erase(hit);
2966             delete hit;
2967         }
2968         uniqueGroupings.insert(merged);
2969 
2970         // update setmap
2971         BOOST_FOREACH(CTxDestination element, *merged)
2972             setmap[element] = merged;
2973     }
2974 
2975     set< set<CTxDestination> > ret;
2976     BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
2977     {
2978         ret.insert(*uniqueGrouping);
2979         delete uniqueGrouping;
2980     }
2981 
2982     return ret;
2983 }
2984 
GetAccountBalance(const std::string & strAccount,int nMinDepth,const isminefilter & filter)2985 CAmount CWallet::GetAccountBalance(const std::string& strAccount, int nMinDepth, const isminefilter& filter)
2986 {
2987     CWalletDB walletdb(strWalletFile);
2988     return GetAccountBalance(walletdb, strAccount, nMinDepth, filter);
2989 }
2990 
GetAccountBalance(CWalletDB & walletdb,const std::string & strAccount,int nMinDepth,const isminefilter & filter)2991 CAmount CWallet::GetAccountBalance(CWalletDB& walletdb, const std::string& strAccount, int nMinDepth, const isminefilter& filter)
2992 {
2993     CAmount nBalance = 0;
2994 
2995     // Tally wallet transactions
2996     for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2997     {
2998         const CWalletTx& wtx = (*it).second;
2999         if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0)
3000             continue;
3001 
3002         CAmount nReceived, nSent, nFee;
3003         wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee, filter);
3004 
3005         if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
3006             nBalance += nReceived;
3007         nBalance -= nSent + nFee;
3008     }
3009 
3010     // Tally internal accounting entries
3011     nBalance += walletdb.GetAccountCreditDebit(strAccount);
3012 
3013     return nBalance;
3014 }
3015 
GetAccountAddresses(const std::string & strAccount) const3016 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3017 {
3018     LOCK(cs_wallet);
3019     set<CTxDestination> result;
3020     BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
3021     {
3022         const CTxDestination& address = item.first;
3023         const string& strName = item.second.name;
3024         if (strName == strAccount)
3025             result.insert(address);
3026     }
3027     return result;
3028 }
3029 
GetReservedKey(CPubKey & pubkey)3030 bool CReserveKey::GetReservedKey(CPubKey& pubkey)
3031 {
3032     if (nIndex == -1)
3033     {
3034         CKeyPool keypool;
3035         pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
3036         if (nIndex != -1)
3037             vchPubKey = keypool.vchPubKey;
3038         else {
3039             return false;
3040         }
3041     }
3042     assert(vchPubKey.IsValid());
3043     pubkey = vchPubKey;
3044     return true;
3045 }
3046 
KeepKey()3047 void CReserveKey::KeepKey()
3048 {
3049     if (nIndex != -1)
3050         pwallet->KeepKey(nIndex);
3051     nIndex = -1;
3052     vchPubKey = CPubKey();
3053 }
3054 
ReturnKey()3055 void CReserveKey::ReturnKey()
3056 {
3057     if (nIndex != -1)
3058         pwallet->ReturnKey(nIndex);
3059     nIndex = -1;
3060     vchPubKey = CPubKey();
3061 }
3062 
GetAllReserveKeys(set<CKeyID> & setAddress) const3063 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
3064 {
3065     setAddress.clear();
3066 
3067     CWalletDB walletdb(strWalletFile);
3068 
3069     LOCK2(cs_main, cs_wallet);
3070     BOOST_FOREACH(const int64_t& id, setKeyPool)
3071     {
3072         CKeyPool keypool;
3073         if (!walletdb.ReadPool(id, keypool))
3074             throw runtime_error(std::string(__func__) + ": read failed");
3075         assert(keypool.vchPubKey.IsValid());
3076         CKeyID keyID = keypool.vchPubKey.GetID();
3077         if (!HaveKey(keyID))
3078             throw runtime_error(std::string(__func__) + ": unknown key in key pool");
3079         setAddress.insert(keyID);
3080     }
3081 }
3082 
UpdatedTransaction(const uint256 & hashTx)3083 void CWallet::UpdatedTransaction(const uint256 &hashTx)
3084 {
3085     {
3086         LOCK(cs_wallet);
3087         // Only notify UI if this transaction is in this wallet
3088         map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
3089         if (mi != mapWallet.end())
3090             NotifyTransactionChanged(this, hashTx, CT_UPDATED);
3091     }
3092 }
3093 
GetScriptForMining(boost::shared_ptr<CReserveScript> & script)3094 void CWallet::GetScriptForMining(boost::shared_ptr<CReserveScript> &script)
3095 {
3096     boost::shared_ptr<CReserveKey> rKey(new CReserveKey(this));
3097     CPubKey pubkey;
3098     if (!rKey->GetReservedKey(pubkey))
3099         return;
3100 
3101     script = rKey;
3102     script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3103 }
3104 
LockCoin(const COutPoint & output)3105 void CWallet::LockCoin(const COutPoint& output)
3106 {
3107     AssertLockHeld(cs_wallet); // setLockedCoins
3108     setLockedCoins.insert(output);
3109 }
3110 
UnlockCoin(const COutPoint & output)3111 void CWallet::UnlockCoin(const COutPoint& output)
3112 {
3113     AssertLockHeld(cs_wallet); // setLockedCoins
3114     setLockedCoins.erase(output);
3115 }
3116 
UnlockAllCoins()3117 void CWallet::UnlockAllCoins()
3118 {
3119     AssertLockHeld(cs_wallet); // setLockedCoins
3120     setLockedCoins.clear();
3121 }
3122 
IsLockedCoin(uint256 hash,unsigned int n) const3123 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3124 {
3125     AssertLockHeld(cs_wallet); // setLockedCoins
3126     COutPoint outpt(hash, n);
3127 
3128     return (setLockedCoins.count(outpt) > 0);
3129 }
3130 
ListLockedCoins(std::vector<COutPoint> & vOutpts)3131 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
3132 {
3133     AssertLockHeld(cs_wallet); // setLockedCoins
3134     for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3135          it != setLockedCoins.end(); it++) {
3136         COutPoint outpt = (*it);
3137         vOutpts.push_back(outpt);
3138     }
3139 }
3140 
3141 /** @} */ // end of Actions
3142 
3143 class CAffectedKeysVisitor : public boost::static_visitor<void> {
3144 private:
3145     const CKeyStore &keystore;
3146     std::vector<CKeyID> &vKeys;
3147 
3148 public:
CAffectedKeysVisitor(const CKeyStore & keystoreIn,std::vector<CKeyID> & vKeysIn)3149     CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
3150 
Process(const CScript & script)3151     void Process(const CScript &script) {
3152         txnouttype type;
3153         std::vector<CTxDestination> vDest;
3154         int nRequired;
3155         if (ExtractDestinations(script, type, vDest, nRequired)) {
3156             BOOST_FOREACH(const CTxDestination &dest, vDest)
3157                 boost::apply_visitor(*this, dest);
3158         }
3159     }
3160 
operator ()(const CKeyID & keyId)3161     void operator()(const CKeyID &keyId) {
3162         if (keystore.HaveKey(keyId))
3163             vKeys.push_back(keyId);
3164     }
3165 
operator ()(const CScriptID & scriptId)3166     void operator()(const CScriptID &scriptId) {
3167         CScript script;
3168         if (keystore.GetCScript(scriptId, script))
3169             Process(script);
3170     }
3171 
operator ()(const CNoDestination & none)3172     void operator()(const CNoDestination &none) {}
3173 };
3174 
GetKeyBirthTimes(std::map<CKeyID,int64_t> & mapKeyBirth) const3175 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
3176     AssertLockHeld(cs_wallet); // mapKeyMetadata
3177     mapKeyBirth.clear();
3178 
3179     // get birth times for keys with metadata
3180     for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
3181         if (it->second.nCreateTime)
3182             mapKeyBirth[it->first] = it->second.nCreateTime;
3183 
3184     // map in which we'll infer heights of other keys
3185     CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3186     std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3187     std::set<CKeyID> setKeys;
3188     GetKeys(setKeys);
3189     BOOST_FOREACH(const CKeyID &keyid, setKeys) {
3190         if (mapKeyBirth.count(keyid) == 0)
3191             mapKeyFirstBlock[keyid] = pindexMax;
3192     }
3193     setKeys.clear();
3194 
3195     // if there are no such keys, we're done
3196     if (mapKeyFirstBlock.empty())
3197         return;
3198 
3199     // find first block that affects those keys, if there are any left
3200     std::vector<CKeyID> vAffected;
3201     for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3202         // iterate over all wallet transactions...
3203         const CWalletTx &wtx = (*it).second;
3204         BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3205         if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3206             // ... which are already in a block
3207             int nHeight = blit->second->nHeight;
3208             BOOST_FOREACH(const CTxOut &txout, wtx.vout) {
3209                 // iterate over all their outputs
3210                 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3211                 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
3212                     // ... and all their affected keys
3213                     std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3214                     if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3215                         rit->second = blit->second;
3216                 }
3217                 vAffected.clear();
3218             }
3219         }
3220     }
3221 
3222     // Extract block timestamps for those keys
3223     for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3224         mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
3225 }
3226 
AddDestData(const CTxDestination & dest,const std::string & key,const std::string & value)3227 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3228 {
3229     if (boost::get<CNoDestination>(&dest))
3230         return false;
3231 
3232     mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3233     if (!fFileBacked)
3234         return true;
3235     return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
3236 }
3237 
EraseDestData(const CTxDestination & dest,const std::string & key)3238 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3239 {
3240     if (!mapAddressBook[dest].destdata.erase(key))
3241         return false;
3242     if (!fFileBacked)
3243         return true;
3244     return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
3245 }
3246 
LoadDestData(const CTxDestination & dest,const std::string & key,const std::string & value)3247 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3248 {
3249     mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3250     return true;
3251 }
3252 
GetDestData(const CTxDestination & dest,const std::string & key,std::string * value) const3253 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3254 {
3255     std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3256     if(i != mapAddressBook.end())
3257     {
3258         CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3259         if(j != i->second.destdata.end())
3260         {
3261             if(value)
3262                 *value = j->second;
3263             return true;
3264         }
3265     }
3266     return false;
3267 }
3268 
GetWalletHelpString(bool showDebug)3269 std::string CWallet::GetWalletHelpString(bool showDebug)
3270 {
3271     std::string strUsage = HelpMessageGroup(_("Wallet options:"));
3272     strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
3273     strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE));
3274     strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
3275                                                                CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)));
3276     strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
3277                                                             CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)));
3278     strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
3279                                                             CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
3280     strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
3281     strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup"));
3282     if (showDebug)
3283         strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), DEFAULT_SEND_FREE_TRANSACTIONS));
3284     strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE));
3285     strUsage += HelpMessageOpt("-txconfirmtarget=<n>", strprintf(_("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)"), DEFAULT_TX_CONFIRM_TARGET));
3286     strUsage += HelpMessageOpt("-usehd", _("Use hierarchical deterministic key generation (HD) after BIP32. Only has effect during wallet creation/first start") + " " + strprintf(_("(default: %u)"), DEFAULT_USE_HD_WALLET));
3287     strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
3288     strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT));
3289     strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST));
3290     strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
3291     strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
3292                                " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
3293 
3294     if (showDebug)
3295     {
3296         strUsage += HelpMessageGroup(_("Wallet debugging/testing options:"));
3297 
3298         strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE));
3299         strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET));
3300         strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB));
3301         strUsage += HelpMessageOpt("-walletrejectlongchains", strprintf(_("Wallet will not create transactions that violate mempool chain limits (default: %u"), DEFAULT_WALLET_REJECT_LONG_CHAINS));
3302     }
3303 
3304     return strUsage;
3305 }
3306 
InitLoadWallet()3307 bool CWallet::InitLoadWallet()
3308 {
3309     std::string walletFile = GetArg("-wallet", DEFAULT_WALLET_DAT);
3310 
3311     // needed to restore wallet transaction meta data after -zapwallettxes
3312     std::vector<CWalletTx> vWtx;
3313 
3314     if (GetBoolArg("-zapwallettxes", false)) {
3315         uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3316 
3317         CWallet *tempWallet = new CWallet(walletFile);
3318         DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3319         if (nZapWalletRet != DB_LOAD_OK) {
3320             return InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3321         }
3322 
3323         delete tempWallet;
3324         tempWallet = NULL;
3325     }
3326 
3327     uiInterface.InitMessage(_("Loading wallet..."));
3328 
3329     int64_t nStart = GetTimeMillis();
3330     bool fFirstRun = true;
3331     CWallet *walletInstance = new CWallet(walletFile);
3332     DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3333     if (nLoadWalletRet != DB_LOAD_OK)
3334     {
3335         if (nLoadWalletRet == DB_CORRUPT)
3336             return InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3337         else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3338         {
3339             InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3340                                          " or address book entries might be missing or incorrect."),
3341                 walletFile));
3342         }
3343         else if (nLoadWalletRet == DB_TOO_NEW)
3344             return InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"),
3345                                walletFile, _(PACKAGE_NAME)));
3346         else if (nLoadWalletRet == DB_NEED_REWRITE)
3347         {
3348             return InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3349         }
3350         else
3351             return InitError(strprintf(_("Error loading %s"), walletFile));
3352     }
3353 
3354     if (GetBoolArg("-upgradewallet", fFirstRun))
3355     {
3356         int nMaxVersion = GetArg("-upgradewallet", 0);
3357         if (nMaxVersion == 0) // the -upgradewallet without argument case
3358         {
3359             LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3360             nMaxVersion = CLIENT_VERSION;
3361             walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3362         }
3363         else
3364             LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3365         if (nMaxVersion < walletInstance->GetVersion())
3366         {
3367             return InitError(_("Cannot downgrade wallet"));
3368         }
3369         walletInstance->SetMaxVersion(nMaxVersion);
3370     }
3371 
3372     if (fFirstRun)
3373     {
3374         // Create new keyUser and set as default key
3375         if (GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && walletInstance->hdChain.masterKeyID.IsNull()) {
3376             // generate a new master key
3377             CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
3378             if (!walletInstance->SetHDMasterKey(masterPubKey))
3379                 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
3380         }
3381         CPubKey newDefaultKey;
3382         if (walletInstance->GetKeyFromPool(newDefaultKey)) {
3383             walletInstance->SetDefaultKey(newDefaultKey);
3384             if (!walletInstance->SetAddressBook(walletInstance->vchDefaultKey.GetID(), "", "receive"))
3385                 return InitError(_("Cannot write default address") += "\n");
3386         }
3387 
3388         walletInstance->SetBestChain(chainActive.GetLocator());
3389     }
3390     else if (mapArgs.count("-usehd")) {
3391         bool useHD = GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
3392         if (!walletInstance->hdChain.masterKeyID.IsNull() && !useHD)
3393             return InitError(strprintf(_("Error loading %s: You can't disable HD on a already existing HD wallet"), walletFile));
3394         if (walletInstance->hdChain.masterKeyID.IsNull() && useHD)
3395             return InitError(strprintf(_("Error loading %s: You can't enable HD on a already existing non-HD wallet"), walletFile));
3396     }
3397 
3398     LogPrintf(" wallet      %15dms\n", GetTimeMillis() - nStart);
3399 
3400     RegisterValidationInterface(walletInstance);
3401 
3402     CBlockIndex *pindexRescan = chainActive.Tip();
3403     if (GetBoolArg("-rescan", false))
3404         pindexRescan = chainActive.Genesis();
3405     else
3406     {
3407         CWalletDB walletdb(walletFile);
3408         CBlockLocator locator;
3409         if (walletdb.ReadBestBlock(locator))
3410             pindexRescan = FindForkInGlobalIndex(chainActive, locator);
3411         else
3412             pindexRescan = chainActive.Genesis();
3413     }
3414     if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
3415     {
3416         //We can't rescan beyond non-pruned blocks, stop and throw an error
3417         //this might happen if a user uses a old wallet within a pruned node
3418         // or if he ran -disablewallet for a longer time, then decided to re-enable
3419         if (fPruneMode)
3420         {
3421             CBlockIndex *block = chainActive.Tip();
3422             while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
3423                 block = block->pprev;
3424 
3425             if (pindexRescan != block)
3426                 return InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3427         }
3428 
3429         uiInterface.InitMessage(_("Rescanning..."));
3430         LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
3431         nStart = GetTimeMillis();
3432         walletInstance->ScanForWalletTransactions(pindexRescan, true);
3433         LogPrintf(" rescan      %15dms\n", GetTimeMillis() - nStart);
3434         walletInstance->SetBestChain(chainActive.GetLocator());
3435         nWalletDBUpdated++;
3436 
3437         // Restore wallet transaction metadata after -zapwallettxes=1
3438         if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
3439         {
3440             CWalletDB walletdb(walletFile);
3441 
3442             BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
3443             {
3444                 uint256 hash = wtxOld.GetHash();
3445                 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
3446                 if (mi != walletInstance->mapWallet.end())
3447                 {
3448                     const CWalletTx* copyFrom = &wtxOld;
3449                     CWalletTx* copyTo = &mi->second;
3450                     copyTo->mapValue = copyFrom->mapValue;
3451                     copyTo->vOrderForm = copyFrom->vOrderForm;
3452                     copyTo->nTimeReceived = copyFrom->nTimeReceived;
3453                     copyTo->nTimeSmart = copyFrom->nTimeSmart;
3454                     copyTo->fFromMe = copyFrom->fFromMe;
3455                     copyTo->strFromAccount = copyFrom->strFromAccount;
3456                     copyTo->nOrderPos = copyFrom->nOrderPos;
3457                     walletdb.WriteTx(*copyTo);
3458                 }
3459             }
3460         }
3461     }
3462     walletInstance->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
3463 
3464     pwalletMain = walletInstance;
3465     return true;
3466 }
3467 
ParameterInteraction()3468 bool CWallet::ParameterInteraction()
3469 {
3470     if (mapArgs.count("-mintxfee"))
3471     {
3472         CAmount n = 0;
3473         if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
3474             CWallet::minTxFee = CFeeRate(n);
3475         else
3476             return InitError(AmountErrMsg("mintxfee", mapArgs["-mintxfee"]));
3477     }
3478     if (mapArgs.count("-fallbackfee"))
3479     {
3480         CAmount nFeePerK = 0;
3481         if (!ParseMoney(mapArgs["-fallbackfee"], nFeePerK))
3482             return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), mapArgs["-fallbackfee"]));
3483         if (nFeePerK > HIGH_TX_FEE_PER_KB)
3484             InitWarning(_("-fallbackfee is set very high! This is the transaction fee you may pay when fee estimates are not available."));
3485         CWallet::fallbackFee = CFeeRate(nFeePerK);
3486     }
3487     if (mapArgs.count("-paytxfee"))
3488     {
3489         CAmount nFeePerK = 0;
3490         if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK))
3491             return InitError(AmountErrMsg("paytxfee", mapArgs["-paytxfee"]));
3492         if (nFeePerK > HIGH_TX_FEE_PER_KB)
3493             InitWarning(_("-paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
3494         payTxFee = CFeeRate(nFeePerK, 1000);
3495         if (payTxFee < ::minRelayTxFee)
3496         {
3497             return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
3498                                        mapArgs["-paytxfee"], ::minRelayTxFee.ToString()));
3499         }
3500     }
3501     if (mapArgs.count("-maxtxfee"))
3502     {
3503         CAmount nMaxFee = 0;
3504         if (!ParseMoney(mapArgs["-maxtxfee"], nMaxFee))
3505             return InitError(AmountErrMsg("maxtxfee", mapArgs["-maxtxfee"]));
3506         if (nMaxFee > HIGH_MAX_TX_FEE)
3507             InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
3508         maxTxFee = nMaxFee;
3509         if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
3510         {
3511             return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
3512                                        mapArgs["-maxtxfee"], ::minRelayTxFee.ToString()));
3513         }
3514     }
3515     nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
3516     bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
3517     fSendFreeTransactions = GetBoolArg("-sendfreetransactions", DEFAULT_SEND_FREE_TRANSACTIONS);
3518 
3519     return true;
3520 }
3521 
BackupWallet(const std::string & strDest)3522 bool CWallet::BackupWallet(const std::string& strDest)
3523 {
3524     if (!fFileBacked)
3525         return false;
3526     while (true)
3527     {
3528         {
3529             LOCK(bitdb.cs_db);
3530             if (!bitdb.mapFileUseCount.count(strWalletFile) || bitdb.mapFileUseCount[strWalletFile] == 0)
3531             {
3532                 // Flush log data to the dat file
3533                 bitdb.CloseDb(strWalletFile);
3534                 bitdb.CheckpointLSN(strWalletFile);
3535                 bitdb.mapFileUseCount.erase(strWalletFile);
3536 
3537                 // Copy wallet file
3538                 boost::filesystem::path pathSrc = GetDataDir() / strWalletFile;
3539                 boost::filesystem::path pathDest(strDest);
3540                 if (boost::filesystem::is_directory(pathDest))
3541                     pathDest /= strWalletFile;
3542 
3543                 try {
3544 #if BOOST_VERSION >= 104000
3545                     boost::filesystem::copy_file(pathSrc, pathDest, boost::filesystem::copy_option::overwrite_if_exists);
3546 #else
3547                     boost::filesystem::copy_file(pathSrc, pathDest);
3548 #endif
3549                     LogPrintf("copied %s to %s\n", strWalletFile, pathDest.string());
3550                     return true;
3551                 } catch (const boost::filesystem::filesystem_error& e) {
3552                     LogPrintf("error copying %s to %s - %s\n", strWalletFile, pathDest.string(), e.what());
3553                     return false;
3554                 }
3555             }
3556         }
3557         MilliSleep(100);
3558     }
3559     return false;
3560 }
3561 
CKeyPool()3562 CKeyPool::CKeyPool()
3563 {
3564     nTime = GetTime();
3565 }
3566 
CKeyPool(const CPubKey & vchPubKeyIn)3567 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
3568 {
3569     nTime = GetTime();
3570     vchPubKey = vchPubKeyIn;
3571 }
3572 
CWalletKey(int64_t nExpires)3573 CWalletKey::CWalletKey(int64_t nExpires)
3574 {
3575     nTimeCreated = (nExpires ? GetTime() : 0);
3576     nTimeExpires = nExpires;
3577 }
3578 
SetMerkleBranch(const CBlock & block)3579 int CMerkleTx::SetMerkleBranch(const CBlock& block)
3580 {
3581     AssertLockHeld(cs_main);
3582     CBlock blockTmp;
3583 
3584     // Update the tx's hashBlock
3585     hashBlock = block.GetHash();
3586 
3587     // Locate the transaction
3588     for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
3589         if (block.vtx[nIndex] == *(CTransaction*)this)
3590             break;
3591     if (nIndex == (int)block.vtx.size())
3592     {
3593         nIndex = -1;
3594         LogPrintf("ERROR: SetMerkleBranch(): couldn't find tx in block\n");
3595         return 0;
3596     }
3597 
3598     // Is the tx in a block that's in the main chain
3599     BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
3600     if (mi == mapBlockIndex.end())
3601         return 0;
3602     const CBlockIndex* pindex = (*mi).second;
3603     if (!pindex || !chainActive.Contains(pindex))
3604         return 0;
3605 
3606     return chainActive.Height() - pindex->nHeight + 1;
3607 }
3608 
GetDepthInMainChain(const CBlockIndex * & pindexRet) const3609 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
3610 {
3611     if (hashUnset())
3612         return 0;
3613 
3614     AssertLockHeld(cs_main);
3615 
3616     // Find the block it claims to be in
3617     BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
3618     if (mi == mapBlockIndex.end())
3619         return 0;
3620     CBlockIndex* pindex = (*mi).second;
3621     if (!pindex || !chainActive.Contains(pindex))
3622         return 0;
3623 
3624     pindexRet = pindex;
3625     return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
3626 }
3627 
GetBlocksToMaturity() const3628 int CMerkleTx::GetBlocksToMaturity() const
3629 {
3630     if (!IsCoinBase())
3631         return 0;
3632     return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
3633 }
3634 
3635 
AcceptToMemoryPool(bool fLimitFree,CAmount nAbsurdFee,CValidationState & state)3636 bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, CAmount nAbsurdFee, CValidationState& state)
3637 {
3638     return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, false, nAbsurdFee);
3639 }
3640