Move CTxInWitness inside CTxIn
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blob2ef4802a1084e2d4d8e4a81108e76dac6466bbce
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.
6 #include "wallet/wallet.h"
8 #include "base58.h"
9 #include "checkpoints.h"
10 #include "chain.h"
11 #include "wallet/coincontrol.h"
12 #include "consensus/consensus.h"
13 #include "consensus/validation.h"
14 #include "key.h"
15 #include "keystore.h"
16 #include "validation.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"
29 #include <assert.h>
31 #include <boost/algorithm/string/replace.hpp>
32 #include <boost/filesystem.hpp>
33 #include <boost/thread.hpp>
35 using namespace std;
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 bool fWalletRbf = DEFAULT_WALLET_RBF;
45 const char * DEFAULT_WALLET_DAT = "wallet.dat";
46 const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
48 /**
49 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
50 * Override with -mintxfee
52 CFeeRate CWallet::minTxFee = CFeeRate(DEFAULT_TRANSACTION_MINFEE);
53 /**
54 * If fee estimation does not have enough data to provide estimates, use this fee instead.
55 * Has no effect if not using fee estimation
56 * Override with -fallbackfee
58 CFeeRate CWallet::fallbackFee = CFeeRate(DEFAULT_FALLBACK_FEE);
60 const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
62 /** @defgroup mapWallet
64 * @{
67 struct CompareValueOnly
69 bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1,
70 const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const
72 return t1.first < t2.first;
76 std::string COutput::ToString() const
78 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
81 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
83 LOCK(cs_wallet);
84 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
85 if (it == mapWallet.end())
86 return NULL;
87 return &(it->second);
90 CPubKey CWallet::GenerateNewKey()
92 AssertLockHeld(cs_wallet); // mapKeyMetadata
93 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
95 CKey secret;
97 // Create new metadata
98 int64_t nCreationTime = GetTime();
99 CKeyMetadata metadata(nCreationTime);
101 // use HD key derivation if HD was enabled during wallet creation
102 if (IsHDEnabled()) {
103 DeriveNewChildKey(metadata, secret);
104 } else {
105 secret.MakeNewKey(fCompressed);
108 // Compressed public keys were introduced in version 0.6.0
109 if (fCompressed)
110 SetMinVersion(FEATURE_COMPRPUBKEY);
112 CPubKey pubkey = secret.GetPubKey();
113 assert(secret.VerifyPubKey(pubkey));
115 mapKeyMetadata[pubkey.GetID()] = metadata;
116 if (!nTimeFirstKey || nCreationTime < nTimeFirstKey)
117 nTimeFirstKey = nCreationTime;
119 if (!AddKeyPubKey(secret, pubkey))
120 throw std::runtime_error(std::string(__func__) + ": AddKey failed");
121 return pubkey;
124 void CWallet::DeriveNewChildKey(CKeyMetadata& metadata, CKey& secret)
126 // for now we use a fixed keypath scheme of m/0'/0'/k
127 CKey key; //master key seed (256bit)
128 CExtKey masterKey; //hd master key
129 CExtKey accountKey; //key at m/0'
130 CExtKey externalChainChildKey; //key at m/0'/0'
131 CExtKey childKey; //key at m/0'/0'/<n>'
133 // try to get the master key
134 if (!GetKey(hdChain.masterKeyID, key))
135 throw std::runtime_error(std::string(__func__) + ": Master key not found");
137 masterKey.SetMaster(key.begin(), key.size());
139 // derive m/0'
140 // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
141 masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
143 // derive m/0'/0'
144 accountKey.Derive(externalChainChildKey, BIP32_HARDENED_KEY_LIMIT);
146 // derive child key at next index, skip keys already known to the wallet
147 do {
148 // always derive hardened keys
149 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
150 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
151 externalChainChildKey.Derive(childKey, hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
152 metadata.hdKeypath = "m/0'/0'/" + std::to_string(hdChain.nExternalChainCounter) + "'";
153 metadata.hdMasterKeyID = hdChain.masterKeyID;
154 // increment childkey index
155 hdChain.nExternalChainCounter++;
156 } while (HaveKey(childKey.key.GetPubKey().GetID()));
157 secret = childKey.key;
159 // update the chain model in the database
160 if (!CWalletDB(strWalletFile).WriteHDChain(hdChain))
161 throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
164 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
166 AssertLockHeld(cs_wallet); // mapKeyMetadata
167 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
168 return false;
170 // check if we need to remove from watch-only
171 CScript script;
172 script = GetScriptForDestination(pubkey.GetID());
173 if (HaveWatchOnly(script))
174 RemoveWatchOnly(script);
175 script = GetScriptForRawPubKey(pubkey);
176 if (HaveWatchOnly(script))
177 RemoveWatchOnly(script);
179 if (!fFileBacked)
180 return true;
181 if (!IsCrypted()) {
182 return CWalletDB(strWalletFile).WriteKey(pubkey,
183 secret.GetPrivKey(),
184 mapKeyMetadata[pubkey.GetID()]);
186 return true;
189 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
190 const vector<unsigned char> &vchCryptedSecret)
192 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
193 return false;
194 if (!fFileBacked)
195 return true;
197 LOCK(cs_wallet);
198 if (pwalletdbEncryption)
199 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
200 vchCryptedSecret,
201 mapKeyMetadata[vchPubKey.GetID()]);
202 else
203 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
204 vchCryptedSecret,
205 mapKeyMetadata[vchPubKey.GetID()]);
207 return false;
210 bool CWallet::LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &meta)
212 AssertLockHeld(cs_wallet); // mapKeyMetadata
213 if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey))
214 nTimeFirstKey = meta.nCreateTime;
216 mapKeyMetadata[pubkey.GetID()] = meta;
217 return true;
220 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
222 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
225 bool CWallet::AddCScript(const CScript& redeemScript)
227 if (!CCryptoKeyStore::AddCScript(redeemScript))
228 return false;
229 if (!fFileBacked)
230 return true;
231 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
234 bool CWallet::LoadCScript(const CScript& redeemScript)
236 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
237 * that never can be redeemed. However, old wallets may still contain
238 * these. Do not add them to the wallet and warn. */
239 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
241 std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
242 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",
243 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
244 return true;
247 return CCryptoKeyStore::AddCScript(redeemScript);
250 bool CWallet::AddWatchOnly(const CScript &dest)
252 if (!CCryptoKeyStore::AddWatchOnly(dest))
253 return false;
254 nTimeFirstKey = 1; // No birthday information for watch-only keys.
255 NotifyWatchonlyChanged(true);
256 if (!fFileBacked)
257 return true;
258 return CWalletDB(strWalletFile).WriteWatchOnly(dest);
261 bool CWallet::RemoveWatchOnly(const CScript &dest)
263 AssertLockHeld(cs_wallet);
264 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
265 return false;
266 if (!HaveWatchOnly())
267 NotifyWatchonlyChanged(false);
268 if (fFileBacked)
269 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
270 return false;
272 return true;
275 bool CWallet::LoadWatchOnly(const CScript &dest)
277 return CCryptoKeyStore::AddWatchOnly(dest);
280 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
282 CCrypter crypter;
283 CKeyingMaterial vMasterKey;
286 LOCK(cs_wallet);
287 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
289 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
290 return false;
291 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
292 continue; // try another master key
293 if (CCryptoKeyStore::Unlock(vMasterKey))
294 return true;
297 return false;
300 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
302 bool fWasLocked = IsLocked();
305 LOCK(cs_wallet);
306 Lock();
308 CCrypter crypter;
309 CKeyingMaterial vMasterKey;
310 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
312 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
313 return false;
314 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey))
315 return false;
316 if (CCryptoKeyStore::Unlock(vMasterKey))
318 int64_t nStartTime = GetTimeMillis();
319 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
320 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
322 nStartTime = GetTimeMillis();
323 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
324 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
326 if (pMasterKey.second.nDeriveIterations < 25000)
327 pMasterKey.second.nDeriveIterations = 25000;
329 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
331 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
332 return false;
333 if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey))
334 return false;
335 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
336 if (fWasLocked)
337 Lock();
338 return true;
343 return false;
346 void CWallet::SetBestChain(const CBlockLocator& loc)
348 CWalletDB walletdb(strWalletFile);
349 walletdb.WriteBestBlock(loc);
352 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
354 LOCK(cs_wallet); // nWalletVersion
355 if (nWalletVersion >= nVersion)
356 return true;
358 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
359 if (fExplicit && nVersion > nWalletMaxVersion)
360 nVersion = FEATURE_LATEST;
362 nWalletVersion = nVersion;
364 if (nVersion > nWalletMaxVersion)
365 nWalletMaxVersion = nVersion;
367 if (fFileBacked)
369 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
370 if (nWalletVersion > 40000)
371 pwalletdb->WriteMinVersion(nWalletVersion);
372 if (!pwalletdbIn)
373 delete pwalletdb;
376 return true;
379 bool CWallet::SetMaxVersion(int nVersion)
381 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
382 // cannot downgrade below current version
383 if (nWalletVersion > nVersion)
384 return false;
386 nWalletMaxVersion = nVersion;
388 return true;
391 set<uint256> CWallet::GetConflicts(const uint256& txid) const
393 set<uint256> result;
394 AssertLockHeld(cs_wallet);
396 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
397 if (it == mapWallet.end())
398 return result;
399 const CWalletTx& wtx = it->second;
401 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
403 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
405 if (mapTxSpends.count(txin.prevout) <= 1)
406 continue; // No conflict if zero or one spends
407 range = mapTxSpends.equal_range(txin.prevout);
408 for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
409 result.insert(_it->second);
411 return result;
414 void CWallet::Flush(bool shutdown)
416 bitdb.Flush(shutdown);
419 bool CWallet::Verify()
421 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
422 return true;
424 LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
425 std::string walletFile = GetArg("-wallet", DEFAULT_WALLET_DAT);
427 LogPrintf("Using wallet %s\n", walletFile);
428 uiInterface.InitMessage(_("Verifying wallet..."));
430 // Wallet file must be a plain filename without a directory
431 if (walletFile != boost::filesystem::basename(walletFile) + boost::filesystem::extension(walletFile))
432 return InitError(strprintf(_("Wallet %s resides outside data directory %s"), walletFile, GetDataDir().string()));
434 if (!bitdb.Open(GetDataDir()))
436 // try moving the database env out of the way
437 boost::filesystem::path pathDatabase = GetDataDir() / "database";
438 boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
439 try {
440 boost::filesystem::rename(pathDatabase, pathDatabaseBak);
441 LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
442 } catch (const boost::filesystem::filesystem_error&) {
443 // failure is ok (well, not really, but it's not worse than what we started with)
446 // try again
447 if (!bitdb.Open(GetDataDir())) {
448 // if it still fails, it probably means we can't even create the database env
449 return InitError(strprintf(_("Error initializing wallet database environment %s!"), GetDataDir()));
453 if (GetBoolArg("-salvagewallet", false))
455 // Recover readable keypairs:
456 if (!CWalletDB::Recover(bitdb, walletFile, true))
457 return false;
460 if (boost::filesystem::exists(GetDataDir() / walletFile))
462 CDBEnv::VerifyResult r = bitdb.Verify(walletFile, CWalletDB::Recover);
463 if (r == CDBEnv::RECOVER_OK)
465 InitWarning(strprintf(_("Warning: Wallet file corrupt, data salvaged!"
466 " Original %s saved as %s in %s; if"
467 " your balance or transactions are incorrect you should"
468 " restore from a backup."),
469 walletFile, "wallet.{timestamp}.bak", GetDataDir()));
471 if (r == CDBEnv::RECOVER_FAIL)
472 return InitError(strprintf(_("%s corrupt, salvage failed"), walletFile));
475 return true;
478 void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range)
480 // We want all the wallet transactions in range to have the same metadata as
481 // the oldest (smallest nOrderPos).
482 // So: find smallest nOrderPos:
484 int nMinOrderPos = std::numeric_limits<int>::max();
485 const CWalletTx* copyFrom = NULL;
486 for (TxSpends::iterator it = range.first; it != range.second; ++it)
488 const uint256& hash = it->second;
489 int n = mapWallet[hash].nOrderPos;
490 if (n < nMinOrderPos)
492 nMinOrderPos = n;
493 copyFrom = &mapWallet[hash];
496 // Now copy data from copyFrom to rest:
497 for (TxSpends::iterator it = range.first; it != range.second; ++it)
499 const uint256& hash = it->second;
500 CWalletTx* copyTo = &mapWallet[hash];
501 if (copyFrom == copyTo) continue;
502 if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
503 copyTo->mapValue = copyFrom->mapValue;
504 copyTo->vOrderForm = copyFrom->vOrderForm;
505 // fTimeReceivedIsTxTime not copied on purpose
506 // nTimeReceived not copied on purpose
507 copyTo->nTimeSmart = copyFrom->nTimeSmart;
508 copyTo->fFromMe = copyFrom->fFromMe;
509 copyTo->strFromAccount = copyFrom->strFromAccount;
510 // nOrderPos not copied on purpose
511 // cached members not copied on purpose
516 * Outpoint is spent if any non-conflicted transaction
517 * spends it:
519 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
521 const COutPoint outpoint(hash, n);
522 pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
523 range = mapTxSpends.equal_range(outpoint);
525 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
527 const uint256& wtxid = it->second;
528 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
529 if (mit != mapWallet.end()) {
530 int depth = mit->second.GetDepthInMainChain();
531 if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
532 return true; // Spent
535 return false;
538 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
540 mapTxSpends.insert(make_pair(outpoint, wtxid));
542 pair<TxSpends::iterator, TxSpends::iterator> range;
543 range = mapTxSpends.equal_range(outpoint);
544 SyncMetaData(range);
548 void CWallet::AddToSpends(const uint256& wtxid)
550 assert(mapWallet.count(wtxid));
551 CWalletTx& thisTx = mapWallet[wtxid];
552 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
553 return;
555 BOOST_FOREACH(const CTxIn& txin, thisTx.tx->vin)
556 AddToSpends(txin.prevout, wtxid);
559 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
561 if (IsCrypted())
562 return false;
564 CKeyingMaterial vMasterKey;
566 vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
567 GetStrongRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
569 CMasterKey kMasterKey;
571 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
572 GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
574 CCrypter crypter;
575 int64_t nStartTime = GetTimeMillis();
576 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
577 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
579 nStartTime = GetTimeMillis();
580 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
581 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
583 if (kMasterKey.nDeriveIterations < 25000)
584 kMasterKey.nDeriveIterations = 25000;
586 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
588 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
589 return false;
590 if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey))
591 return false;
594 LOCK(cs_wallet);
595 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
596 if (fFileBacked)
598 assert(!pwalletdbEncryption);
599 pwalletdbEncryption = new CWalletDB(strWalletFile);
600 if (!pwalletdbEncryption->TxnBegin()) {
601 delete pwalletdbEncryption;
602 pwalletdbEncryption = NULL;
603 return false;
605 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
608 if (!EncryptKeys(vMasterKey))
610 if (fFileBacked) {
611 pwalletdbEncryption->TxnAbort();
612 delete pwalletdbEncryption;
614 // We now probably have half of our keys encrypted in memory, and half not...
615 // die and let the user reload the unencrypted wallet.
616 assert(false);
619 // Encryption was introduced in version 0.4.0
620 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
622 if (fFileBacked)
624 if (!pwalletdbEncryption->TxnCommit()) {
625 delete pwalletdbEncryption;
626 // We now have keys encrypted in memory, but not on disk...
627 // die to avoid confusion and let the user reload the unencrypted wallet.
628 assert(false);
631 delete pwalletdbEncryption;
632 pwalletdbEncryption = NULL;
635 Lock();
636 Unlock(strWalletPassphrase);
638 // if we are using HD, replace the HD master key (seed) with a new one
639 if (IsHDEnabled()) {
640 CKey key;
641 CPubKey masterPubKey = GenerateNewHDMasterKey();
642 if (!SetHDMasterKey(masterPubKey))
643 return false;
646 NewKeyPool();
647 Lock();
649 // Need to completely rewrite the wallet file; if we don't, bdb might keep
650 // bits of the unencrypted private key in slack space in the database file.
651 CDB::Rewrite(strWalletFile);
654 NotifyStatusChanged(this);
656 return true;
659 DBErrors CWallet::ReorderTransactions()
661 LOCK(cs_wallet);
662 CWalletDB walletdb(strWalletFile);
664 // Old wallets didn't have any defined order for transactions
665 // Probably a bad idea to change the output of this
667 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
668 typedef pair<CWalletTx*, CAccountingEntry*> TxPair;
669 typedef multimap<int64_t, TxPair > TxItems;
670 TxItems txByTime;
672 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
674 CWalletTx* wtx = &((*it).second);
675 txByTime.insert(make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
677 list<CAccountingEntry> acentries;
678 walletdb.ListAccountCreditDebit("", acentries);
679 BOOST_FOREACH(CAccountingEntry& entry, acentries)
681 txByTime.insert(make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
684 nOrderPosNext = 0;
685 std::vector<int64_t> nOrderPosOffsets;
686 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
688 CWalletTx *const pwtx = (*it).second.first;
689 CAccountingEntry *const pacentry = (*it).second.second;
690 int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
692 if (nOrderPos == -1)
694 nOrderPos = nOrderPosNext++;
695 nOrderPosOffsets.push_back(nOrderPos);
697 if (pwtx)
699 if (!walletdb.WriteTx(*pwtx))
700 return DB_LOAD_FAIL;
702 else
703 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
704 return DB_LOAD_FAIL;
706 else
708 int64_t nOrderPosOff = 0;
709 BOOST_FOREACH(const int64_t& nOffsetStart, nOrderPosOffsets)
711 if (nOrderPos >= nOffsetStart)
712 ++nOrderPosOff;
714 nOrderPos += nOrderPosOff;
715 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
717 if (!nOrderPosOff)
718 continue;
720 // Since we're changing the order, write it back
721 if (pwtx)
723 if (!walletdb.WriteTx(*pwtx))
724 return DB_LOAD_FAIL;
726 else
727 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
728 return DB_LOAD_FAIL;
731 walletdb.WriteOrderPosNext(nOrderPosNext);
733 return DB_LOAD_OK;
736 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
738 AssertLockHeld(cs_wallet); // nOrderPosNext
739 int64_t nRet = nOrderPosNext++;
740 if (pwalletdb) {
741 pwalletdb->WriteOrderPosNext(nOrderPosNext);
742 } else {
743 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
745 return nRet;
748 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
750 CWalletDB walletdb(strWalletFile);
751 if (!walletdb.TxnBegin())
752 return false;
754 int64_t nNow = GetAdjustedTime();
756 // Debit
757 CAccountingEntry debit;
758 debit.nOrderPos = IncOrderPosNext(&walletdb);
759 debit.strAccount = strFrom;
760 debit.nCreditDebit = -nAmount;
761 debit.nTime = nNow;
762 debit.strOtherAccount = strTo;
763 debit.strComment = strComment;
764 AddAccountingEntry(debit, &walletdb);
766 // Credit
767 CAccountingEntry credit;
768 credit.nOrderPos = IncOrderPosNext(&walletdb);
769 credit.strAccount = strTo;
770 credit.nCreditDebit = nAmount;
771 credit.nTime = nNow;
772 credit.strOtherAccount = strFrom;
773 credit.strComment = strComment;
774 AddAccountingEntry(credit, &walletdb);
776 if (!walletdb.TxnCommit())
777 return false;
779 return true;
782 bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
784 CWalletDB walletdb(strWalletFile);
786 CAccount account;
787 walletdb.ReadAccount(strAccount, account);
789 if (!bForceNew) {
790 if (!account.vchPubKey.IsValid())
791 bForceNew = true;
792 else {
793 // Check if the current key has been used
794 CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
795 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin();
796 it != mapWallet.end() && account.vchPubKey.IsValid();
797 ++it)
798 BOOST_FOREACH(const CTxOut& txout, (*it).second.tx->vout)
799 if (txout.scriptPubKey == scriptPubKey) {
800 bForceNew = true;
801 break;
806 // Generate a new key
807 if (bForceNew) {
808 if (!GetKeyFromPool(account.vchPubKey))
809 return false;
811 SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
812 walletdb.WriteAccount(strAccount, account);
815 pubKey = account.vchPubKey;
817 return true;
820 void CWallet::MarkDirty()
823 LOCK(cs_wallet);
824 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
825 item.second.MarkDirty();
829 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
831 LOCK(cs_wallet);
833 CWalletDB walletdb(strWalletFile, "r+", fFlushOnClose);
835 uint256 hash = wtxIn.GetHash();
837 // Inserts only if not already there, returns tx inserted or tx found
838 pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn));
839 CWalletTx& wtx = (*ret.first).second;
840 wtx.BindWallet(this);
841 bool fInsertedNew = ret.second;
842 if (fInsertedNew)
844 wtx.nTimeReceived = GetAdjustedTime();
845 wtx.nOrderPos = IncOrderPosNext(&walletdb);
846 wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
848 wtx.nTimeSmart = wtx.nTimeReceived;
849 if (!wtxIn.hashUnset())
851 if (mapBlockIndex.count(wtxIn.hashBlock))
853 int64_t latestNow = wtx.nTimeReceived;
854 int64_t latestEntry = 0;
856 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
857 int64_t latestTolerated = latestNow + 300;
858 const TxItems & txOrdered = wtxOrdered;
859 for (TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
861 CWalletTx *const pwtx = (*it).second.first;
862 if (pwtx == &wtx)
863 continue;
864 CAccountingEntry *const pacentry = (*it).second.second;
865 int64_t nSmartTime;
866 if (pwtx)
868 nSmartTime = pwtx->nTimeSmart;
869 if (!nSmartTime)
870 nSmartTime = pwtx->nTimeReceived;
872 else
873 nSmartTime = pacentry->nTime;
874 if (nSmartTime <= latestTolerated)
876 latestEntry = nSmartTime;
877 if (nSmartTime > latestNow)
878 latestNow = nSmartTime;
879 break;
884 int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime();
885 wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
887 else
888 LogPrintf("AddToWallet(): found %s in block %s not in index\n",
889 wtxIn.GetHash().ToString(),
890 wtxIn.hashBlock.ToString());
892 AddToSpends(hash);
895 bool fUpdated = false;
896 if (!fInsertedNew)
898 // Merge
899 if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
901 wtx.hashBlock = wtxIn.hashBlock;
902 fUpdated = true;
904 // If no longer abandoned, update
905 if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
907 wtx.hashBlock = wtxIn.hashBlock;
908 fUpdated = true;
910 if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
912 wtx.nIndex = wtxIn.nIndex;
913 fUpdated = true;
915 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
917 wtx.fFromMe = wtxIn.fFromMe;
918 fUpdated = true;
922 //// debug print
923 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
925 // Write to disk
926 if (fInsertedNew || fUpdated)
927 if (!walletdb.WriteTx(wtx))
928 return false;
930 // Break debit/credit balance caches:
931 wtx.MarkDirty();
933 // Notify UI of new or updated transaction
934 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
936 // notify an external script when a wallet transaction comes in or is updated
937 std::string strCmd = GetArg("-walletnotify", "");
939 if ( !strCmd.empty())
941 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
942 boost::thread t(runCommand, strCmd); // thread runs free
945 return true;
948 bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
950 uint256 hash = wtxIn.GetHash();
952 mapWallet[hash] = wtxIn;
953 CWalletTx& wtx = mapWallet[hash];
954 wtx.BindWallet(this);
955 wtxOrdered.insert(make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
956 AddToSpends(hash);
957 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin) {
958 if (mapWallet.count(txin.prevout.hash)) {
959 CWalletTx& prevtx = mapWallet[txin.prevout.hash];
960 if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
961 MarkConflicted(prevtx.hashBlock, wtx.GetHash());
966 return true;
970 * Add a transaction to the wallet, or update it.
971 * pblock is optional, but should be provided if the transaction is known to be in a block.
972 * If fUpdate is true, existing transactions will be updated.
974 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
977 AssertLockHeld(cs_wallet);
979 if (posInBlock != -1) {
980 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
981 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
982 while (range.first != range.second) {
983 if (range.first->second != tx.GetHash()) {
984 LogPrintf("Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.GetHash().ToString(), pIndex->GetBlockHash().ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
985 MarkConflicted(pIndex->GetBlockHash(), range.first->second);
987 range.first++;
992 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
993 if (fExisted && !fUpdate) return false;
994 if (fExisted || IsMine(tx) || IsFromMe(tx))
996 CWalletTx wtx(this, MakeTransactionRef(tx));
998 // Get merkle branch if transaction was found in a block
999 if (posInBlock != -1)
1000 wtx.SetMerkleBranch(pIndex, posInBlock);
1002 return AddToWallet(wtx, false);
1005 return false;
1008 bool CWallet::AbandonTransaction(const uint256& hashTx)
1010 LOCK2(cs_main, cs_wallet);
1012 // Do not flush the wallet here for performance reasons
1013 CWalletDB walletdb(strWalletFile, "r+", false);
1015 std::set<uint256> todo;
1016 std::set<uint256> done;
1018 // Can't mark abandoned if confirmed or in mempool
1019 assert(mapWallet.count(hashTx));
1020 CWalletTx& origtx = mapWallet[hashTx];
1021 if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
1022 return false;
1025 todo.insert(hashTx);
1027 while (!todo.empty()) {
1028 uint256 now = *todo.begin();
1029 todo.erase(now);
1030 done.insert(now);
1031 assert(mapWallet.count(now));
1032 CWalletTx& wtx = mapWallet[now];
1033 int currentconfirm = wtx.GetDepthInMainChain();
1034 // If the orig tx was not in block, none of its spends can be
1035 assert(currentconfirm <= 0);
1036 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1037 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1038 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1039 assert(!wtx.InMempool());
1040 wtx.nIndex = -1;
1041 wtx.setAbandoned();
1042 wtx.MarkDirty();
1043 walletdb.WriteTx(wtx);
1044 NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1045 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1046 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1047 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1048 if (!done.count(iter->second)) {
1049 todo.insert(iter->second);
1051 iter++;
1053 // If a transaction changes 'conflicted' state, that changes the balance
1054 // available of the outputs it spends. So force those to be recomputed
1055 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
1057 if (mapWallet.count(txin.prevout.hash))
1058 mapWallet[txin.prevout.hash].MarkDirty();
1063 return true;
1066 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1068 LOCK2(cs_main, cs_wallet);
1070 int conflictconfirms = 0;
1071 if (mapBlockIndex.count(hashBlock)) {
1072 CBlockIndex* pindex = mapBlockIndex[hashBlock];
1073 if (chainActive.Contains(pindex)) {
1074 conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1077 // If number of conflict confirms cannot be determined, this means
1078 // that the block is still unknown or not yet part of the main chain,
1079 // for example when loading the wallet during a reindex. Do nothing in that
1080 // case.
1081 if (conflictconfirms >= 0)
1082 return;
1084 // Do not flush the wallet here for performance reasons
1085 CWalletDB walletdb(strWalletFile, "r+", false);
1087 std::set<uint256> todo;
1088 std::set<uint256> done;
1090 todo.insert(hashTx);
1092 while (!todo.empty()) {
1093 uint256 now = *todo.begin();
1094 todo.erase(now);
1095 done.insert(now);
1096 assert(mapWallet.count(now));
1097 CWalletTx& wtx = mapWallet[now];
1098 int currentconfirm = wtx.GetDepthInMainChain();
1099 if (conflictconfirms < currentconfirm) {
1100 // Block is 'more conflicted' than current confirm; update.
1101 // Mark transaction as conflicted with this block.
1102 wtx.nIndex = -1;
1103 wtx.hashBlock = hashBlock;
1104 wtx.MarkDirty();
1105 walletdb.WriteTx(wtx);
1106 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1107 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1108 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1109 if (!done.count(iter->second)) {
1110 todo.insert(iter->second);
1112 iter++;
1114 // If a transaction changes 'conflicted' state, that changes the balance
1115 // available of the outputs it spends. So force those to be recomputed
1116 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
1118 if (mapWallet.count(txin.prevout.hash))
1119 mapWallet[txin.prevout.hash].MarkDirty();
1125 void CWallet::SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, int posInBlock)
1127 LOCK2(cs_main, cs_wallet);
1129 if (!AddToWalletIfInvolvingMe(tx, pindex, posInBlock, true))
1130 return; // Not one of ours
1132 // If a transaction changes 'conflicted' state, that changes the balance
1133 // available of the outputs it spends. So force those to be
1134 // recomputed, also:
1135 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1137 if (mapWallet.count(txin.prevout.hash))
1138 mapWallet[txin.prevout.hash].MarkDirty();
1143 isminetype CWallet::IsMine(const CTxIn &txin) const
1146 LOCK(cs_wallet);
1147 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1148 if (mi != mapWallet.end())
1150 const CWalletTx& prev = (*mi).second;
1151 if (txin.prevout.n < prev.tx->vout.size())
1152 return IsMine(prev.tx->vout[txin.prevout.n]);
1155 return ISMINE_NO;
1158 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1161 LOCK(cs_wallet);
1162 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1163 if (mi != mapWallet.end())
1165 const CWalletTx& prev = (*mi).second;
1166 if (txin.prevout.n < prev.tx->vout.size())
1167 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1168 return prev.tx->vout[txin.prevout.n].nValue;
1171 return 0;
1174 isminetype CWallet::IsMine(const CTxOut& txout) const
1176 return ::IsMine(*this, txout.scriptPubKey);
1179 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1181 if (!MoneyRange(txout.nValue))
1182 throw std::runtime_error(std::string(__func__) + ": value out of range");
1183 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1186 bool CWallet::IsChange(const CTxOut& txout) const
1188 // TODO: fix handling of 'change' outputs. The assumption is that any
1189 // payment to a script that is ours, but is not in the address book
1190 // is change. That assumption is likely to break when we implement multisignature
1191 // wallets that return change back into a multi-signature-protected address;
1192 // a better way of identifying which outputs are 'the send' and which are
1193 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1194 // which output, if any, was change).
1195 if (::IsMine(*this, txout.scriptPubKey))
1197 CTxDestination address;
1198 if (!ExtractDestination(txout.scriptPubKey, address))
1199 return true;
1201 LOCK(cs_wallet);
1202 if (!mapAddressBook.count(address))
1203 return true;
1205 return false;
1208 CAmount CWallet::GetChange(const CTxOut& txout) const
1210 if (!MoneyRange(txout.nValue))
1211 throw std::runtime_error(std::string(__func__) + ": value out of range");
1212 return (IsChange(txout) ? txout.nValue : 0);
1215 bool CWallet::IsMine(const CTransaction& tx) const
1217 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1218 if (IsMine(txout))
1219 return true;
1220 return false;
1223 bool CWallet::IsFromMe(const CTransaction& tx) const
1225 return (GetDebit(tx, ISMINE_ALL) > 0);
1228 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1230 CAmount nDebit = 0;
1231 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1233 nDebit += GetDebit(txin, filter);
1234 if (!MoneyRange(nDebit))
1235 throw std::runtime_error(std::string(__func__) + ": value out of range");
1237 return nDebit;
1240 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1242 CAmount nCredit = 0;
1243 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1245 nCredit += GetCredit(txout, filter);
1246 if (!MoneyRange(nCredit))
1247 throw std::runtime_error(std::string(__func__) + ": value out of range");
1249 return nCredit;
1252 CAmount CWallet::GetChange(const CTransaction& tx) const
1254 CAmount nChange = 0;
1255 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1257 nChange += GetChange(txout);
1258 if (!MoneyRange(nChange))
1259 throw std::runtime_error(std::string(__func__) + ": value out of range");
1261 return nChange;
1264 CPubKey CWallet::GenerateNewHDMasterKey()
1266 CKey key;
1267 key.MakeNewKey(true);
1269 int64_t nCreationTime = GetTime();
1270 CKeyMetadata metadata(nCreationTime);
1272 // calculate the pubkey
1273 CPubKey pubkey = key.GetPubKey();
1274 assert(key.VerifyPubKey(pubkey));
1276 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1277 metadata.hdKeypath = "m";
1278 metadata.hdMasterKeyID = pubkey.GetID();
1281 LOCK(cs_wallet);
1283 // mem store the metadata
1284 mapKeyMetadata[pubkey.GetID()] = metadata;
1286 // write the key&metadata to the database
1287 if (!AddKeyPubKey(key, pubkey))
1288 throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1291 return pubkey;
1294 bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
1296 LOCK(cs_wallet);
1298 // ensure this wallet.dat can only be opened by clients supporting HD
1299 SetMinVersion(FEATURE_HD);
1301 // store the keyid (hash160) together with
1302 // the child index counter in the database
1303 // as a hdchain object
1304 CHDChain newHdChain;
1305 newHdChain.masterKeyID = pubkey.GetID();
1306 SetHDChain(newHdChain, false);
1308 return true;
1311 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1313 LOCK(cs_wallet);
1314 if (!memonly && !CWalletDB(strWalletFile).WriteHDChain(chain))
1315 throw runtime_error(std::string(__func__) + ": writing chain failed");
1317 hdChain = chain;
1318 return true;
1321 bool CWallet::IsHDEnabled()
1323 return !hdChain.masterKeyID.IsNull();
1326 int64_t CWalletTx::GetTxTime() const
1328 int64_t n = nTimeSmart;
1329 return n ? n : nTimeReceived;
1332 int CWalletTx::GetRequestCount() const
1334 // Returns -1 if it wasn't being tracked
1335 int nRequests = -1;
1337 LOCK(pwallet->cs_wallet);
1338 if (IsCoinBase())
1340 // Generated block
1341 if (!hashUnset())
1343 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1344 if (mi != pwallet->mapRequestCount.end())
1345 nRequests = (*mi).second;
1348 else
1350 // Did anyone request this transaction?
1351 map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1352 if (mi != pwallet->mapRequestCount.end())
1354 nRequests = (*mi).second;
1356 // How about the block it's in?
1357 if (nRequests == 0 && !hashUnset())
1359 map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1360 if (_mi != pwallet->mapRequestCount.end())
1361 nRequests = (*_mi).second;
1362 else
1363 nRequests = 1; // If it's in someone else's block it must have got out
1368 return nRequests;
1371 void CWalletTx::GetAmounts(list<COutputEntry>& listReceived,
1372 list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const
1374 nFee = 0;
1375 listReceived.clear();
1376 listSent.clear();
1377 strSentAccount = strFromAccount;
1379 // Compute fee:
1380 CAmount nDebit = GetDebit(filter);
1381 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1383 CAmount nValueOut = tx->GetValueOut();
1384 nFee = nDebit - nValueOut;
1387 // Sent/received.
1388 for (unsigned int i = 0; i < tx->vout.size(); ++i)
1390 const CTxOut& txout = tx->vout[i];
1391 isminetype fIsMine = pwallet->IsMine(txout);
1392 // Only need to handle txouts if AT LEAST one of these is true:
1393 // 1) they debit from us (sent)
1394 // 2) the output is to us (received)
1395 if (nDebit > 0)
1397 // Don't report 'change' txouts
1398 if (pwallet->IsChange(txout))
1399 continue;
1401 else if (!(fIsMine & filter))
1402 continue;
1404 // In either case, we need to get the destination address
1405 CTxDestination address;
1407 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1409 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1410 this->GetHash().ToString());
1411 address = CNoDestination();
1414 COutputEntry output = {address, txout.nValue, (int)i};
1416 // If we are debited by the transaction, add the output as a "sent" entry
1417 if (nDebit > 0)
1418 listSent.push_back(output);
1420 // If we are receiving the output, add it as a "received" entry
1421 if (fIsMine & filter)
1422 listReceived.push_back(output);
1427 void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived,
1428 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
1430 nReceived = nSent = nFee = 0;
1432 CAmount allFee;
1433 string strSentAccount;
1434 list<COutputEntry> listReceived;
1435 list<COutputEntry> listSent;
1436 GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
1438 if (strAccount == strSentAccount)
1440 BOOST_FOREACH(const COutputEntry& s, listSent)
1441 nSent += s.amount;
1442 nFee = allFee;
1445 LOCK(pwallet->cs_wallet);
1446 BOOST_FOREACH(const COutputEntry& r, listReceived)
1448 if (pwallet->mapAddressBook.count(r.destination))
1450 map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
1451 if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
1452 nReceived += r.amount;
1454 else if (strAccount.empty())
1456 nReceived += r.amount;
1463 * Scan the block chain (starting in pindexStart) for transactions
1464 * from or to us. If fUpdate is true, found transactions that already
1465 * exist in the wallet will be updated.
1467 int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1469 int ret = 0;
1470 int64_t nNow = GetTime();
1471 const CChainParams& chainParams = Params();
1473 CBlockIndex* pindex = pindexStart;
1475 LOCK2(cs_main, cs_wallet);
1477 // no need to read and scan block, if block was created before
1478 // our wallet birthday (as adjusted for block time variability)
1479 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200)))
1480 pindex = chainActive.Next(pindex);
1482 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1483 double dProgressStart = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false);
1484 double dProgressTip = Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), chainActive.Tip(), false);
1485 while (pindex)
1487 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1488 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1490 CBlock block;
1491 ReadBlockFromDisk(block, pindex, Params().GetConsensus());
1492 int posInBlock;
1493 for (posInBlock = 0; posInBlock < (int)block.vtx.size(); posInBlock++)
1495 if (AddToWalletIfInvolvingMe(*block.vtx[posInBlock], pindex, posInBlock, fUpdate))
1496 ret++;
1498 pindex = chainActive.Next(pindex);
1499 if (GetTime() >= nNow + 60) {
1500 nNow = GetTime();
1501 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(chainParams.Checkpoints(), pindex));
1504 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1506 return ret;
1509 void CWallet::ReacceptWalletTransactions()
1511 // If transactions aren't being broadcasted, don't let them into local mempool either
1512 if (!fBroadcastTransactions)
1513 return;
1514 LOCK2(cs_main, cs_wallet);
1515 std::map<int64_t, CWalletTx*> mapSorted;
1517 // Sort pending wallet transactions based on their initial wallet insertion order
1518 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1520 const uint256& wtxid = item.first;
1521 CWalletTx& wtx = item.second;
1522 assert(wtx.GetHash() == wtxid);
1524 int nDepth = wtx.GetDepthInMainChain();
1526 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1527 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1531 // Try to add wallet transactions to memory pool
1532 BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
1534 CWalletTx& wtx = *(item.second);
1536 LOCK(mempool.cs);
1537 CValidationState state;
1538 wtx.AcceptToMemoryPool(maxTxFee, state);
1542 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1544 assert(pwallet->GetBroadcastTransactions());
1545 if (!IsCoinBase())
1547 if (GetDepthInMainChain() == 0 && !isAbandoned() && InMempool()) {
1548 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1549 if (connman) {
1550 CInv inv(MSG_TX, GetHash());
1551 connman->ForEachNode([&inv](CNode* pnode)
1553 pnode->PushInventory(inv);
1555 return true;
1559 return false;
1562 set<uint256> CWalletTx::GetConflicts() const
1564 set<uint256> result;
1565 if (pwallet != NULL)
1567 uint256 myHash = GetHash();
1568 result = pwallet->GetConflicts(myHash);
1569 result.erase(myHash);
1571 return result;
1574 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1576 if (tx->vin.empty())
1577 return 0;
1579 CAmount debit = 0;
1580 if(filter & ISMINE_SPENDABLE)
1582 if (fDebitCached)
1583 debit += nDebitCached;
1584 else
1586 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1587 fDebitCached = true;
1588 debit += nDebitCached;
1591 if(filter & ISMINE_WATCH_ONLY)
1593 if(fWatchDebitCached)
1594 debit += nWatchDebitCached;
1595 else
1597 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1598 fWatchDebitCached = true;
1599 debit += nWatchDebitCached;
1602 return debit;
1605 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1607 // Must wait until coinbase is safely deep enough in the chain before valuing it
1608 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1609 return 0;
1611 CAmount credit = 0;
1612 if (filter & ISMINE_SPENDABLE)
1614 // GetBalance can assume transactions in mapWallet won't change
1615 if (fCreditCached)
1616 credit += nCreditCached;
1617 else
1619 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1620 fCreditCached = true;
1621 credit += nCreditCached;
1624 if (filter & ISMINE_WATCH_ONLY)
1626 if (fWatchCreditCached)
1627 credit += nWatchCreditCached;
1628 else
1630 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1631 fWatchCreditCached = true;
1632 credit += nWatchCreditCached;
1635 return credit;
1638 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1640 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1642 if (fUseCache && fImmatureCreditCached)
1643 return nImmatureCreditCached;
1644 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1645 fImmatureCreditCached = true;
1646 return nImmatureCreditCached;
1649 return 0;
1652 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1654 if (pwallet == 0)
1655 return 0;
1657 // Must wait until coinbase is safely deep enough in the chain before valuing it
1658 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1659 return 0;
1661 if (fUseCache && fAvailableCreditCached)
1662 return nAvailableCreditCached;
1664 CAmount nCredit = 0;
1665 uint256 hashTx = GetHash();
1666 for (unsigned int i = 0; i < tx->vout.size(); i++)
1668 if (!pwallet->IsSpent(hashTx, i))
1670 const CTxOut &txout = tx->vout[i];
1671 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1672 if (!MoneyRange(nCredit))
1673 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1677 nAvailableCreditCached = nCredit;
1678 fAvailableCreditCached = true;
1679 return nCredit;
1682 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1684 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1686 if (fUseCache && fImmatureWatchCreditCached)
1687 return nImmatureWatchCreditCached;
1688 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1689 fImmatureWatchCreditCached = true;
1690 return nImmatureWatchCreditCached;
1693 return 0;
1696 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1698 if (pwallet == 0)
1699 return 0;
1701 // Must wait until coinbase is safely deep enough in the chain before valuing it
1702 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1703 return 0;
1705 if (fUseCache && fAvailableWatchCreditCached)
1706 return nAvailableWatchCreditCached;
1708 CAmount nCredit = 0;
1709 for (unsigned int i = 0; i < tx->vout.size(); i++)
1711 if (!pwallet->IsSpent(GetHash(), i))
1713 const CTxOut &txout = tx->vout[i];
1714 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1715 if (!MoneyRange(nCredit))
1716 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1720 nAvailableWatchCreditCached = nCredit;
1721 fAvailableWatchCreditCached = true;
1722 return nCredit;
1725 CAmount CWalletTx::GetChange() const
1727 if (fChangeCached)
1728 return nChangeCached;
1729 nChangeCached = pwallet->GetChange(*this);
1730 fChangeCached = true;
1731 return nChangeCached;
1734 bool CWalletTx::InMempool() const
1736 LOCK(mempool.cs);
1737 if (mempool.exists(GetHash())) {
1738 return true;
1740 return false;
1743 bool CWalletTx::IsTrusted() const
1745 // Quick answer in most cases
1746 if (!CheckFinalTx(*this))
1747 return false;
1748 int nDepth = GetDepthInMainChain();
1749 if (nDepth >= 1)
1750 return true;
1751 if (nDepth < 0)
1752 return false;
1753 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1754 return false;
1756 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1757 if (!InMempool())
1758 return false;
1760 // Trusted if all inputs are from us and are in the mempool:
1761 BOOST_FOREACH(const CTxIn& txin, tx->vin)
1763 // Transactions not sent by us: not trusted
1764 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1765 if (parent == NULL)
1766 return false;
1767 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1768 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1769 return false;
1771 return true;
1774 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1776 CMutableTransaction tx1 = *this->tx;
1777 CMutableTransaction tx2 = *_tx.tx;
1778 for (unsigned int i = 0; i < tx1.vin.size(); i++) tx1.vin[i].scriptSig = CScript();
1779 for (unsigned int i = 0; i < tx2.vin.size(); i++) tx2.vin[i].scriptSig = CScript();
1780 return CTransaction(tx1) == CTransaction(tx2);
1783 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1785 std::vector<uint256> result;
1787 LOCK(cs_wallet);
1788 // Sort them in chronological order
1789 multimap<unsigned int, CWalletTx*> mapSorted;
1790 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1792 CWalletTx& wtx = item.second;
1793 // Don't rebroadcast if newer than nTime:
1794 if (wtx.nTimeReceived > nTime)
1795 continue;
1796 mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx));
1798 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1800 CWalletTx& wtx = *item.second;
1801 if (wtx.RelayWalletTransaction(connman))
1802 result.push_back(wtx.GetHash());
1804 return result;
1807 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1809 // Do this infrequently and randomly to avoid giving away
1810 // that these are our transactions.
1811 if (GetTime() < nNextResend || !fBroadcastTransactions)
1812 return;
1813 bool fFirst = (nNextResend == 0);
1814 nNextResend = GetTime() + GetRand(30 * 60);
1815 if (fFirst)
1816 return;
1818 // Only do it if there's been a new block since last time
1819 if (nBestBlockTime < nLastResend)
1820 return;
1821 nLastResend = GetTime();
1823 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1824 // block was found:
1825 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
1826 if (!relayed.empty())
1827 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
1830 /** @} */ // end of mapWallet
1835 /** @defgroup Actions
1837 * @{
1841 CAmount CWallet::GetBalance() const
1843 CAmount nTotal = 0;
1845 LOCK2(cs_main, cs_wallet);
1846 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1848 const CWalletTx* pcoin = &(*it).second;
1849 if (pcoin->IsTrusted())
1850 nTotal += pcoin->GetAvailableCredit();
1854 return nTotal;
1857 CAmount CWallet::GetUnconfirmedBalance() const
1859 CAmount nTotal = 0;
1861 LOCK2(cs_main, cs_wallet);
1862 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1864 const CWalletTx* pcoin = &(*it).second;
1865 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1866 nTotal += pcoin->GetAvailableCredit();
1869 return nTotal;
1872 CAmount CWallet::GetImmatureBalance() const
1874 CAmount nTotal = 0;
1876 LOCK2(cs_main, cs_wallet);
1877 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1879 const CWalletTx* pcoin = &(*it).second;
1880 nTotal += pcoin->GetImmatureCredit();
1883 return nTotal;
1886 CAmount CWallet::GetWatchOnlyBalance() const
1888 CAmount nTotal = 0;
1890 LOCK2(cs_main, cs_wallet);
1891 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1893 const CWalletTx* pcoin = &(*it).second;
1894 if (pcoin->IsTrusted())
1895 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1899 return nTotal;
1902 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
1904 CAmount nTotal = 0;
1906 LOCK2(cs_main, cs_wallet);
1907 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1909 const CWalletTx* pcoin = &(*it).second;
1910 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1911 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1914 return nTotal;
1917 CAmount CWallet::GetImmatureWatchOnlyBalance() const
1919 CAmount nTotal = 0;
1921 LOCK2(cs_main, cs_wallet);
1922 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1924 const CWalletTx* pcoin = &(*it).second;
1925 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1928 return nTotal;
1931 void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, bool fIncludeZeroValue) const
1933 vCoins.clear();
1936 LOCK2(cs_main, cs_wallet);
1937 for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1939 const uint256& wtxid = it->first;
1940 const CWalletTx* pcoin = &(*it).second;
1942 if (!CheckFinalTx(*pcoin))
1943 continue;
1945 if (fOnlyConfirmed && !pcoin->IsTrusted())
1946 continue;
1948 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1949 continue;
1951 int nDepth = pcoin->GetDepthInMainChain();
1952 if (nDepth < 0)
1953 continue;
1955 // We should not consider coins which aren't at least in our mempool
1956 // It's possible for these to be conflicted via ancestors which we may never be able to detect
1957 if (nDepth == 0 && !pcoin->InMempool())
1958 continue;
1960 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
1961 isminetype mine = IsMine(pcoin->tx->vout[i]);
1962 if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
1963 !IsLockedCoin((*it).first, i) && (pcoin->tx->vout[i].nValue > 0 || fIncludeZeroValue) &&
1964 (!coinControl || !coinControl->HasSelected() || coinControl->fAllowOtherInputs || coinControl->IsSelected(COutPoint((*it).first, i))))
1965 vCoins.push_back(COutput(pcoin, i, nDepth,
1966 ((mine & ISMINE_SPENDABLE) != ISMINE_NO) ||
1967 (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO),
1968 (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO));
1974 static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > >vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
1975 vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
1977 vector<char> vfIncluded;
1979 vfBest.assign(vValue.size(), true);
1980 nBest = nTotalLower;
1982 FastRandomContext insecure_rand;
1984 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
1986 vfIncluded.assign(vValue.size(), false);
1987 CAmount nTotal = 0;
1988 bool fReachedTarget = false;
1989 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
1991 for (unsigned int i = 0; i < vValue.size(); i++)
1993 //The solver here uses a randomized algorithm,
1994 //the randomness serves no real security purpose but is just
1995 //needed to prevent degenerate behavior and it is important
1996 //that the rng is fast. We do not use a constant random sequence,
1997 //because there may be some privacy improvement by making
1998 //the selection random.
1999 if (nPass == 0 ? insecure_rand.rand32()&1 : !vfIncluded[i])
2001 nTotal += vValue[i].first;
2002 vfIncluded[i] = true;
2003 if (nTotal >= nTargetValue)
2005 fReachedTarget = true;
2006 if (nTotal < nBest)
2008 nBest = nTotal;
2009 vfBest = vfIncluded;
2011 nTotal -= vValue[i].first;
2012 vfIncluded[i] = false;
2020 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins,
2021 set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
2023 setCoinsRet.clear();
2024 nValueRet = 0;
2026 // List of values less than target
2027 pair<CAmount, pair<const CWalletTx*,unsigned int> > coinLowestLarger;
2028 coinLowestLarger.first = std::numeric_limits<CAmount>::max();
2029 coinLowestLarger.second.first = NULL;
2030 vector<pair<CAmount, pair<const CWalletTx*,unsigned int> > > vValue;
2031 CAmount nTotalLower = 0;
2033 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2035 BOOST_FOREACH(const COutput &output, vCoins)
2037 if (!output.fSpendable)
2038 continue;
2040 const CWalletTx *pcoin = output.tx;
2042 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2043 continue;
2045 int i = output.i;
2046 CAmount n = pcoin->tx->vout[i].nValue;
2048 pair<CAmount,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin, i));
2050 if (n == nTargetValue)
2052 setCoinsRet.insert(coin.second);
2053 nValueRet += coin.first;
2054 return true;
2056 else if (n < nTargetValue + MIN_CHANGE)
2058 vValue.push_back(coin);
2059 nTotalLower += n;
2061 else if (n < coinLowestLarger.first)
2063 coinLowestLarger = coin;
2067 if (nTotalLower == nTargetValue)
2069 for (unsigned int i = 0; i < vValue.size(); ++i)
2071 setCoinsRet.insert(vValue[i].second);
2072 nValueRet += vValue[i].first;
2074 return true;
2077 if (nTotalLower < nTargetValue)
2079 if (coinLowestLarger.second.first == NULL)
2080 return false;
2081 setCoinsRet.insert(coinLowestLarger.second);
2082 nValueRet += coinLowestLarger.first;
2083 return true;
2086 // Solve subset sum by stochastic approximation
2087 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2088 std::reverse(vValue.begin(), vValue.end());
2089 vector<char> vfBest;
2090 CAmount nBest;
2092 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2093 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2094 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2096 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2097 // or the next bigger coin is closer), return the bigger coin
2098 if (coinLowestLarger.second.first &&
2099 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger.first <= nBest))
2101 setCoinsRet.insert(coinLowestLarger.second);
2102 nValueRet += coinLowestLarger.first;
2104 else {
2105 for (unsigned int i = 0; i < vValue.size(); i++)
2106 if (vfBest[i])
2108 setCoinsRet.insert(vValue[i].second);
2109 nValueRet += vValue[i].first;
2112 LogPrint("selectcoins", "SelectCoins() best subset: ");
2113 for (unsigned int i = 0; i < vValue.size(); i++)
2114 if (vfBest[i])
2115 LogPrint("selectcoins", "%s ", FormatMoney(vValue[i].first));
2116 LogPrint("selectcoins", "total %s\n", FormatMoney(nBest));
2119 return true;
2122 bool CWallet::SelectCoins(const vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, set<pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2124 vector<COutput> vCoins(vAvailableCoins);
2126 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2127 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2129 BOOST_FOREACH(const COutput& out, vCoins)
2131 if (!out.fSpendable)
2132 continue;
2133 nValueRet += out.tx->tx->vout[out.i].nValue;
2134 setCoinsRet.insert(make_pair(out.tx, out.i));
2136 return (nValueRet >= nTargetValue);
2139 // calculate value from preset inputs and store them
2140 set<pair<const CWalletTx*, uint32_t> > setPresetCoins;
2141 CAmount nValueFromPresetInputs = 0;
2143 std::vector<COutPoint> vPresetInputs;
2144 if (coinControl)
2145 coinControl->ListSelected(vPresetInputs);
2146 BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
2148 map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2149 if (it != mapWallet.end())
2151 const CWalletTx* pcoin = &it->second;
2152 // Clearly invalid input, fail
2153 if (pcoin->tx->vout.size() <= outpoint.n)
2154 return false;
2155 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2156 setPresetCoins.insert(make_pair(pcoin, outpoint.n));
2157 } else
2158 return false; // TODO: Allow non-wallet inputs
2161 // remove preset inputs from vCoins
2162 for (vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2164 if (setPresetCoins.count(make_pair(it->tx, it->i)))
2165 it = vCoins.erase(it);
2166 else
2167 ++it;
2170 bool res = nTargetValue <= nValueFromPresetInputs ||
2171 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, vCoins, setCoinsRet, nValueRet) ||
2172 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, vCoins, setCoinsRet, nValueRet) ||
2173 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, vCoins, setCoinsRet, nValueRet));
2175 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2176 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2178 // add preset inputs to the total value selected
2179 nValueRet += nValueFromPresetInputs;
2181 return res;
2184 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, bool overrideEstimatedFeeRate, const CFeeRate& specificFeeRate, int& nChangePosInOut, std::string& strFailReason, bool includeWatching, bool lockUnspents, const CTxDestination& destChange)
2186 vector<CRecipient> vecSend;
2188 // Turn the txout set into a CRecipient vector
2189 BOOST_FOREACH(const CTxOut& txOut, tx.vout)
2191 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, false};
2192 vecSend.push_back(recipient);
2195 CCoinControl coinControl;
2196 coinControl.destChange = destChange;
2197 coinControl.fAllowOtherInputs = true;
2198 coinControl.fAllowWatchOnly = includeWatching;
2199 coinControl.fOverrideFeeRate = overrideEstimatedFeeRate;
2200 coinControl.nFeeRate = specificFeeRate;
2202 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2203 coinControl.Select(txin.prevout);
2205 CReserveKey reservekey(this);
2206 CWalletTx wtx;
2207 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, &coinControl, false))
2208 return false;
2210 if (nChangePosInOut != -1)
2211 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2213 // Add new txins (keeping original txin scriptSig/order)
2214 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
2216 if (!coinControl.IsSelected(txin.prevout))
2218 tx.vin.push_back(txin);
2220 if (lockUnspents)
2222 LOCK2(cs_main, cs_wallet);
2223 LockCoin(txin.prevout);
2228 return true;
2231 bool CWallet::CreateTransaction(const vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2232 int& nChangePosInOut, std::string& strFailReason, const CCoinControl* coinControl, bool sign)
2234 CAmount nValue = 0;
2235 int nChangePosRequest = nChangePosInOut;
2236 unsigned int nSubtractFeeFromAmount = 0;
2237 BOOST_FOREACH (const CRecipient& recipient, vecSend)
2239 if (nValue < 0 || recipient.nAmount < 0)
2241 strFailReason = _("Transaction amounts must not be negative");
2242 return false;
2244 nValue += recipient.nAmount;
2246 if (recipient.fSubtractFeeFromAmount)
2247 nSubtractFeeFromAmount++;
2249 if (vecSend.empty())
2251 strFailReason = _("Transaction must have at least one recipient");
2252 return false;
2255 wtxNew.fTimeReceivedIsTxTime = true;
2256 wtxNew.BindWallet(this);
2257 CMutableTransaction txNew;
2259 // Discourage fee sniping.
2261 // For a large miner the value of the transactions in the best block and
2262 // the mempool can exceed the cost of deliberately attempting to mine two
2263 // blocks to orphan the current best block. By setting nLockTime such that
2264 // only the next block can include the transaction, we discourage this
2265 // practice as the height restricted and limited blocksize gives miners
2266 // considering fee sniping fewer options for pulling off this attack.
2268 // A simple way to think about this is from the wallet's point of view we
2269 // always want the blockchain to move forward. By setting nLockTime this
2270 // way we're basically making the statement that we only want this
2271 // transaction to appear in the next block; we don't want to potentially
2272 // encourage reorgs by allowing transactions to appear at lower heights
2273 // than the next block in forks of the best chain.
2275 // Of course, the subsidy is high enough, and transaction volume low
2276 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2277 // now we ensure code won't be written that makes assumptions about
2278 // nLockTime that preclude a fix later.
2279 txNew.nLockTime = chainActive.Height();
2281 // Secondly occasionally randomly pick a nLockTime even further back, so
2282 // that transactions that are delayed after signing for whatever reason,
2283 // e.g. high-latency mix networks and some CoinJoin implementations, have
2284 // better privacy.
2285 if (GetRandInt(10) == 0)
2286 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2288 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2289 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2292 LOCK2(cs_main, cs_wallet);
2294 std::vector<COutput> vAvailableCoins;
2295 AvailableCoins(vAvailableCoins, true, coinControl);
2297 nFeeRet = 0;
2298 // Start with no fee and loop until there is enough fee
2299 while (true)
2301 nChangePosInOut = nChangePosRequest;
2302 txNew.vin.clear();
2303 txNew.vout.clear();
2304 wtxNew.fFromMe = true;
2305 bool fFirst = true;
2307 CAmount nValueToSelect = nValue;
2308 if (nSubtractFeeFromAmount == 0)
2309 nValueToSelect += nFeeRet;
2310 double dPriority = 0;
2311 // vouts to the payees
2312 BOOST_FOREACH (const CRecipient& recipient, vecSend)
2314 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2316 if (recipient.fSubtractFeeFromAmount)
2318 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2320 if (fFirst) // first receiver pays the remainder not divisible by output count
2322 fFirst = false;
2323 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2327 if (txout.IsDust(::minRelayTxFee))
2329 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2331 if (txout.nValue < 0)
2332 strFailReason = _("The transaction amount is too small to pay the fee");
2333 else
2334 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2336 else
2337 strFailReason = _("Transaction amount too small");
2338 return false;
2340 txNew.vout.push_back(txout);
2343 // Choose coins to use
2344 set<pair<const CWalletTx*,unsigned int> > setCoins;
2345 CAmount nValueIn = 0;
2346 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, coinControl))
2348 strFailReason = _("Insufficient funds");
2349 return false;
2351 BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins)
2353 CAmount nCredit = pcoin.first->tx->vout[pcoin.second].nValue;
2354 //The coin age after the next block (depth+1) is used instead of the current,
2355 //reflecting an assumption the user would accept a bit more delay for
2356 //a chance at a free transaction.
2357 //But mempool inputs might still be in the mempool, so their age stays 0
2358 int age = pcoin.first->GetDepthInMainChain();
2359 assert(age >= 0);
2360 if (age != 0)
2361 age += 1;
2362 dPriority += (double)nCredit * age;
2365 const CAmount nChange = nValueIn - nValueToSelect;
2366 if (nChange > 0)
2368 // Fill a vout to ourself
2369 // TODO: pass in scriptChange instead of reservekey so
2370 // change transaction isn't always pay-to-bitcoin-address
2371 CScript scriptChange;
2373 // coin control: send change to custom address
2374 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
2375 scriptChange = GetScriptForDestination(coinControl->destChange);
2377 // no coin control: send change to newly generated address
2378 else
2380 // Note: We use a new key here to keep it from being obvious which side is the change.
2381 // The drawback is that by not reusing a previous key, the change may be lost if a
2382 // backup is restored, if the backup doesn't have the new private key for the change.
2383 // If we reused the old key, it would be possible to add code to look for and
2384 // rediscover unknown transactions that were written with keys of ours to recover
2385 // post-backup change.
2387 // Reserve a new key pair from key pool
2388 CPubKey vchPubKey;
2389 bool ret;
2390 ret = reservekey.GetReservedKey(vchPubKey);
2391 assert(ret); // should never fail, as we just unlocked
2393 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2396 CTxOut newTxOut(nChange, scriptChange);
2398 // We do not move dust-change to fees, because the sender would end up paying more than requested.
2399 // This would be against the purpose of the all-inclusive feature.
2400 // So instead we raise the change and deduct from the recipient.
2401 if (nSubtractFeeFromAmount > 0 && newTxOut.IsDust(::minRelayTxFee))
2403 CAmount nDust = newTxOut.GetDustThreshold(::minRelayTxFee) - newTxOut.nValue;
2404 newTxOut.nValue += nDust; // raise change until no more dust
2405 for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
2407 if (vecSend[i].fSubtractFeeFromAmount)
2409 txNew.vout[i].nValue -= nDust;
2410 if (txNew.vout[i].IsDust(::minRelayTxFee))
2412 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2413 return false;
2415 break;
2420 // Never create dust outputs; if we would, just
2421 // add the dust to the fee.
2422 if (newTxOut.IsDust(::minRelayTxFee))
2424 nChangePosInOut = -1;
2425 nFeeRet += nChange;
2426 reservekey.ReturnKey();
2428 else
2430 if (nChangePosInOut == -1)
2432 // Insert change txn at random position:
2433 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2435 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2437 strFailReason = _("Change index out of range");
2438 return false;
2441 vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2442 txNew.vout.insert(position, newTxOut);
2445 else
2446 reservekey.ReturnKey();
2448 // Fill vin
2450 // Note how the sequence number is set to non-maxint so that
2451 // the nLockTime set above actually works.
2453 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2454 // we use the highest possible value in that range (maxint-2)
2455 // to avoid conflicting with other possible uses of nSequence,
2456 // and in the spirit of "smallest posible change from prior
2457 // behavior."
2458 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2459 txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
2460 std::numeric_limits<unsigned int>::max() - (fWalletRbf ? 2 : 1)));
2462 // Sign
2463 int nIn = 0;
2464 CTransaction txNewConst(txNew);
2465 BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins)
2467 bool signSuccess;
2468 const CScript& scriptPubKey = coin.first->tx->vout[coin.second].scriptPubKey;
2469 SignatureData sigdata;
2470 if (sign)
2471 signSuccess = ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.first->tx->vout[coin.second].nValue, SIGHASH_ALL), scriptPubKey, sigdata);
2472 else
2473 signSuccess = ProduceSignature(DummySignatureCreator(this), scriptPubKey, sigdata);
2475 if (!signSuccess)
2477 strFailReason = _("Signing transaction failed");
2478 return false;
2479 } else {
2480 UpdateTransaction(txNew, nIn, sigdata);
2483 nIn++;
2486 unsigned int nBytes = GetVirtualTransactionSize(txNew);
2488 // Remove scriptSigs if we used dummy signatures for fee calculation
2489 if (!sign) {
2490 BOOST_FOREACH (CTxIn& vin, txNew.vin) {
2491 vin.scriptSig = CScript();
2492 vin.scriptWitness.SetNull();
2496 // Embed the constructed transaction data in wtxNew.
2497 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2499 // Limit size
2500 if (GetTransactionWeight(wtxNew) >= MAX_STANDARD_TX_WEIGHT)
2502 strFailReason = _("Transaction too large");
2503 return false;
2506 dPriority = wtxNew.tx->ComputePriority(dPriority, nBytes);
2508 // Allow to override the default confirmation target over the CoinControl instance
2509 int currentConfirmationTarget = nTxConfirmTarget;
2510 if (coinControl && coinControl->nConfirmTarget > 0)
2511 currentConfirmationTarget = coinControl->nConfirmTarget;
2513 // Can we complete this as a free transaction?
2514 if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE)
2516 // Not enough fee: enough priority?
2517 double dPriorityNeeded = mempool.estimateSmartPriority(currentConfirmationTarget);
2518 // Require at least hard-coded AllowFree.
2519 if (dPriority >= dPriorityNeeded && AllowFree(dPriority))
2520 break;
2523 CAmount nFeeNeeded = GetMinimumFee(nBytes, currentConfirmationTarget, mempool);
2524 if (coinControl && nFeeNeeded > 0 && coinControl->nMinimumTotalFee > nFeeNeeded) {
2525 nFeeNeeded = coinControl->nMinimumTotalFee;
2527 if (coinControl && coinControl->fOverrideFeeRate)
2528 nFeeNeeded = coinControl->nFeeRate.GetFee(nBytes);
2530 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2531 // because we must be at the maximum allowed fee.
2532 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2534 strFailReason = _("Transaction too large for fee policy");
2535 return false;
2538 if (nFeeRet >= nFeeNeeded)
2539 break; // Done, enough fee included.
2541 // Include more fee and try again.
2542 nFeeRet = nFeeNeeded;
2543 continue;
2548 return true;
2552 * Call after CreateTransaction unless you want to abort
2554 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
2557 LOCK2(cs_main, cs_wallet);
2558 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
2560 // Take key pair from key pool so it won't be used again
2561 reservekey.KeepKey();
2563 // Add tx to wallet, because if it has change it's also ours,
2564 // otherwise just for transaction history.
2565 AddToWallet(wtxNew);
2567 // Notify that old coins are spent
2568 BOOST_FOREACH(const CTxIn& txin, wtxNew.tx->vin)
2570 CWalletTx &coin = mapWallet[txin.prevout.hash];
2571 coin.BindWallet(this);
2572 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2576 // Track how many getdata requests our transaction gets
2577 mapRequestCount[wtxNew.GetHash()] = 0;
2579 if (fBroadcastTransactions)
2581 // Broadcast
2582 if (!wtxNew.AcceptToMemoryPool(maxTxFee, state)) {
2583 // This must not fail. The transaction has already been signed and recorded.
2584 LogPrintf("CommitTransaction(): Error: Transaction not valid, %s\n", state.GetRejectReason());
2585 return false;
2587 wtxNew.RelayWalletTransaction(connman);
2590 return true;
2593 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
2594 CWalletDB walletdb(strWalletFile);
2595 return walletdb.ListAccountCreditDebit(strAccount, entries);
2598 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
2600 CWalletDB walletdb(strWalletFile);
2602 return AddAccountingEntry(acentry, &walletdb);
2605 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
2607 if (!pwalletdb->WriteAccountingEntry_Backend(acentry))
2608 return false;
2610 laccentries.push_back(acentry);
2611 CAccountingEntry & entry = laccentries.back();
2612 wtxOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
2614 return true;
2617 CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
2619 return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
2622 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
2624 // payTxFee is user-set "I want to pay this much"
2625 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
2626 // User didn't set: use -txconfirmtarget to estimate...
2627 if (nFeeNeeded == 0) {
2628 int estimateFoundTarget = nConfirmTarget;
2629 nFeeNeeded = pool.estimateSmartFee(nConfirmTarget, &estimateFoundTarget).GetFee(nTxBytes);
2630 // ... unless we don't have enough mempool data for estimatefee, then use fallbackFee
2631 if (nFeeNeeded == 0)
2632 nFeeNeeded = fallbackFee.GetFee(nTxBytes);
2634 // prevent user from paying a fee below minRelayTxFee or minTxFee
2635 nFeeNeeded = std::max(nFeeNeeded, GetRequiredFee(nTxBytes));
2636 // But always obey the maximum
2637 if (nFeeNeeded > maxTxFee)
2638 nFeeNeeded = maxTxFee;
2639 return nFeeNeeded;
2645 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2647 if (!fFileBacked)
2648 return DB_LOAD_OK;
2649 fFirstRunRet = false;
2650 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2651 if (nLoadWalletRet == DB_NEED_REWRITE)
2653 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2655 LOCK(cs_wallet);
2656 setKeyPool.clear();
2657 // Note: can't top-up keypool here, because wallet is locked.
2658 // User will be prompted to unlock wallet the next operation
2659 // that requires a new key.
2663 if (nLoadWalletRet != DB_LOAD_OK)
2664 return nLoadWalletRet;
2665 fFirstRunRet = !vchDefaultKey.IsValid();
2667 uiInterface.LoadWallet(this);
2669 return DB_LOAD_OK;
2672 DBErrors CWallet::ZapSelectTx(vector<uint256>& vHashIn, vector<uint256>& vHashOut)
2674 if (!fFileBacked)
2675 return DB_LOAD_OK;
2676 DBErrors nZapSelectTxRet = CWalletDB(strWalletFile,"cr+").ZapSelectTx(this, vHashIn, vHashOut);
2677 if (nZapSelectTxRet == DB_NEED_REWRITE)
2679 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2681 LOCK(cs_wallet);
2682 setKeyPool.clear();
2683 // Note: can't top-up keypool here, because wallet is locked.
2684 // User will be prompted to unlock wallet the next operation
2685 // that requires a new key.
2689 if (nZapSelectTxRet != DB_LOAD_OK)
2690 return nZapSelectTxRet;
2692 MarkDirty();
2694 return DB_LOAD_OK;
2698 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
2700 if (!fFileBacked)
2701 return DB_LOAD_OK;
2702 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(this, vWtx);
2703 if (nZapWalletTxRet == DB_NEED_REWRITE)
2705 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2707 LOCK(cs_wallet);
2708 setKeyPool.clear();
2709 // Note: can't top-up keypool here, because wallet is locked.
2710 // User will be prompted to unlock wallet the next operation
2711 // that requires a new key.
2715 if (nZapWalletTxRet != DB_LOAD_OK)
2716 return nZapWalletTxRet;
2718 return DB_LOAD_OK;
2722 bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose)
2724 bool fUpdated = false;
2726 LOCK(cs_wallet); // mapAddressBook
2727 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
2728 fUpdated = mi != mapAddressBook.end();
2729 mapAddressBook[address].name = strName;
2730 if (!strPurpose.empty()) /* update purpose only if requested */
2731 mapAddressBook[address].purpose = strPurpose;
2733 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
2734 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
2735 if (!fFileBacked)
2736 return false;
2737 if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
2738 return false;
2739 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2742 bool CWallet::DelAddressBook(const CTxDestination& address)
2745 LOCK(cs_wallet); // mapAddressBook
2747 if(fFileBacked)
2749 // Delete destdata tuples associated with address
2750 std::string strAddress = CBitcoinAddress(address).ToString();
2751 BOOST_FOREACH(const PAIRTYPE(string, string) &item, mapAddressBook[address].destdata)
2753 CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
2756 mapAddressBook.erase(address);
2759 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
2761 if (!fFileBacked)
2762 return false;
2763 CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
2764 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2767 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2769 if (fFileBacked)
2771 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2772 return false;
2774 vchDefaultKey = vchPubKey;
2775 return true;
2779 * Mark old keypool keys as used,
2780 * and generate all new keys
2782 bool CWallet::NewKeyPool()
2785 LOCK(cs_wallet);
2786 CWalletDB walletdb(strWalletFile);
2787 BOOST_FOREACH(int64_t nIndex, setKeyPool)
2788 walletdb.ErasePool(nIndex);
2789 setKeyPool.clear();
2791 if (IsLocked())
2792 return false;
2794 int64_t nKeys = max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t)0);
2795 for (int i = 0; i < nKeys; i++)
2797 int64_t nIndex = i+1;
2798 walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
2799 setKeyPool.insert(nIndex);
2801 LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys);
2803 return true;
2806 bool CWallet::TopUpKeyPool(unsigned int kpSize)
2809 LOCK(cs_wallet);
2811 if (IsLocked())
2812 return false;
2814 CWalletDB walletdb(strWalletFile);
2816 // Top up key pool
2817 unsigned int nTargetSize;
2818 if (kpSize > 0)
2819 nTargetSize = kpSize;
2820 else
2821 nTargetSize = max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
2823 while (setKeyPool.size() < (nTargetSize + 1))
2825 int64_t nEnd = 1;
2826 if (!setKeyPool.empty())
2827 nEnd = *(--setKeyPool.end()) + 1;
2828 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
2829 throw runtime_error(std::string(__func__) + ": writing generated key failed");
2830 setKeyPool.insert(nEnd);
2831 LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size());
2834 return true;
2837 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool)
2839 nIndex = -1;
2840 keypool.vchPubKey = CPubKey();
2842 LOCK(cs_wallet);
2844 if (!IsLocked())
2845 TopUpKeyPool();
2847 // Get the oldest key
2848 if(setKeyPool.empty())
2849 return;
2851 CWalletDB walletdb(strWalletFile);
2853 nIndex = *(setKeyPool.begin());
2854 setKeyPool.erase(setKeyPool.begin());
2855 if (!walletdb.ReadPool(nIndex, keypool))
2856 throw runtime_error(std::string(__func__) + ": read failed");
2857 if (!HaveKey(keypool.vchPubKey.GetID()))
2858 throw runtime_error(std::string(__func__) + ": unknown key in key pool");
2859 assert(keypool.vchPubKey.IsValid());
2860 LogPrintf("keypool reserve %d\n", nIndex);
2864 void CWallet::KeepKey(int64_t nIndex)
2866 // Remove from key pool
2867 if (fFileBacked)
2869 CWalletDB walletdb(strWalletFile);
2870 walletdb.ErasePool(nIndex);
2872 LogPrintf("keypool keep %d\n", nIndex);
2875 void CWallet::ReturnKey(int64_t nIndex)
2877 // Return to key pool
2879 LOCK(cs_wallet);
2880 setKeyPool.insert(nIndex);
2882 LogPrintf("keypool return %d\n", nIndex);
2885 bool CWallet::GetKeyFromPool(CPubKey& result)
2887 int64_t nIndex = 0;
2888 CKeyPool keypool;
2890 LOCK(cs_wallet);
2891 ReserveKeyFromKeyPool(nIndex, keypool);
2892 if (nIndex == -1)
2894 if (IsLocked()) return false;
2895 result = GenerateNewKey();
2896 return true;
2898 KeepKey(nIndex);
2899 result = keypool.vchPubKey;
2901 return true;
2904 int64_t CWallet::GetOldestKeyPoolTime()
2906 LOCK(cs_wallet);
2908 // if the keypool is empty, return <NOW>
2909 if (setKeyPool.empty())
2910 return GetTime();
2912 // load oldest key from keypool, get time and return
2913 CKeyPool keypool;
2914 CWalletDB walletdb(strWalletFile);
2915 int64_t nIndex = *(setKeyPool.begin());
2916 if (!walletdb.ReadPool(nIndex, keypool))
2917 throw runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
2918 assert(keypool.vchPubKey.IsValid());
2919 return keypool.nTime;
2922 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
2924 map<CTxDestination, CAmount> balances;
2927 LOCK(cs_wallet);
2928 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2930 CWalletTx *pcoin = &walletEntry.second;
2932 if (!pcoin->IsTrusted())
2933 continue;
2935 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2936 continue;
2938 int nDepth = pcoin->GetDepthInMainChain();
2939 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
2940 continue;
2942 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
2944 CTxDestination addr;
2945 if (!IsMine(pcoin->tx->vout[i]))
2946 continue;
2947 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
2948 continue;
2950 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
2952 if (!balances.count(addr))
2953 balances[addr] = 0;
2954 balances[addr] += n;
2959 return balances;
2962 set< set<CTxDestination> > CWallet::GetAddressGroupings()
2964 AssertLockHeld(cs_wallet); // mapWallet
2965 set< set<CTxDestination> > groupings;
2966 set<CTxDestination> grouping;
2968 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
2970 CWalletTx *pcoin = &walletEntry.second;
2972 if (pcoin->tx->vin.size() > 0)
2974 bool any_mine = false;
2975 // group all input addresses with each other
2976 BOOST_FOREACH(CTxIn txin, pcoin->tx->vin)
2978 CTxDestination address;
2979 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
2980 continue;
2981 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
2982 continue;
2983 grouping.insert(address);
2984 any_mine = true;
2987 // group change with input addresses
2988 if (any_mine)
2990 BOOST_FOREACH(CTxOut txout, pcoin->tx->vout)
2991 if (IsChange(txout))
2993 CTxDestination txoutAddr;
2994 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
2995 continue;
2996 grouping.insert(txoutAddr);
2999 if (grouping.size() > 0)
3001 groupings.insert(grouping);
3002 grouping.clear();
3006 // group lone addrs by themselves
3007 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3008 if (IsMine(pcoin->tx->vout[i]))
3010 CTxDestination address;
3011 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, address))
3012 continue;
3013 grouping.insert(address);
3014 groupings.insert(grouping);
3015 grouping.clear();
3019 set< set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3020 map< CTxDestination, set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3021 BOOST_FOREACH(set<CTxDestination> _grouping, groupings)
3023 // make a set of all the groups hit by this new group
3024 set< set<CTxDestination>* > hits;
3025 map< CTxDestination, set<CTxDestination>* >::iterator it;
3026 BOOST_FOREACH(CTxDestination address, _grouping)
3027 if ((it = setmap.find(address)) != setmap.end())
3028 hits.insert((*it).second);
3030 // merge all hit groups into a new single group and delete old groups
3031 set<CTxDestination>* merged = new set<CTxDestination>(_grouping);
3032 BOOST_FOREACH(set<CTxDestination>* hit, hits)
3034 merged->insert(hit->begin(), hit->end());
3035 uniqueGroupings.erase(hit);
3036 delete hit;
3038 uniqueGroupings.insert(merged);
3040 // update setmap
3041 BOOST_FOREACH(CTxDestination element, *merged)
3042 setmap[element] = merged;
3045 set< set<CTxDestination> > ret;
3046 BOOST_FOREACH(set<CTxDestination>* uniqueGrouping, uniqueGroupings)
3048 ret.insert(*uniqueGrouping);
3049 delete uniqueGrouping;
3052 return ret;
3055 CAmount CWallet::GetAccountBalance(const std::string& strAccount, int nMinDepth, const isminefilter& filter)
3057 CWalletDB walletdb(strWalletFile);
3058 return GetAccountBalance(walletdb, strAccount, nMinDepth, filter);
3061 CAmount CWallet::GetAccountBalance(CWalletDB& walletdb, const std::string& strAccount, int nMinDepth, const isminefilter& filter)
3063 CAmount nBalance = 0;
3065 // Tally wallet transactions
3066 for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3068 const CWalletTx& wtx = (*it).second;
3069 if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0)
3070 continue;
3072 CAmount nReceived, nSent, nFee;
3073 wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee, filter);
3075 if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
3076 nBalance += nReceived;
3077 nBalance -= nSent + nFee;
3080 // Tally internal accounting entries
3081 nBalance += walletdb.GetAccountCreditDebit(strAccount);
3083 return nBalance;
3086 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3088 LOCK(cs_wallet);
3089 set<CTxDestination> result;
3090 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
3092 const CTxDestination& address = item.first;
3093 const string& strName = item.second.name;
3094 if (strName == strAccount)
3095 result.insert(address);
3097 return result;
3100 bool CReserveKey::GetReservedKey(CPubKey& pubkey)
3102 if (nIndex == -1)
3104 CKeyPool keypool;
3105 pwallet->ReserveKeyFromKeyPool(nIndex, keypool);
3106 if (nIndex != -1)
3107 vchPubKey = keypool.vchPubKey;
3108 else {
3109 return false;
3112 assert(vchPubKey.IsValid());
3113 pubkey = vchPubKey;
3114 return true;
3117 void CReserveKey::KeepKey()
3119 if (nIndex != -1)
3120 pwallet->KeepKey(nIndex);
3121 nIndex = -1;
3122 vchPubKey = CPubKey();
3125 void CReserveKey::ReturnKey()
3127 if (nIndex != -1)
3128 pwallet->ReturnKey(nIndex);
3129 nIndex = -1;
3130 vchPubKey = CPubKey();
3133 void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const
3135 setAddress.clear();
3137 CWalletDB walletdb(strWalletFile);
3139 LOCK2(cs_main, cs_wallet);
3140 BOOST_FOREACH(const int64_t& id, setKeyPool)
3142 CKeyPool keypool;
3143 if (!walletdb.ReadPool(id, keypool))
3144 throw runtime_error(std::string(__func__) + ": read failed");
3145 assert(keypool.vchPubKey.IsValid());
3146 CKeyID keyID = keypool.vchPubKey.GetID();
3147 if (!HaveKey(keyID))
3148 throw runtime_error(std::string(__func__) + ": unknown key in key pool");
3149 setAddress.insert(keyID);
3153 void CWallet::UpdatedTransaction(const uint256 &hashTx)
3156 LOCK(cs_wallet);
3157 // Only notify UI if this transaction is in this wallet
3158 map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
3159 if (mi != mapWallet.end())
3160 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
3164 void CWallet::GetScriptForMining(boost::shared_ptr<CReserveScript> &script)
3166 boost::shared_ptr<CReserveKey> rKey(new CReserveKey(this));
3167 CPubKey pubkey;
3168 if (!rKey->GetReservedKey(pubkey))
3169 return;
3171 script = rKey;
3172 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3175 void CWallet::LockCoin(const COutPoint& output)
3177 AssertLockHeld(cs_wallet); // setLockedCoins
3178 setLockedCoins.insert(output);
3181 void CWallet::UnlockCoin(const COutPoint& output)
3183 AssertLockHeld(cs_wallet); // setLockedCoins
3184 setLockedCoins.erase(output);
3187 void CWallet::UnlockAllCoins()
3189 AssertLockHeld(cs_wallet); // setLockedCoins
3190 setLockedCoins.clear();
3193 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3195 AssertLockHeld(cs_wallet); // setLockedCoins
3196 COutPoint outpt(hash, n);
3198 return (setLockedCoins.count(outpt) > 0);
3201 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
3203 AssertLockHeld(cs_wallet); // setLockedCoins
3204 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3205 it != setLockedCoins.end(); it++) {
3206 COutPoint outpt = (*it);
3207 vOutpts.push_back(outpt);
3211 /** @} */ // end of Actions
3213 class CAffectedKeysVisitor : public boost::static_visitor<void> {
3214 private:
3215 const CKeyStore &keystore;
3216 std::vector<CKeyID> &vKeys;
3218 public:
3219 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
3221 void Process(const CScript &script) {
3222 txnouttype type;
3223 std::vector<CTxDestination> vDest;
3224 int nRequired;
3225 if (ExtractDestinations(script, type, vDest, nRequired)) {
3226 BOOST_FOREACH(const CTxDestination &dest, vDest)
3227 boost::apply_visitor(*this, dest);
3231 void operator()(const CKeyID &keyId) {
3232 if (keystore.HaveKey(keyId))
3233 vKeys.push_back(keyId);
3236 void operator()(const CScriptID &scriptId) {
3237 CScript script;
3238 if (keystore.GetCScript(scriptId, script))
3239 Process(script);
3242 void operator()(const CNoDestination &none) {}
3245 void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t> &mapKeyBirth) const {
3246 AssertLockHeld(cs_wallet); // mapKeyMetadata
3247 mapKeyBirth.clear();
3249 // get birth times for keys with metadata
3250 for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++)
3251 if (it->second.nCreateTime)
3252 mapKeyBirth[it->first] = it->second.nCreateTime;
3254 // map in which we'll infer heights of other keys
3255 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3256 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3257 std::set<CKeyID> setKeys;
3258 GetKeys(setKeys);
3259 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
3260 if (mapKeyBirth.count(keyid) == 0)
3261 mapKeyFirstBlock[keyid] = pindexMax;
3263 setKeys.clear();
3265 // if there are no such keys, we're done
3266 if (mapKeyFirstBlock.empty())
3267 return;
3269 // find first block that affects those keys, if there are any left
3270 std::vector<CKeyID> vAffected;
3271 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3272 // iterate over all wallet transactions...
3273 const CWalletTx &wtx = (*it).second;
3274 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3275 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3276 // ... which are already in a block
3277 int nHeight = blit->second->nHeight;
3278 BOOST_FOREACH(const CTxOut &txout, wtx.tx->vout) {
3279 // iterate over all their outputs
3280 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3281 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
3282 // ... and all their affected keys
3283 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3284 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3285 rit->second = blit->second;
3287 vAffected.clear();
3292 // Extract block timestamps for those keys
3293 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3294 mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off
3297 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3299 if (boost::get<CNoDestination>(&dest))
3300 return false;
3302 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3303 if (!fFileBacked)
3304 return true;
3305 return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
3308 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3310 if (!mapAddressBook[dest].destdata.erase(key))
3311 return false;
3312 if (!fFileBacked)
3313 return true;
3314 return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
3317 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3319 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3320 return true;
3323 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3325 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3326 if(i != mapAddressBook.end())
3328 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3329 if(j != i->second.destdata.end())
3331 if(value)
3332 *value = j->second;
3333 return true;
3336 return false;
3339 std::string CWallet::GetWalletHelpString(bool showDebug)
3341 std::string strUsage = HelpMessageGroup(_("Wallet options:"));
3342 strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
3343 strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE));
3344 strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
3345 CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)));
3346 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
3347 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)));
3348 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
3349 CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
3350 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
3351 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup"));
3352 if (showDebug)
3353 strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), DEFAULT_SEND_FREE_TRANSACTIONS));
3354 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE));
3355 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));
3356 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));
3357 strUsage += HelpMessageOpt("-walletrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (default: %u)"), DEFAULT_WALLET_RBF));
3358 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
3359 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT));
3360 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST));
3361 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
3362 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
3363 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
3365 if (showDebug)
3367 strUsage += HelpMessageGroup(_("Wallet debugging/testing options:"));
3369 strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE));
3370 strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET));
3371 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB));
3374 return strUsage;
3377 bool CWallet::InitLoadWallet()
3379 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
3380 pwalletMain = NULL;
3381 LogPrintf("Wallet disabled!\n");
3382 return true;
3385 std::string walletFile = GetArg("-wallet", DEFAULT_WALLET_DAT);
3387 // needed to restore wallet transaction meta data after -zapwallettxes
3388 std::vector<CWalletTx> vWtx;
3390 if (GetBoolArg("-zapwallettxes", false)) {
3391 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3393 CWallet *tempWallet = new CWallet(walletFile);
3394 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3395 if (nZapWalletRet != DB_LOAD_OK) {
3396 return InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3399 delete tempWallet;
3400 tempWallet = NULL;
3403 uiInterface.InitMessage(_("Loading wallet..."));
3405 int64_t nStart = GetTimeMillis();
3406 bool fFirstRun = true;
3407 CWallet *walletInstance = new CWallet(walletFile);
3408 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3409 if (nLoadWalletRet != DB_LOAD_OK)
3411 if (nLoadWalletRet == DB_CORRUPT)
3412 return InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3413 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3415 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3416 " or address book entries might be missing or incorrect."),
3417 walletFile));
3419 else if (nLoadWalletRet == DB_TOO_NEW)
3420 return InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"),
3421 walletFile, _(PACKAGE_NAME)));
3422 else if (nLoadWalletRet == DB_NEED_REWRITE)
3424 return InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3426 else
3427 return InitError(strprintf(_("Error loading %s"), walletFile));
3430 if (GetBoolArg("-upgradewallet", fFirstRun))
3432 int nMaxVersion = GetArg("-upgradewallet", 0);
3433 if (nMaxVersion == 0) // the -upgradewallet without argument case
3435 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3436 nMaxVersion = CLIENT_VERSION;
3437 walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3439 else
3440 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3441 if (nMaxVersion < walletInstance->GetVersion())
3443 return InitError(_("Cannot downgrade wallet"));
3445 walletInstance->SetMaxVersion(nMaxVersion);
3448 if (fFirstRun)
3450 // Create new keyUser and set as default key
3451 if (GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && !walletInstance->IsHDEnabled()) {
3452 // generate a new master key
3453 CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
3454 if (!walletInstance->SetHDMasterKey(masterPubKey))
3455 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
3457 CPubKey newDefaultKey;
3458 if (walletInstance->GetKeyFromPool(newDefaultKey)) {
3459 walletInstance->SetDefaultKey(newDefaultKey);
3460 if (!walletInstance->SetAddressBook(walletInstance->vchDefaultKey.GetID(), "", "receive"))
3461 return InitError(_("Cannot write default address") += "\n");
3464 walletInstance->SetBestChain(chainActive.GetLocator());
3466 else if (mapArgs.count("-usehd")) {
3467 bool useHD = GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
3468 if (walletInstance->IsHDEnabled() && !useHD)
3469 return InitError(strprintf(_("Error loading %s: You can't disable HD on a already existing HD wallet"), walletFile));
3470 if (!walletInstance->IsHDEnabled() && useHD)
3471 return InitError(strprintf(_("Error loading %s: You can't enable HD on a already existing non-HD wallet"), walletFile));
3474 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
3476 RegisterValidationInterface(walletInstance);
3478 CBlockIndex *pindexRescan = chainActive.Tip();
3479 if (GetBoolArg("-rescan", false))
3480 pindexRescan = chainActive.Genesis();
3481 else
3483 CWalletDB walletdb(walletFile);
3484 CBlockLocator locator;
3485 if (walletdb.ReadBestBlock(locator))
3486 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
3487 else
3488 pindexRescan = chainActive.Genesis();
3490 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
3492 //We can't rescan beyond non-pruned blocks, stop and throw an error
3493 //this might happen if a user uses a old wallet within a pruned node
3494 // or if he ran -disablewallet for a longer time, then decided to re-enable
3495 if (fPruneMode)
3497 CBlockIndex *block = chainActive.Tip();
3498 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
3499 block = block->pprev;
3501 if (pindexRescan != block)
3502 return InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3505 uiInterface.InitMessage(_("Rescanning..."));
3506 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
3507 nStart = GetTimeMillis();
3508 walletInstance->ScanForWalletTransactions(pindexRescan, true);
3509 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
3510 walletInstance->SetBestChain(chainActive.GetLocator());
3511 nWalletDBUpdated++;
3513 // Restore wallet transaction metadata after -zapwallettxes=1
3514 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
3516 CWalletDB walletdb(walletFile);
3518 BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
3520 uint256 hash = wtxOld.GetHash();
3521 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
3522 if (mi != walletInstance->mapWallet.end())
3524 const CWalletTx* copyFrom = &wtxOld;
3525 CWalletTx* copyTo = &mi->second;
3526 copyTo->mapValue = copyFrom->mapValue;
3527 copyTo->vOrderForm = copyFrom->vOrderForm;
3528 copyTo->nTimeReceived = copyFrom->nTimeReceived;
3529 copyTo->nTimeSmart = copyFrom->nTimeSmart;
3530 copyTo->fFromMe = copyFrom->fFromMe;
3531 copyTo->strFromAccount = copyFrom->strFromAccount;
3532 copyTo->nOrderPos = copyFrom->nOrderPos;
3533 walletdb.WriteTx(*copyTo);
3538 walletInstance->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
3541 LOCK(walletInstance->cs_wallet);
3542 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
3543 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
3544 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
3547 pwalletMain = walletInstance;
3549 return true;
3552 void CWallet::postInitProcess(boost::thread_group& threadGroup)
3554 // Add wallet transactions that aren't already in a block to mempool
3555 // Do this here as mempool requires genesis block to be loaded
3556 ReacceptWalletTransactions();
3558 // Run a thread to flush wallet periodically
3559 threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(this->strWalletFile)));
3562 bool CWallet::ParameterInteraction()
3564 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
3565 return true;
3567 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && SoftSetBoolArg("-walletbroadcast", false)) {
3568 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
3571 if (GetBoolArg("-salvagewallet", false) && SoftSetBoolArg("-rescan", true)) {
3572 // Rewrite just private keys: rescan to find transactions
3573 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
3576 // -zapwallettx implies a rescan
3577 if (GetBoolArg("-zapwallettxes", false) && SoftSetBoolArg("-rescan", true)) {
3578 LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
3581 if (GetBoolArg("-sysperms", false))
3582 return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
3583 if (GetArg("-prune", 0) && GetBoolArg("-rescan", false))
3584 return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
3586 if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB)
3587 InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
3588 _("The wallet will avoid paying less than the minimum relay fee."));
3590 if (mapArgs.count("-mintxfee"))
3592 CAmount n = 0;
3593 if (!ParseMoney(mapArgs["-mintxfee"], n) || 0 == n)
3594 return InitError(AmountErrMsg("mintxfee", mapArgs["-mintxfee"]));
3595 if (n > HIGH_TX_FEE_PER_KB)
3596 InitWarning(AmountHighWarn("-mintxfee") + " " +
3597 _("This is the minimum transaction fee you pay on every transaction."));
3598 CWallet::minTxFee = CFeeRate(n);
3600 if (mapArgs.count("-fallbackfee"))
3602 CAmount nFeePerK = 0;
3603 if (!ParseMoney(mapArgs["-fallbackfee"], nFeePerK))
3604 return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), mapArgs["-fallbackfee"]));
3605 if (nFeePerK > HIGH_TX_FEE_PER_KB)
3606 InitWarning(AmountHighWarn("-fallbackfee") + " " +
3607 _("This is the transaction fee you may pay when fee estimates are not available."));
3608 CWallet::fallbackFee = CFeeRate(nFeePerK);
3610 if (mapArgs.count("-paytxfee"))
3612 CAmount nFeePerK = 0;
3613 if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK))
3614 return InitError(AmountErrMsg("paytxfee", mapArgs["-paytxfee"]));
3615 if (nFeePerK > HIGH_TX_FEE_PER_KB)
3616 InitWarning(AmountHighWarn("-paytxfee") + " " +
3617 _("This is the transaction fee you will pay if you send a transaction."));
3619 payTxFee = CFeeRate(nFeePerK, 1000);
3620 if (payTxFee < ::minRelayTxFee)
3622 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
3623 mapArgs["-paytxfee"], ::minRelayTxFee.ToString()));
3626 if (mapArgs.count("-maxtxfee"))
3628 CAmount nMaxFee = 0;
3629 if (!ParseMoney(mapArgs["-maxtxfee"], nMaxFee))
3630 return InitError(AmountErrMsg("maxtxfee", mapArgs["-maxtxfee"]));
3631 if (nMaxFee > HIGH_MAX_TX_FEE)
3632 InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
3633 maxTxFee = nMaxFee;
3634 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
3636 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
3637 mapArgs["-maxtxfee"], ::minRelayTxFee.ToString()));
3640 nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
3641 bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
3642 fSendFreeTransactions = GetBoolArg("-sendfreetransactions", DEFAULT_SEND_FREE_TRANSACTIONS);
3643 fWalletRbf = GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
3645 return true;
3648 bool CWallet::BackupWallet(const std::string& strDest)
3650 if (!fFileBacked)
3651 return false;
3652 while (true)
3655 LOCK(bitdb.cs_db);
3656 if (!bitdb.mapFileUseCount.count(strWalletFile) || bitdb.mapFileUseCount[strWalletFile] == 0)
3658 // Flush log data to the dat file
3659 bitdb.CloseDb(strWalletFile);
3660 bitdb.CheckpointLSN(strWalletFile);
3661 bitdb.mapFileUseCount.erase(strWalletFile);
3663 // Copy wallet file
3664 boost::filesystem::path pathSrc = GetDataDir() / strWalletFile;
3665 boost::filesystem::path pathDest(strDest);
3666 if (boost::filesystem::is_directory(pathDest))
3667 pathDest /= strWalletFile;
3669 try {
3670 #if BOOST_VERSION >= 104000
3671 boost::filesystem::copy_file(pathSrc, pathDest, boost::filesystem::copy_option::overwrite_if_exists);
3672 #else
3673 boost::filesystem::copy_file(pathSrc, pathDest);
3674 #endif
3675 LogPrintf("copied %s to %s\n", strWalletFile, pathDest.string());
3676 return true;
3677 } catch (const boost::filesystem::filesystem_error& e) {
3678 LogPrintf("error copying %s to %s - %s\n", strWalletFile, pathDest.string(), e.what());
3679 return false;
3683 MilliSleep(100);
3685 return false;
3688 CKeyPool::CKeyPool()
3690 nTime = GetTime();
3693 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn)
3695 nTime = GetTime();
3696 vchPubKey = vchPubKeyIn;
3699 CWalletKey::CWalletKey(int64_t nExpires)
3701 nTimeCreated = (nExpires ? GetTime() : 0);
3702 nTimeExpires = nExpires;
3705 int CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
3707 AssertLockHeld(cs_main);
3709 // Update the tx's hashBlock
3710 hashBlock = pindex->GetBlockHash();
3712 // set the position of the transaction in the block
3713 nIndex = posInBlock;
3715 // Is the tx in a block that's in the main chain
3716 if (!chainActive.Contains(pindex))
3717 return 0;
3719 return chainActive.Height() - pindex->nHeight + 1;
3722 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
3724 if (hashUnset())
3725 return 0;
3727 AssertLockHeld(cs_main);
3729 // Find the block it claims to be in
3730 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
3731 if (mi == mapBlockIndex.end())
3732 return 0;
3733 CBlockIndex* pindex = (*mi).second;
3734 if (!pindex || !chainActive.Contains(pindex))
3735 return 0;
3737 pindexRet = pindex;
3738 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
3741 int CMerkleTx::GetBlocksToMaturity() const
3743 if (!IsCoinBase())
3744 return 0;
3745 return max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
3749 bool CMerkleTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
3751 return ::AcceptToMemoryPool(mempool, state, *this, true, NULL, false, nAbsurdFee);