Refactor Bumpfee core functionality
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blob186d3c5cd34ff169f0cb000e4898fe89fece5f13
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 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 "policy/rbf.h"
20 #include "primitives/block.h"
21 #include "primitives/transaction.h"
22 #include "script/script.h"
23 #include "script/sign.h"
24 #include "scheduler.h"
25 #include "timedata.h"
26 #include "txmempool.h"
27 #include "util.h"
28 #include "ui_interface.h"
29 #include "utilmoneystr.h"
31 #include <assert.h>
33 #include <boost/algorithm/string/replace.hpp>
34 #include <boost/filesystem.hpp>
35 #include <boost/thread.hpp>
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 fWalletRbf = DEFAULT_WALLET_RBF;
44 const char * DEFAULT_WALLET_DAT = "wallet.dat";
45 const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
47 /**
48 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
49 * Override with -mintxfee
51 CFeeRate CWallet::minTxFee = CFeeRate(DEFAULT_TRANSACTION_MINFEE);
52 /**
53 * If fee estimation does not have enough data to provide estimates, use this fee instead.
54 * Has no effect if not using fee estimation
55 * Override with -fallbackfee
57 CFeeRate CWallet::fallbackFee = CFeeRate(DEFAULT_FALLBACK_FEE);
59 const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
61 /** @defgroup mapWallet
63 * @{
66 struct CompareValueOnly
68 bool operator()(const std::pair<CAmount, std::pair<const CWalletTx*, unsigned int> >& t1,
69 const std::pair<CAmount, std::pair<const CWalletTx*, unsigned int> >& t2) const
71 return t1.first < t2.first;
75 std::string COutput::ToString() const
77 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
80 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
82 LOCK(cs_wallet);
83 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
84 if (it == mapWallet.end())
85 return NULL;
86 return &(it->second);
89 CPubKey CWallet::GenerateNewKey(bool internal)
91 AssertLockHeld(cs_wallet); // mapKeyMetadata
92 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
94 CKey secret;
96 // Create new metadata
97 int64_t nCreationTime = GetTime();
98 CKeyMetadata metadata(nCreationTime);
100 // use HD key derivation if HD was enabled during wallet creation
101 if (IsHDEnabled()) {
102 DeriveNewChildKey(metadata, secret, (CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
103 } else {
104 secret.MakeNewKey(fCompressed);
107 // Compressed public keys were introduced in version 0.6.0
108 if (fCompressed)
109 SetMinVersion(FEATURE_COMPRPUBKEY);
111 CPubKey pubkey = secret.GetPubKey();
112 assert(secret.VerifyPubKey(pubkey));
114 mapKeyMetadata[pubkey.GetID()] = metadata;
115 UpdateTimeFirstKey(nCreationTime);
117 if (!AddKeyPubKey(secret, pubkey))
118 throw std::runtime_error(std::string(__func__) + ": AddKey failed");
119 return pubkey;
122 void CWallet::DeriveNewChildKey(CKeyMetadata& metadata, CKey& secret, bool internal)
124 // for now we use a fixed keypath scheme of m/0'/0'/k
125 CKey key; //master key seed (256bit)
126 CExtKey masterKey; //hd master key
127 CExtKey accountKey; //key at m/0'
128 CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
129 CExtKey childKey; //key at m/0'/0'/<n>'
131 // try to get the master key
132 if (!GetKey(hdChain.masterKeyID, key))
133 throw std::runtime_error(std::string(__func__) + ": Master key not found");
135 masterKey.SetMaster(key.begin(), key.size());
137 // derive m/0'
138 // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
139 masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
141 // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
142 assert(internal ? CanSupportFeature(FEATURE_HD_SPLIT) : true);
143 accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
145 // derive child key at next index, skip keys already known to the wallet
146 do {
147 // always derive hardened keys
148 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
149 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
150 if (internal) {
151 chainChildKey.Derive(childKey, hdChain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
152 metadata.hdKeypath = "m/0'/1'/" + std::to_string(hdChain.nInternalChainCounter) + "'";
153 hdChain.nInternalChainCounter++;
155 else {
156 chainChildKey.Derive(childKey, hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
157 metadata.hdKeypath = "m/0'/0'/" + std::to_string(hdChain.nExternalChainCounter) + "'";
158 hdChain.nExternalChainCounter++;
160 } while (HaveKey(childKey.key.GetPubKey().GetID()));
161 secret = childKey.key;
162 metadata.hdMasterKeyID = hdChain.masterKeyID;
163 // update the chain model in the database
164 if (!CWalletDB(strWalletFile).WriteHDChain(hdChain))
165 throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
168 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
170 AssertLockHeld(cs_wallet); // mapKeyMetadata
171 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
172 return false;
174 // check if we need to remove from watch-only
175 CScript script;
176 script = GetScriptForDestination(pubkey.GetID());
177 if (HaveWatchOnly(script))
178 RemoveWatchOnly(script);
179 script = GetScriptForRawPubKey(pubkey);
180 if (HaveWatchOnly(script))
181 RemoveWatchOnly(script);
183 if (!fFileBacked)
184 return true;
185 if (!IsCrypted()) {
186 return CWalletDB(strWalletFile).WriteKey(pubkey,
187 secret.GetPrivKey(),
188 mapKeyMetadata[pubkey.GetID()]);
190 return true;
193 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
194 const std::vector<unsigned char> &vchCryptedSecret)
196 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
197 return false;
198 if (!fFileBacked)
199 return true;
201 LOCK(cs_wallet);
202 if (pwalletdbEncryption)
203 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
204 vchCryptedSecret,
205 mapKeyMetadata[vchPubKey.GetID()]);
206 else
207 return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey,
208 vchCryptedSecret,
209 mapKeyMetadata[vchPubKey.GetID()]);
211 return false;
214 bool CWallet::LoadKeyMetadata(const CTxDestination& keyID, const CKeyMetadata &meta)
216 AssertLockHeld(cs_wallet); // mapKeyMetadata
217 UpdateTimeFirstKey(meta.nCreateTime);
218 mapKeyMetadata[keyID] = meta;
219 return true;
222 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
224 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
227 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
229 AssertLockHeld(cs_wallet);
230 if (nCreateTime <= 1) {
231 // Cannot determine birthday information, so set the wallet birthday to
232 // the beginning of time.
233 nTimeFirstKey = 1;
234 } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
235 nTimeFirstKey = nCreateTime;
239 bool CWallet::AddCScript(const CScript& redeemScript)
241 if (!CCryptoKeyStore::AddCScript(redeemScript))
242 return false;
243 if (!fFileBacked)
244 return true;
245 return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript);
248 bool CWallet::LoadCScript(const CScript& redeemScript)
250 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
251 * that never can be redeemed. However, old wallets may still contain
252 * these. Do not add them to the wallet and warn. */
253 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
255 std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
256 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",
257 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
258 return true;
261 return CCryptoKeyStore::AddCScript(redeemScript);
264 bool CWallet::AddWatchOnly(const CScript& dest)
266 if (!CCryptoKeyStore::AddWatchOnly(dest))
267 return false;
268 const CKeyMetadata& meta = mapKeyMetadata[CScriptID(dest)];
269 UpdateTimeFirstKey(meta.nCreateTime);
270 NotifyWatchonlyChanged(true);
271 if (!fFileBacked)
272 return true;
273 return CWalletDB(strWalletFile).WriteWatchOnly(dest, meta);
276 bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
278 mapKeyMetadata[CScriptID(dest)].nCreateTime = nCreateTime;
279 return AddWatchOnly(dest);
282 bool CWallet::RemoveWatchOnly(const CScript &dest)
284 AssertLockHeld(cs_wallet);
285 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
286 return false;
287 if (!HaveWatchOnly())
288 NotifyWatchonlyChanged(false);
289 if (fFileBacked)
290 if (!CWalletDB(strWalletFile).EraseWatchOnly(dest))
291 return false;
293 return true;
296 bool CWallet::LoadWatchOnly(const CScript &dest)
298 return CCryptoKeyStore::AddWatchOnly(dest);
301 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
303 CCrypter crypter;
304 CKeyingMaterial _vMasterKey;
307 LOCK(cs_wallet);
308 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
310 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
311 return false;
312 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
313 continue; // try another master key
314 if (CCryptoKeyStore::Unlock(_vMasterKey))
315 return true;
318 return false;
321 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
323 bool fWasLocked = IsLocked();
326 LOCK(cs_wallet);
327 Lock();
329 CCrypter crypter;
330 CKeyingMaterial _vMasterKey;
331 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
333 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
334 return false;
335 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
336 return false;
337 if (CCryptoKeyStore::Unlock(_vMasterKey))
339 int64_t nStartTime = GetTimeMillis();
340 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
341 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
343 nStartTime = GetTimeMillis();
344 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
345 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
347 if (pMasterKey.second.nDeriveIterations < 25000)
348 pMasterKey.second.nDeriveIterations = 25000;
350 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
352 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
353 return false;
354 if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
355 return false;
356 CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second);
357 if (fWasLocked)
358 Lock();
359 return true;
364 return false;
367 void CWallet::SetBestChain(const CBlockLocator& loc)
369 CWalletDB walletdb(strWalletFile);
370 walletdb.WriteBestBlock(loc);
373 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
375 LOCK(cs_wallet); // nWalletVersion
376 if (nWalletVersion >= nVersion)
377 return true;
379 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
380 if (fExplicit && nVersion > nWalletMaxVersion)
381 nVersion = FEATURE_LATEST;
383 nWalletVersion = nVersion;
385 if (nVersion > nWalletMaxVersion)
386 nWalletMaxVersion = nVersion;
388 if (fFileBacked)
390 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile);
391 if (nWalletVersion > 40000)
392 pwalletdb->WriteMinVersion(nWalletVersion);
393 if (!pwalletdbIn)
394 delete pwalletdb;
397 return true;
400 bool CWallet::SetMaxVersion(int nVersion)
402 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
403 // cannot downgrade below current version
404 if (nWalletVersion > nVersion)
405 return false;
407 nWalletMaxVersion = nVersion;
409 return true;
412 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
414 std::set<uint256> result;
415 AssertLockHeld(cs_wallet);
417 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
418 if (it == mapWallet.end())
419 return result;
420 const CWalletTx& wtx = it->second;
422 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
424 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
426 if (mapTxSpends.count(txin.prevout) <= 1)
427 continue; // No conflict if zero or one spends
428 range = mapTxSpends.equal_range(txin.prevout);
429 for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
430 result.insert(_it->second);
432 return result;
435 bool CWallet::HasWalletSpend(const uint256& txid) const
437 AssertLockHeld(cs_wallet);
438 auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
439 return (iter != mapTxSpends.end() && iter->first.hash == txid);
442 void CWallet::Flush(bool shutdown)
444 bitdb.Flush(shutdown);
447 bool CWallet::Verify()
449 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
450 return true;
452 uiInterface.InitMessage(_("Verifying wallet..."));
453 std::string walletFile = GetArg("-wallet", DEFAULT_WALLET_DAT);
455 std::string strError;
456 if (!CWalletDB::VerifyEnvironment(walletFile, GetDataDir().string(), strError))
457 return InitError(strError);
459 if (GetBoolArg("-salvagewallet", false))
461 // Recover readable keypairs:
462 CWallet dummyWallet;
463 if (!CWalletDB::Recover(walletFile, (void *)&dummyWallet, CWalletDB::RecoverKeysOnlyFilter))
464 return false;
467 std::string strWarning;
468 bool dbV = CWalletDB::VerifyDatabaseFile(walletFile, GetDataDir().string(), strWarning, strError);
469 if (!strWarning.empty())
470 InitWarning(strWarning);
471 if (!dbV)
473 InitError(strError);
474 return false;
476 return true;
479 void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
481 // We want all the wallet transactions in range to have the same metadata as
482 // the oldest (smallest nOrderPos).
483 // So: find smallest nOrderPos:
485 int nMinOrderPos = std::numeric_limits<int>::max();
486 const CWalletTx* copyFrom = NULL;
487 for (TxSpends::iterator it = range.first; it != range.second; ++it)
489 const uint256& hash = it->second;
490 int n = mapWallet[hash].nOrderPos;
491 if (n < nMinOrderPos)
493 nMinOrderPos = n;
494 copyFrom = &mapWallet[hash];
497 // Now copy data from copyFrom to rest:
498 for (TxSpends::iterator it = range.first; it != range.second; ++it)
500 const uint256& hash = it->second;
501 CWalletTx* copyTo = &mapWallet[hash];
502 if (copyFrom == copyTo) continue;
503 if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
504 copyTo->mapValue = copyFrom->mapValue;
505 copyTo->vOrderForm = copyFrom->vOrderForm;
506 // fTimeReceivedIsTxTime not copied on purpose
507 // nTimeReceived not copied on purpose
508 copyTo->nTimeSmart = copyFrom->nTimeSmart;
509 copyTo->fFromMe = copyFrom->fFromMe;
510 copyTo->strFromAccount = copyFrom->strFromAccount;
511 // nOrderPos not copied on purpose
512 // cached members not copied on purpose
517 * Outpoint is spent if any non-conflicted transaction
518 * spends it:
520 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
522 const COutPoint outpoint(hash, n);
523 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
524 range = mapTxSpends.equal_range(outpoint);
526 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
528 const uint256& wtxid = it->second;
529 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
530 if (mit != mapWallet.end()) {
531 int depth = mit->second.GetDepthInMainChain();
532 if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
533 return true; // Spent
536 return false;
539 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
541 mapTxSpends.insert(std::make_pair(outpoint, wtxid));
543 std::pair<TxSpends::iterator, TxSpends::iterator> range;
544 range = mapTxSpends.equal_range(outpoint);
545 SyncMetaData(range);
549 void CWallet::AddToSpends(const uint256& wtxid)
551 assert(mapWallet.count(wtxid));
552 CWalletTx& thisTx = mapWallet[wtxid];
553 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
554 return;
556 BOOST_FOREACH(const CTxIn& txin, thisTx.tx->vin)
557 AddToSpends(txin.prevout, wtxid);
560 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
562 if (IsCrypted())
563 return false;
565 CKeyingMaterial _vMasterKey;
567 _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
568 GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
570 CMasterKey kMasterKey;
572 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
573 GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
575 CCrypter crypter;
576 int64_t nStartTime = GetTimeMillis();
577 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
578 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
580 nStartTime = GetTimeMillis();
581 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
582 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
584 if (kMasterKey.nDeriveIterations < 25000)
585 kMasterKey.nDeriveIterations = 25000;
587 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
589 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
590 return false;
591 if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
592 return false;
595 LOCK(cs_wallet);
596 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
597 if (fFileBacked)
599 assert(!pwalletdbEncryption);
600 pwalletdbEncryption = new CWalletDB(strWalletFile);
601 if (!pwalletdbEncryption->TxnBegin()) {
602 delete pwalletdbEncryption;
603 pwalletdbEncryption = NULL;
604 return false;
606 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
609 if (!EncryptKeys(_vMasterKey))
611 if (fFileBacked) {
612 pwalletdbEncryption->TxnAbort();
613 delete pwalletdbEncryption;
615 // We now probably have half of our keys encrypted in memory, and half not...
616 // die and let the user reload the unencrypted wallet.
617 assert(false);
620 // Encryption was introduced in version 0.4.0
621 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
623 if (fFileBacked)
625 if (!pwalletdbEncryption->TxnCommit()) {
626 delete pwalletdbEncryption;
627 // We now have keys encrypted in memory, but not on disk...
628 // die to avoid confusion and let the user reload the unencrypted wallet.
629 assert(false);
632 delete pwalletdbEncryption;
633 pwalletdbEncryption = NULL;
636 Lock();
637 Unlock(strWalletPassphrase);
639 // if we are using HD, replace the HD master key (seed) with a new one
640 if (IsHDEnabled()) {
641 CKey key;
642 CPubKey masterPubKey = GenerateNewHDMasterKey();
643 // preserve the old chains version to not break backward compatibility
644 CHDChain oldChain = GetHDChain();
645 if (!SetHDMasterKey(masterPubKey, &oldChain))
646 return false;
649 NewKeyPool();
650 Lock();
652 // Need to completely rewrite the wallet file; if we don't, bdb might keep
653 // bits of the unencrypted private key in slack space in the database file.
654 CDB::Rewrite(strWalletFile);
657 NotifyStatusChanged(this);
659 return true;
662 DBErrors CWallet::ReorderTransactions()
664 LOCK(cs_wallet);
665 CWalletDB walletdb(strWalletFile);
667 // Old wallets didn't have any defined order for transactions
668 // Probably a bad idea to change the output of this
670 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
671 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
672 typedef std::multimap<int64_t, TxPair > TxItems;
673 TxItems txByTime;
675 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
677 CWalletTx* wtx = &((*it).second);
678 txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
680 std::list<CAccountingEntry> acentries;
681 walletdb.ListAccountCreditDebit("", acentries);
682 BOOST_FOREACH(CAccountingEntry& entry, acentries)
684 txByTime.insert(std::make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
687 nOrderPosNext = 0;
688 std::vector<int64_t> nOrderPosOffsets;
689 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
691 CWalletTx *const pwtx = (*it).second.first;
692 CAccountingEntry *const pacentry = (*it).second.second;
693 int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
695 if (nOrderPos == -1)
697 nOrderPos = nOrderPosNext++;
698 nOrderPosOffsets.push_back(nOrderPos);
700 if (pwtx)
702 if (!walletdb.WriteTx(*pwtx))
703 return DB_LOAD_FAIL;
705 else
706 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
707 return DB_LOAD_FAIL;
709 else
711 int64_t nOrderPosOff = 0;
712 BOOST_FOREACH(const int64_t& nOffsetStart, nOrderPosOffsets)
714 if (nOrderPos >= nOffsetStart)
715 ++nOrderPosOff;
717 nOrderPos += nOrderPosOff;
718 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
720 if (!nOrderPosOff)
721 continue;
723 // Since we're changing the order, write it back
724 if (pwtx)
726 if (!walletdb.WriteTx(*pwtx))
727 return DB_LOAD_FAIL;
729 else
730 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
731 return DB_LOAD_FAIL;
734 walletdb.WriteOrderPosNext(nOrderPosNext);
736 return DB_LOAD_OK;
739 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
741 AssertLockHeld(cs_wallet); // nOrderPosNext
742 int64_t nRet = nOrderPosNext++;
743 if (pwalletdb) {
744 pwalletdb->WriteOrderPosNext(nOrderPosNext);
745 } else {
746 CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext);
748 return nRet;
751 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
753 CWalletDB walletdb(strWalletFile);
754 if (!walletdb.TxnBegin())
755 return false;
757 int64_t nNow = GetAdjustedTime();
759 // Debit
760 CAccountingEntry debit;
761 debit.nOrderPos = IncOrderPosNext(&walletdb);
762 debit.strAccount = strFrom;
763 debit.nCreditDebit = -nAmount;
764 debit.nTime = nNow;
765 debit.strOtherAccount = strTo;
766 debit.strComment = strComment;
767 AddAccountingEntry(debit, &walletdb);
769 // Credit
770 CAccountingEntry credit;
771 credit.nOrderPos = IncOrderPosNext(&walletdb);
772 credit.strAccount = strTo;
773 credit.nCreditDebit = nAmount;
774 credit.nTime = nNow;
775 credit.strOtherAccount = strFrom;
776 credit.strComment = strComment;
777 AddAccountingEntry(credit, &walletdb);
779 if (!walletdb.TxnCommit())
780 return false;
782 return true;
785 bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
787 CWalletDB walletdb(strWalletFile);
789 CAccount account;
790 walletdb.ReadAccount(strAccount, account);
792 if (!bForceNew) {
793 if (!account.vchPubKey.IsValid())
794 bForceNew = true;
795 else {
796 // Check if the current key has been used
797 CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
798 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
799 it != mapWallet.end() && account.vchPubKey.IsValid();
800 ++it)
801 BOOST_FOREACH(const CTxOut& txout, (*it).second.tx->vout)
802 if (txout.scriptPubKey == scriptPubKey) {
803 bForceNew = true;
804 break;
809 // Generate a new key
810 if (bForceNew) {
811 if (!GetKeyFromPool(account.vchPubKey, false))
812 return false;
814 SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
815 walletdb.WriteAccount(strAccount, account);
818 pubKey = account.vchPubKey;
820 return true;
823 void CWallet::MarkDirty()
826 LOCK(cs_wallet);
827 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
828 item.second.MarkDirty();
832 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
834 LOCK(cs_wallet);
836 auto mi = mapWallet.find(originalHash);
838 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
839 assert(mi != mapWallet.end());
841 CWalletTx& wtx = (*mi).second;
843 // Ensure for now that we're not overwriting data
844 assert(wtx.mapValue.count("replaced_by_txid") == 0);
846 wtx.mapValue["replaced_by_txid"] = newHash.ToString();
848 CWalletDB walletdb(strWalletFile, "r+");
850 bool success = true;
851 if (!walletdb.WriteTx(wtx)) {
852 LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
853 success = false;
856 NotifyTransactionChanged(this, originalHash, CT_UPDATED);
858 return success;
861 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
863 LOCK(cs_wallet);
865 CWalletDB walletdb(strWalletFile, "r+", fFlushOnClose);
867 uint256 hash = wtxIn.GetHash();
869 // Inserts only if not already there, returns tx inserted or tx found
870 std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
871 CWalletTx& wtx = (*ret.first).second;
872 wtx.BindWallet(this);
873 bool fInsertedNew = ret.second;
874 if (fInsertedNew)
876 wtx.nTimeReceived = GetAdjustedTime();
877 wtx.nOrderPos = IncOrderPosNext(&walletdb);
878 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
879 wtx.nTimeSmart = ComputeTimeSmart(wtx);
880 AddToSpends(hash);
883 bool fUpdated = false;
884 if (!fInsertedNew)
886 // Merge
887 if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
889 wtx.hashBlock = wtxIn.hashBlock;
890 fUpdated = true;
892 // If no longer abandoned, update
893 if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
895 wtx.hashBlock = wtxIn.hashBlock;
896 fUpdated = true;
898 if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
900 wtx.nIndex = wtxIn.nIndex;
901 fUpdated = true;
903 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
905 wtx.fFromMe = wtxIn.fFromMe;
906 fUpdated = true;
910 //// debug print
911 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
913 // Write to disk
914 if (fInsertedNew || fUpdated)
915 if (!walletdb.WriteTx(wtx))
916 return false;
918 // Break debit/credit balance caches:
919 wtx.MarkDirty();
921 // Notify UI of new or updated transaction
922 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
924 // notify an external script when a wallet transaction comes in or is updated
925 std::string strCmd = GetArg("-walletnotify", "");
927 if ( !strCmd.empty())
929 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
930 boost::thread t(runCommand, strCmd); // thread runs free
933 return true;
936 bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
938 uint256 hash = wtxIn.GetHash();
940 mapWallet[hash] = wtxIn;
941 CWalletTx& wtx = mapWallet[hash];
942 wtx.BindWallet(this);
943 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
944 AddToSpends(hash);
945 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin) {
946 if (mapWallet.count(txin.prevout.hash)) {
947 CWalletTx& prevtx = mapWallet[txin.prevout.hash];
948 if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
949 MarkConflicted(prevtx.hashBlock, wtx.GetHash());
954 return true;
958 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
959 * be set when the transaction was known to be included in a block. When
960 * posInBlock = SYNC_TRANSACTION_NOT_IN_BLOCK (-1) , then wallet state is not
961 * updated in AddToWallet, but notifications happen and cached balances are
962 * marked dirty.
963 * If fUpdate is true, existing transactions will be updated.
964 * TODO: One exception to this is that the abandoned state is cleared under the
965 * assumption that any further notification of a transaction that was considered
966 * abandoned is an indication that it is not safe to be considered abandoned.
967 * Abandoned state should probably be more carefully tracked via different
968 * posInBlock signals or by checking mempool presence when necessary.
970 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
973 AssertLockHeld(cs_wallet);
975 if (posInBlock != -1) {
976 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
977 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
978 while (range.first != range.second) {
979 if (range.first->second != tx.GetHash()) {
980 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);
981 MarkConflicted(pIndex->GetBlockHash(), range.first->second);
983 range.first++;
988 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
989 if (fExisted && !fUpdate) return false;
990 if (fExisted || IsMine(tx) || IsFromMe(tx))
992 CWalletTx wtx(this, MakeTransactionRef(tx));
994 // Get merkle branch if transaction was found in a block
995 if (posInBlock != -1)
996 wtx.SetMerkleBranch(pIndex, posInBlock);
998 return AddToWallet(wtx, false);
1001 return false;
1004 bool CWallet::AbandonTransaction(const uint256& hashTx)
1006 LOCK2(cs_main, cs_wallet);
1008 CWalletDB walletdb(strWalletFile, "r+");
1010 std::set<uint256> todo;
1011 std::set<uint256> done;
1013 // Can't mark abandoned if confirmed or in mempool
1014 assert(mapWallet.count(hashTx));
1015 CWalletTx& origtx = mapWallet[hashTx];
1016 if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
1017 return false;
1020 todo.insert(hashTx);
1022 while (!todo.empty()) {
1023 uint256 now = *todo.begin();
1024 todo.erase(now);
1025 done.insert(now);
1026 assert(mapWallet.count(now));
1027 CWalletTx& wtx = mapWallet[now];
1028 int currentconfirm = wtx.GetDepthInMainChain();
1029 // If the orig tx was not in block, none of its spends can be
1030 assert(currentconfirm <= 0);
1031 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1032 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1033 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1034 assert(!wtx.InMempool());
1035 wtx.nIndex = -1;
1036 wtx.setAbandoned();
1037 wtx.MarkDirty();
1038 walletdb.WriteTx(wtx);
1039 NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1040 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1041 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1042 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1043 if (!done.count(iter->second)) {
1044 todo.insert(iter->second);
1046 iter++;
1048 // If a transaction changes 'conflicted' state, that changes the balance
1049 // available of the outputs it spends. So force those to be recomputed
1050 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
1052 if (mapWallet.count(txin.prevout.hash))
1053 mapWallet[txin.prevout.hash].MarkDirty();
1058 return true;
1061 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1063 LOCK2(cs_main, cs_wallet);
1065 int conflictconfirms = 0;
1066 if (mapBlockIndex.count(hashBlock)) {
1067 CBlockIndex* pindex = mapBlockIndex[hashBlock];
1068 if (chainActive.Contains(pindex)) {
1069 conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1072 // If number of conflict confirms cannot be determined, this means
1073 // that the block is still unknown or not yet part of the main chain,
1074 // for example when loading the wallet during a reindex. Do nothing in that
1075 // case.
1076 if (conflictconfirms >= 0)
1077 return;
1079 // Do not flush the wallet here for performance reasons
1080 CWalletDB walletdb(strWalletFile, "r+", false);
1082 std::set<uint256> todo;
1083 std::set<uint256> done;
1085 todo.insert(hashTx);
1087 while (!todo.empty()) {
1088 uint256 now = *todo.begin();
1089 todo.erase(now);
1090 done.insert(now);
1091 assert(mapWallet.count(now));
1092 CWalletTx& wtx = mapWallet[now];
1093 int currentconfirm = wtx.GetDepthInMainChain();
1094 if (conflictconfirms < currentconfirm) {
1095 // Block is 'more conflicted' than current confirm; update.
1096 // Mark transaction as conflicted with this block.
1097 wtx.nIndex = -1;
1098 wtx.hashBlock = hashBlock;
1099 wtx.MarkDirty();
1100 walletdb.WriteTx(wtx);
1101 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1102 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1103 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1104 if (!done.count(iter->second)) {
1105 todo.insert(iter->second);
1107 iter++;
1109 // If a transaction changes 'conflicted' state, that changes the balance
1110 // available of the outputs it spends. So force those to be recomputed
1111 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
1113 if (mapWallet.count(txin.prevout.hash))
1114 mapWallet[txin.prevout.hash].MarkDirty();
1120 void CWallet::SyncTransaction(const CTransaction& tx, const CBlockIndex *pindex, int posInBlock)
1122 LOCK2(cs_main, cs_wallet);
1124 if (!AddToWalletIfInvolvingMe(tx, pindex, posInBlock, true))
1125 return; // Not one of ours
1127 // If a transaction changes 'conflicted' state, that changes the balance
1128 // available of the outputs it spends. So force those to be
1129 // recomputed, also:
1130 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1132 if (mapWallet.count(txin.prevout.hash))
1133 mapWallet[txin.prevout.hash].MarkDirty();
1138 isminetype CWallet::IsMine(const CTxIn &txin) const
1141 LOCK(cs_wallet);
1142 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1143 if (mi != mapWallet.end())
1145 const CWalletTx& prev = (*mi).second;
1146 if (txin.prevout.n < prev.tx->vout.size())
1147 return IsMine(prev.tx->vout[txin.prevout.n]);
1150 return ISMINE_NO;
1153 // Note that this function doesn't distinguish between a 0-valued input,
1154 // and a not-"is mine" (according to the filter) input.
1155 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1158 LOCK(cs_wallet);
1159 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1160 if (mi != mapWallet.end())
1162 const CWalletTx& prev = (*mi).second;
1163 if (txin.prevout.n < prev.tx->vout.size())
1164 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1165 return prev.tx->vout[txin.prevout.n].nValue;
1168 return 0;
1171 isminetype CWallet::IsMine(const CTxOut& txout) const
1173 return ::IsMine(*this, txout.scriptPubKey);
1176 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1178 if (!MoneyRange(txout.nValue))
1179 throw std::runtime_error(std::string(__func__) + ": value out of range");
1180 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1183 bool CWallet::IsChange(const CTxOut& txout) const
1185 // TODO: fix handling of 'change' outputs. The assumption is that any
1186 // payment to a script that is ours, but is not in the address book
1187 // is change. That assumption is likely to break when we implement multisignature
1188 // wallets that return change back into a multi-signature-protected address;
1189 // a better way of identifying which outputs are 'the send' and which are
1190 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1191 // which output, if any, was change).
1192 if (::IsMine(*this, txout.scriptPubKey))
1194 CTxDestination address;
1195 if (!ExtractDestination(txout.scriptPubKey, address))
1196 return true;
1198 LOCK(cs_wallet);
1199 if (!mapAddressBook.count(address))
1200 return true;
1202 return false;
1205 CAmount CWallet::GetChange(const CTxOut& txout) const
1207 if (!MoneyRange(txout.nValue))
1208 throw std::runtime_error(std::string(__func__) + ": value out of range");
1209 return (IsChange(txout) ? txout.nValue : 0);
1212 bool CWallet::IsMine(const CTransaction& tx) const
1214 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1215 if (IsMine(txout))
1216 return true;
1217 return false;
1220 bool CWallet::IsFromMe(const CTransaction& tx) const
1222 return (GetDebit(tx, ISMINE_ALL) > 0);
1225 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1227 CAmount nDebit = 0;
1228 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1230 nDebit += GetDebit(txin, filter);
1231 if (!MoneyRange(nDebit))
1232 throw std::runtime_error(std::string(__func__) + ": value out of range");
1234 return nDebit;
1237 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1239 LOCK(cs_wallet);
1241 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1243 auto mi = mapWallet.find(txin.prevout.hash);
1244 if (mi == mapWallet.end())
1245 return false; // any unknown inputs can't be from us
1247 const CWalletTx& prev = (*mi).second;
1249 if (txin.prevout.n >= prev.tx->vout.size())
1250 return false; // invalid input!
1252 if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1253 return false;
1255 return true;
1258 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1260 CAmount nCredit = 0;
1261 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1263 nCredit += GetCredit(txout, filter);
1264 if (!MoneyRange(nCredit))
1265 throw std::runtime_error(std::string(__func__) + ": value out of range");
1267 return nCredit;
1270 CAmount CWallet::GetChange(const CTransaction& tx) const
1272 CAmount nChange = 0;
1273 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1275 nChange += GetChange(txout);
1276 if (!MoneyRange(nChange))
1277 throw std::runtime_error(std::string(__func__) + ": value out of range");
1279 return nChange;
1282 CPubKey CWallet::GenerateNewHDMasterKey()
1284 CKey key;
1285 key.MakeNewKey(true);
1287 int64_t nCreationTime = GetTime();
1288 CKeyMetadata metadata(nCreationTime);
1290 // calculate the pubkey
1291 CPubKey pubkey = key.GetPubKey();
1292 assert(key.VerifyPubKey(pubkey));
1294 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1295 metadata.hdKeypath = "m";
1296 metadata.hdMasterKeyID = pubkey.GetID();
1299 LOCK(cs_wallet);
1301 // mem store the metadata
1302 mapKeyMetadata[pubkey.GetID()] = metadata;
1304 // write the key&metadata to the database
1305 if (!AddKeyPubKey(key, pubkey))
1306 throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1309 return pubkey;
1312 bool CWallet::SetHDMasterKey(const CPubKey& pubkey, CHDChain *possibleOldChain)
1314 LOCK(cs_wallet);
1315 // store the keyid (hash160) together with
1316 // the child index counter in the database
1317 // as a hdchain object
1318 CHDChain newHdChain;
1319 if (possibleOldChain) {
1320 // preserve the old chains version
1321 newHdChain.nVersion = possibleOldChain->nVersion;
1323 newHdChain.masterKeyID = pubkey.GetID();
1324 SetHDChain(newHdChain, false);
1326 return true;
1329 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1331 LOCK(cs_wallet);
1332 if (!memonly && !CWalletDB(strWalletFile).WriteHDChain(chain))
1333 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1335 hdChain = chain;
1336 return true;
1339 bool CWallet::IsHDEnabled() const
1341 return !hdChain.masterKeyID.IsNull();
1344 int64_t CWalletTx::GetTxTime() const
1346 int64_t n = nTimeSmart;
1347 return n ? n : nTimeReceived;
1350 int CWalletTx::GetRequestCount() const
1352 // Returns -1 if it wasn't being tracked
1353 int nRequests = -1;
1355 LOCK(pwallet->cs_wallet);
1356 if (IsCoinBase())
1358 // Generated block
1359 if (!hashUnset())
1361 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1362 if (mi != pwallet->mapRequestCount.end())
1363 nRequests = (*mi).second;
1366 else
1368 // Did anyone request this transaction?
1369 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1370 if (mi != pwallet->mapRequestCount.end())
1372 nRequests = (*mi).second;
1374 // How about the block it's in?
1375 if (nRequests == 0 && !hashUnset())
1377 std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1378 if (_mi != pwallet->mapRequestCount.end())
1379 nRequests = (*_mi).second;
1380 else
1381 nRequests = 1; // If it's in someone else's block it must have got out
1386 return nRequests;
1389 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1390 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1392 nFee = 0;
1393 listReceived.clear();
1394 listSent.clear();
1395 strSentAccount = strFromAccount;
1397 // Compute fee:
1398 CAmount nDebit = GetDebit(filter);
1399 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1401 CAmount nValueOut = tx->GetValueOut();
1402 nFee = nDebit - nValueOut;
1405 // Sent/received.
1406 for (unsigned int i = 0; i < tx->vout.size(); ++i)
1408 const CTxOut& txout = tx->vout[i];
1409 isminetype fIsMine = pwallet->IsMine(txout);
1410 // Only need to handle txouts if AT LEAST one of these is true:
1411 // 1) they debit from us (sent)
1412 // 2) the output is to us (received)
1413 if (nDebit > 0)
1415 // Don't report 'change' txouts
1416 if (pwallet->IsChange(txout))
1417 continue;
1419 else if (!(fIsMine & filter))
1420 continue;
1422 // In either case, we need to get the destination address
1423 CTxDestination address;
1425 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1427 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1428 this->GetHash().ToString());
1429 address = CNoDestination();
1432 COutputEntry output = {address, txout.nValue, (int)i};
1434 // If we are debited by the transaction, add the output as a "sent" entry
1435 if (nDebit > 0)
1436 listSent.push_back(output);
1438 // If we are receiving the output, add it as a "received" entry
1439 if (fIsMine & filter)
1440 listReceived.push_back(output);
1445 void CWalletTx::GetAccountAmounts(const std::string& strAccount, CAmount& nReceived,
1446 CAmount& nSent, CAmount& nFee, const isminefilter& filter) const
1448 nReceived = nSent = nFee = 0;
1450 CAmount allFee;
1451 std::string strSentAccount;
1452 std::list<COutputEntry> listReceived;
1453 std::list<COutputEntry> listSent;
1454 GetAmounts(listReceived, listSent, allFee, strSentAccount, filter);
1456 if (strAccount == strSentAccount)
1458 BOOST_FOREACH(const COutputEntry& s, listSent)
1459 nSent += s.amount;
1460 nFee = allFee;
1463 LOCK(pwallet->cs_wallet);
1464 BOOST_FOREACH(const COutputEntry& r, listReceived)
1466 if (pwallet->mapAddressBook.count(r.destination))
1468 std::map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination);
1469 if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount)
1470 nReceived += r.amount;
1472 else if (strAccount.empty())
1474 nReceived += r.amount;
1481 * Scan the block chain (starting in pindexStart) for transactions
1482 * from or to us. If fUpdate is true, found transactions that already
1483 * exist in the wallet will be updated.
1485 * Returns pointer to the first block in the last contiguous range that was
1486 * successfully scanned.
1489 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1491 CBlockIndex* ret = nullptr;
1492 int64_t nNow = GetTime();
1493 const CChainParams& chainParams = Params();
1495 CBlockIndex* pindex = pindexStart;
1497 LOCK2(cs_main, cs_wallet);
1499 // no need to read and scan block, if block was created before
1500 // our wallet birthday (as adjusted for block time variability)
1501 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - TIMESTAMP_WINDOW)))
1502 pindex = chainActive.Next(pindex);
1504 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1505 double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
1506 double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
1507 while (pindex)
1509 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1510 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1512 CBlock block;
1513 if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
1514 for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1515 AddToWalletIfInvolvingMe(*block.vtx[posInBlock], pindex, posInBlock, fUpdate);
1517 if (!ret) {
1518 ret = pindex;
1520 } else {
1521 ret = nullptr;
1523 pindex = chainActive.Next(pindex);
1524 if (GetTime() >= nNow + 60) {
1525 nNow = GetTime();
1526 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1529 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1531 return ret;
1534 void CWallet::ReacceptWalletTransactions()
1536 // If transactions aren't being broadcasted, don't let them into local mempool either
1537 if (!fBroadcastTransactions)
1538 return;
1539 LOCK2(cs_main, cs_wallet);
1540 std::map<int64_t, CWalletTx*> mapSorted;
1542 // Sort pending wallet transactions based on their initial wallet insertion order
1543 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1545 const uint256& wtxid = item.first;
1546 CWalletTx& wtx = item.second;
1547 assert(wtx.GetHash() == wtxid);
1549 int nDepth = wtx.GetDepthInMainChain();
1551 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1552 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1556 // Try to add wallet transactions to memory pool
1557 BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
1559 CWalletTx& wtx = *(item.second);
1561 LOCK(mempool.cs);
1562 CValidationState state;
1563 wtx.AcceptToMemoryPool(maxTxFee, state);
1567 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1569 assert(pwallet->GetBroadcastTransactions());
1570 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1572 CValidationState state;
1573 /* GetDepthInMainChain already catches known conflicts. */
1574 if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1575 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1576 if (connman) {
1577 CInv inv(MSG_TX, GetHash());
1578 connman->ForEachNode([&inv](CNode* pnode)
1580 pnode->PushInventory(inv);
1582 return true;
1586 return false;
1589 std::set<uint256> CWalletTx::GetConflicts() const
1591 std::set<uint256> result;
1592 if (pwallet != NULL)
1594 uint256 myHash = GetHash();
1595 result = pwallet->GetConflicts(myHash);
1596 result.erase(myHash);
1598 return result;
1601 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1603 if (tx->vin.empty())
1604 return 0;
1606 CAmount debit = 0;
1607 if(filter & ISMINE_SPENDABLE)
1609 if (fDebitCached)
1610 debit += nDebitCached;
1611 else
1613 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1614 fDebitCached = true;
1615 debit += nDebitCached;
1618 if(filter & ISMINE_WATCH_ONLY)
1620 if(fWatchDebitCached)
1621 debit += nWatchDebitCached;
1622 else
1624 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1625 fWatchDebitCached = true;
1626 debit += nWatchDebitCached;
1629 return debit;
1632 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1634 // Must wait until coinbase is safely deep enough in the chain before valuing it
1635 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1636 return 0;
1638 CAmount credit = 0;
1639 if (filter & ISMINE_SPENDABLE)
1641 // GetBalance can assume transactions in mapWallet won't change
1642 if (fCreditCached)
1643 credit += nCreditCached;
1644 else
1646 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1647 fCreditCached = true;
1648 credit += nCreditCached;
1651 if (filter & ISMINE_WATCH_ONLY)
1653 if (fWatchCreditCached)
1654 credit += nWatchCreditCached;
1655 else
1657 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1658 fWatchCreditCached = true;
1659 credit += nWatchCreditCached;
1662 return credit;
1665 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1667 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1669 if (fUseCache && fImmatureCreditCached)
1670 return nImmatureCreditCached;
1671 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1672 fImmatureCreditCached = true;
1673 return nImmatureCreditCached;
1676 return 0;
1679 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1681 if (pwallet == 0)
1682 return 0;
1684 // Must wait until coinbase is safely deep enough in the chain before valuing it
1685 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1686 return 0;
1688 if (fUseCache && fAvailableCreditCached)
1689 return nAvailableCreditCached;
1691 CAmount nCredit = 0;
1692 uint256 hashTx = GetHash();
1693 for (unsigned int i = 0; i < tx->vout.size(); i++)
1695 if (!pwallet->IsSpent(hashTx, i))
1697 const CTxOut &txout = tx->vout[i];
1698 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1699 if (!MoneyRange(nCredit))
1700 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1704 nAvailableCreditCached = nCredit;
1705 fAvailableCreditCached = true;
1706 return nCredit;
1709 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1711 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1713 if (fUseCache && fImmatureWatchCreditCached)
1714 return nImmatureWatchCreditCached;
1715 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1716 fImmatureWatchCreditCached = true;
1717 return nImmatureWatchCreditCached;
1720 return 0;
1723 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1725 if (pwallet == 0)
1726 return 0;
1728 // Must wait until coinbase is safely deep enough in the chain before valuing it
1729 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1730 return 0;
1732 if (fUseCache && fAvailableWatchCreditCached)
1733 return nAvailableWatchCreditCached;
1735 CAmount nCredit = 0;
1736 for (unsigned int i = 0; i < tx->vout.size(); i++)
1738 if (!pwallet->IsSpent(GetHash(), i))
1740 const CTxOut &txout = tx->vout[i];
1741 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1742 if (!MoneyRange(nCredit))
1743 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1747 nAvailableWatchCreditCached = nCredit;
1748 fAvailableWatchCreditCached = true;
1749 return nCredit;
1752 CAmount CWalletTx::GetChange() const
1754 if (fChangeCached)
1755 return nChangeCached;
1756 nChangeCached = pwallet->GetChange(*this);
1757 fChangeCached = true;
1758 return nChangeCached;
1761 bool CWalletTx::InMempool() const
1763 LOCK(mempool.cs);
1764 if (mempool.exists(GetHash())) {
1765 return true;
1767 return false;
1770 bool CWalletTx::IsTrusted() const
1772 // Quick answer in most cases
1773 if (!CheckFinalTx(*this))
1774 return false;
1775 int nDepth = GetDepthInMainChain();
1776 if (nDepth >= 1)
1777 return true;
1778 if (nDepth < 0)
1779 return false;
1780 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1781 return false;
1783 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1784 if (!InMempool())
1785 return false;
1787 // Trusted if all inputs are from us and are in the mempool:
1788 BOOST_FOREACH(const CTxIn& txin, tx->vin)
1790 // Transactions not sent by us: not trusted
1791 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1792 if (parent == NULL)
1793 return false;
1794 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1795 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1796 return false;
1798 return true;
1801 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1803 CMutableTransaction tx1 = *this->tx;
1804 CMutableTransaction tx2 = *_tx.tx;
1805 for (unsigned int i = 0; i < tx1.vin.size(); i++) tx1.vin[i].scriptSig = CScript();
1806 for (unsigned int i = 0; i < tx2.vin.size(); i++) tx2.vin[i].scriptSig = CScript();
1807 return CTransaction(tx1) == CTransaction(tx2);
1810 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1812 std::vector<uint256> result;
1814 LOCK(cs_wallet);
1815 // Sort them in chronological order
1816 std::multimap<unsigned int, CWalletTx*> mapSorted;
1817 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1819 CWalletTx& wtx = item.second;
1820 // Don't rebroadcast if newer than nTime:
1821 if (wtx.nTimeReceived > nTime)
1822 continue;
1823 mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1825 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1827 CWalletTx& wtx = *item.second;
1828 if (wtx.RelayWalletTransaction(connman))
1829 result.push_back(wtx.GetHash());
1831 return result;
1834 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1836 // Do this infrequently and randomly to avoid giving away
1837 // that these are our transactions.
1838 if (GetTime() < nNextResend || !fBroadcastTransactions)
1839 return;
1840 bool fFirst = (nNextResend == 0);
1841 nNextResend = GetTime() + GetRand(30 * 60);
1842 if (fFirst)
1843 return;
1845 // Only do it if there's been a new block since last time
1846 if (nBestBlockTime < nLastResend)
1847 return;
1848 nLastResend = GetTime();
1850 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1851 // block was found:
1852 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
1853 if (!relayed.empty())
1854 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
1857 /** @} */ // end of mapWallet
1862 /** @defgroup Actions
1864 * @{
1868 CAmount CWallet::GetBalance() const
1870 CAmount nTotal = 0;
1872 LOCK2(cs_main, cs_wallet);
1873 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1875 const CWalletTx* pcoin = &(*it).second;
1876 if (pcoin->IsTrusted())
1877 nTotal += pcoin->GetAvailableCredit();
1881 return nTotal;
1884 CAmount CWallet::GetUnconfirmedBalance() const
1886 CAmount nTotal = 0;
1888 LOCK2(cs_main, cs_wallet);
1889 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1891 const CWalletTx* pcoin = &(*it).second;
1892 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1893 nTotal += pcoin->GetAvailableCredit();
1896 return nTotal;
1899 CAmount CWallet::GetImmatureBalance() const
1901 CAmount nTotal = 0;
1903 LOCK2(cs_main, cs_wallet);
1904 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1906 const CWalletTx* pcoin = &(*it).second;
1907 nTotal += pcoin->GetImmatureCredit();
1910 return nTotal;
1913 CAmount CWallet::GetWatchOnlyBalance() const
1915 CAmount nTotal = 0;
1917 LOCK2(cs_main, cs_wallet);
1918 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1920 const CWalletTx* pcoin = &(*it).second;
1921 if (pcoin->IsTrusted())
1922 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1926 return nTotal;
1929 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
1931 CAmount nTotal = 0;
1933 LOCK2(cs_main, cs_wallet);
1934 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1936 const CWalletTx* pcoin = &(*it).second;
1937 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1938 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1941 return nTotal;
1944 CAmount CWallet::GetImmatureWatchOnlyBalance() const
1946 CAmount nTotal = 0;
1948 LOCK2(cs_main, cs_wallet);
1949 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1951 const CWalletTx* pcoin = &(*it).second;
1952 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1955 return nTotal;
1958 void CWallet::AvailableCoins(std::vector<COutput>& vCoins, bool fOnlySafe, const CCoinControl *coinControl, bool fIncludeZeroValue) const
1960 vCoins.clear();
1963 LOCK2(cs_main, cs_wallet);
1964 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1966 const uint256& wtxid = it->first;
1967 const CWalletTx* pcoin = &(*it).second;
1969 if (!CheckFinalTx(*pcoin))
1970 continue;
1972 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1973 continue;
1975 int nDepth = pcoin->GetDepthInMainChain();
1976 if (nDepth < 0)
1977 continue;
1979 // We should not consider coins which aren't at least in our mempool
1980 // It's possible for these to be conflicted via ancestors which we may never be able to detect
1981 if (nDepth == 0 && !pcoin->InMempool())
1982 continue;
1984 bool safeTx = pcoin->IsTrusted();
1986 // We should not consider coins from transactions that are replacing
1987 // other transactions.
1989 // Example: There is a transaction A which is replaced by bumpfee
1990 // transaction B. In this case, we want to prevent creation of
1991 // a transaction B' which spends an output of B.
1993 // Reason: If transaction A were initially confirmed, transactions B
1994 // and B' would no longer be valid, so the user would have to create
1995 // a new transaction C to replace B'. However, in the case of a
1996 // one-block reorg, transactions B' and C might BOTH be accepted,
1997 // when the user only wanted one of them. Specifically, there could
1998 // be a 1-block reorg away from the chain where transactions A and C
1999 // were accepted to another chain where B, B', and C were all
2000 // accepted.
2001 if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2002 safeTx = false;
2005 // Similarly, we should not consider coins from transactions that
2006 // have been replaced. In the example above, we would want to prevent
2007 // creation of a transaction A' spending an output of A, because if
2008 // transaction B were initially confirmed, conflicting with A and
2009 // A', we wouldn't want to the user to create a transaction D
2010 // intending to replace A', but potentially resulting in a scenario
2011 // where A, A', and D could all be accepted (instead of just B and
2012 // D, or just A and A' like the user would want).
2013 if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2014 safeTx = false;
2017 if (fOnlySafe && !safeTx) {
2018 continue;
2021 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2022 isminetype mine = IsMine(pcoin->tx->vout[i]);
2023 if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO &&
2024 !IsLockedCoin((*it).first, i) && (pcoin->tx->vout[i].nValue > 0 || fIncludeZeroValue) &&
2025 (!coinControl || !coinControl->HasSelected() || coinControl->fAllowOtherInputs || coinControl->IsSelected(COutPoint((*it).first, i))))
2026 vCoins.push_back(COutput(pcoin, i, nDepth,
2027 ((mine & ISMINE_SPENDABLE) != ISMINE_NO) ||
2028 (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO),
2029 (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO, safeTx));
2035 static void ApproximateBestSubset(const std::vector<std::pair<CAmount, std::pair<const CWalletTx*,unsigned int> > >& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2036 std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2038 std::vector<char> vfIncluded;
2040 vfBest.assign(vValue.size(), true);
2041 nBest = nTotalLower;
2043 FastRandomContext insecure_rand;
2045 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2047 vfIncluded.assign(vValue.size(), false);
2048 CAmount nTotal = 0;
2049 bool fReachedTarget = false;
2050 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2052 for (unsigned int i = 0; i < vValue.size(); i++)
2054 //The solver here uses a randomized algorithm,
2055 //the randomness serves no real security purpose but is just
2056 //needed to prevent degenerate behavior and it is important
2057 //that the rng is fast. We do not use a constant random sequence,
2058 //because there may be some privacy improvement by making
2059 //the selection random.
2060 if (nPass == 0 ? insecure_rand.rand32()&1 : !vfIncluded[i])
2062 nTotal += vValue[i].first;
2063 vfIncluded[i] = true;
2064 if (nTotal >= nTargetValue)
2066 fReachedTarget = true;
2067 if (nTotal < nBest)
2069 nBest = nTotal;
2070 vfBest = vfIncluded;
2072 nTotal -= vValue[i].first;
2073 vfIncluded[i] = false;
2081 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2082 std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet) const
2084 setCoinsRet.clear();
2085 nValueRet = 0;
2087 // List of values less than target
2088 std::pair<CAmount, std::pair<const CWalletTx*,unsigned int> > coinLowestLarger;
2089 coinLowestLarger.first = std::numeric_limits<CAmount>::max();
2090 coinLowestLarger.second.first = NULL;
2091 std::vector<std::pair<CAmount, std::pair<const CWalletTx*,unsigned int> > > vValue;
2092 CAmount nTotalLower = 0;
2094 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2096 BOOST_FOREACH(const COutput &output, vCoins)
2098 if (!output.fSpendable)
2099 continue;
2101 const CWalletTx *pcoin = output.tx;
2103 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2104 continue;
2106 if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2107 continue;
2109 int i = output.i;
2110 CAmount n = pcoin->tx->vout[i].nValue;
2112 std::pair<CAmount,std::pair<const CWalletTx*,unsigned int> > coin = std::make_pair(n,std::make_pair(pcoin, i));
2114 if (n == nTargetValue)
2116 setCoinsRet.insert(coin.second);
2117 nValueRet += coin.first;
2118 return true;
2120 else if (n < nTargetValue + MIN_CHANGE)
2122 vValue.push_back(coin);
2123 nTotalLower += n;
2125 else if (n < coinLowestLarger.first)
2127 coinLowestLarger = coin;
2131 if (nTotalLower == nTargetValue)
2133 for (unsigned int i = 0; i < vValue.size(); ++i)
2135 setCoinsRet.insert(vValue[i].second);
2136 nValueRet += vValue[i].first;
2138 return true;
2141 if (nTotalLower < nTargetValue)
2143 if (coinLowestLarger.second.first == NULL)
2144 return false;
2145 setCoinsRet.insert(coinLowestLarger.second);
2146 nValueRet += coinLowestLarger.first;
2147 return true;
2150 // Solve subset sum by stochastic approximation
2151 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2152 std::reverse(vValue.begin(), vValue.end());
2153 std::vector<char> vfBest;
2154 CAmount nBest;
2156 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2157 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2158 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2160 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2161 // or the next bigger coin is closer), return the bigger coin
2162 if (coinLowestLarger.second.first &&
2163 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger.first <= nBest))
2165 setCoinsRet.insert(coinLowestLarger.second);
2166 nValueRet += coinLowestLarger.first;
2168 else {
2169 for (unsigned int i = 0; i < vValue.size(); i++)
2170 if (vfBest[i])
2172 setCoinsRet.insert(vValue[i].second);
2173 nValueRet += vValue[i].first;
2176 if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2177 LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2178 for (unsigned int i = 0; i < vValue.size(); i++) {
2179 if (vfBest[i]) {
2180 LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].first));
2183 LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2187 return true;
2190 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<std::pair<const CWalletTx*,unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2192 std::vector<COutput> vCoins(vAvailableCoins);
2194 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2195 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2197 BOOST_FOREACH(const COutput& out, vCoins)
2199 if (!out.fSpendable)
2200 continue;
2201 nValueRet += out.tx->tx->vout[out.i].nValue;
2202 setCoinsRet.insert(std::make_pair(out.tx, out.i));
2204 return (nValueRet >= nTargetValue);
2207 // calculate value from preset inputs and store them
2208 std::set<std::pair<const CWalletTx*, uint32_t> > setPresetCoins;
2209 CAmount nValueFromPresetInputs = 0;
2211 std::vector<COutPoint> vPresetInputs;
2212 if (coinControl)
2213 coinControl->ListSelected(vPresetInputs);
2214 BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
2216 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2217 if (it != mapWallet.end())
2219 const CWalletTx* pcoin = &it->second;
2220 // Clearly invalid input, fail
2221 if (pcoin->tx->vout.size() <= outpoint.n)
2222 return false;
2223 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2224 setPresetCoins.insert(std::make_pair(pcoin, outpoint.n));
2225 } else
2226 return false; // TODO: Allow non-wallet inputs
2229 // remove preset inputs from vCoins
2230 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2232 if (setPresetCoins.count(std::make_pair(it->tx, it->i)))
2233 it = vCoins.erase(it);
2234 else
2235 ++it;
2238 size_t nMaxChainLength = std::min(GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2239 bool fRejectLongChains = GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2241 bool res = nTargetValue <= nValueFromPresetInputs ||
2242 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2243 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2244 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2245 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2246 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2247 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2248 (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2250 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2251 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2253 // add preset inputs to the total value selected
2254 nValueRet += nValueFromPresetInputs;
2256 return res;
2259 bool CWallet::SignTransaction(CMutableTransaction &tx)
2261 // sign the new tx
2262 CTransaction txNewConst(tx);
2263 int nIn = 0;
2264 for (auto& input : tx.vin) {
2265 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2266 assert(mi != mapWallet.end() && input.prevout.n < mi->second.tx->vout.size());
2267 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2268 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2269 SignatureData sigdata;
2270 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2271 return false;
2273 UpdateTransaction(tx, nIn, sigdata);
2274 nIn++;
2276 return true;
2279 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, bool overrideEstimatedFeeRate, const CFeeRate& specificFeeRate, int& nChangePosInOut, std::string& strFailReason, bool includeWatching, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, bool keepReserveKey, const CTxDestination& destChange)
2281 std::vector<CRecipient> vecSend;
2283 // Turn the txout set into a CRecipient vector
2284 for (size_t idx = 0; idx < tx.vout.size(); idx++)
2286 const CTxOut& txOut = tx.vout[idx];
2287 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2288 vecSend.push_back(recipient);
2291 CCoinControl coinControl;
2292 coinControl.destChange = destChange;
2293 coinControl.fAllowOtherInputs = true;
2294 coinControl.fAllowWatchOnly = includeWatching;
2295 coinControl.fOverrideFeeRate = overrideEstimatedFeeRate;
2296 coinControl.nFeeRate = specificFeeRate;
2298 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2299 coinControl.Select(txin.prevout);
2301 CReserveKey reservekey(this);
2302 CWalletTx wtx;
2303 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, &coinControl, false))
2304 return false;
2306 if (nChangePosInOut != -1)
2307 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2309 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2310 for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
2311 tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2313 // Add new txins (keeping original txin scriptSig/order)
2314 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
2316 if (!coinControl.IsSelected(txin.prevout))
2318 tx.vin.push_back(txin);
2320 if (lockUnspents)
2322 LOCK2(cs_main, cs_wallet);
2323 LockCoin(txin.prevout);
2328 // optionally keep the change output key
2329 if (keepReserveKey)
2330 reservekey.KeepKey();
2332 return true;
2335 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2336 int& nChangePosInOut, std::string& strFailReason, const CCoinControl* coinControl, bool sign)
2338 CAmount nValue = 0;
2339 int nChangePosRequest = nChangePosInOut;
2340 unsigned int nSubtractFeeFromAmount = 0;
2341 for (const auto& recipient : vecSend)
2343 if (nValue < 0 || recipient.nAmount < 0)
2345 strFailReason = _("Transaction amounts must not be negative");
2346 return false;
2348 nValue += recipient.nAmount;
2350 if (recipient.fSubtractFeeFromAmount)
2351 nSubtractFeeFromAmount++;
2353 if (vecSend.empty())
2355 strFailReason = _("Transaction must have at least one recipient");
2356 return false;
2359 wtxNew.fTimeReceivedIsTxTime = true;
2360 wtxNew.BindWallet(this);
2361 CMutableTransaction txNew;
2363 // Discourage fee sniping.
2365 // For a large miner the value of the transactions in the best block and
2366 // the mempool can exceed the cost of deliberately attempting to mine two
2367 // blocks to orphan the current best block. By setting nLockTime such that
2368 // only the next block can include the transaction, we discourage this
2369 // practice as the height restricted and limited blocksize gives miners
2370 // considering fee sniping fewer options for pulling off this attack.
2372 // A simple way to think about this is from the wallet's point of view we
2373 // always want the blockchain to move forward. By setting nLockTime this
2374 // way we're basically making the statement that we only want this
2375 // transaction to appear in the next block; we don't want to potentially
2376 // encourage reorgs by allowing transactions to appear at lower heights
2377 // than the next block in forks of the best chain.
2379 // Of course, the subsidy is high enough, and transaction volume low
2380 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2381 // now we ensure code won't be written that makes assumptions about
2382 // nLockTime that preclude a fix later.
2383 txNew.nLockTime = chainActive.Height();
2385 // Secondly occasionally randomly pick a nLockTime even further back, so
2386 // that transactions that are delayed after signing for whatever reason,
2387 // e.g. high-latency mix networks and some CoinJoin implementations, have
2388 // better privacy.
2389 if (GetRandInt(10) == 0)
2390 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2392 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2393 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2396 std::set<std::pair<const CWalletTx*,unsigned int> > setCoins;
2397 LOCK2(cs_main, cs_wallet);
2399 std::vector<COutput> vAvailableCoins;
2400 AvailableCoins(vAvailableCoins, true, coinControl);
2402 nFeeRet = 0;
2403 // Start with no fee and loop until there is enough fee
2404 while (true)
2406 nChangePosInOut = nChangePosRequest;
2407 txNew.vin.clear();
2408 txNew.vout.clear();
2409 wtxNew.fFromMe = true;
2410 bool fFirst = true;
2412 CAmount nValueToSelect = nValue;
2413 if (nSubtractFeeFromAmount == 0)
2414 nValueToSelect += nFeeRet;
2415 // vouts to the payees
2416 for (const auto& recipient : vecSend)
2418 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2420 if (recipient.fSubtractFeeFromAmount)
2422 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2424 if (fFirst) // first receiver pays the remainder not divisible by output count
2426 fFirst = false;
2427 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2431 if (txout.IsDust(dustRelayFee))
2433 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2435 if (txout.nValue < 0)
2436 strFailReason = _("The transaction amount is too small to pay the fee");
2437 else
2438 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2440 else
2441 strFailReason = _("Transaction amount too small");
2442 return false;
2444 txNew.vout.push_back(txout);
2447 // Choose coins to use
2448 CAmount nValueIn = 0;
2449 setCoins.clear();
2450 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, coinControl))
2452 strFailReason = _("Insufficient funds");
2453 return false;
2456 const CAmount nChange = nValueIn - nValueToSelect;
2457 if (nChange > 0)
2459 // Fill a vout to ourself
2460 // TODO: pass in scriptChange instead of reservekey so
2461 // change transaction isn't always pay-to-bitcoin-address
2462 CScript scriptChange;
2464 // coin control: send change to custom address
2465 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
2466 scriptChange = GetScriptForDestination(coinControl->destChange);
2468 // no coin control: send change to newly generated address
2469 else
2471 // Note: We use a new key here to keep it from being obvious which side is the change.
2472 // The drawback is that by not reusing a previous key, the change may be lost if a
2473 // backup is restored, if the backup doesn't have the new private key for the change.
2474 // If we reused the old key, it would be possible to add code to look for and
2475 // rediscover unknown transactions that were written with keys of ours to recover
2476 // post-backup change.
2478 // Reserve a new key pair from key pool
2479 CPubKey vchPubKey;
2480 bool ret;
2481 ret = reservekey.GetReservedKey(vchPubKey, true);
2482 if (!ret)
2484 strFailReason = _("Keypool ran out, please call keypoolrefill first");
2485 return false;
2488 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2491 CTxOut newTxOut(nChange, scriptChange);
2493 // We do not move dust-change to fees, because the sender would end up paying more than requested.
2494 // This would be against the purpose of the all-inclusive feature.
2495 // So instead we raise the change and deduct from the recipient.
2496 if (nSubtractFeeFromAmount > 0 && newTxOut.IsDust(dustRelayFee))
2498 CAmount nDust = newTxOut.GetDustThreshold(dustRelayFee) - newTxOut.nValue;
2499 newTxOut.nValue += nDust; // raise change until no more dust
2500 for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
2502 if (vecSend[i].fSubtractFeeFromAmount)
2504 txNew.vout[i].nValue -= nDust;
2505 if (txNew.vout[i].IsDust(dustRelayFee))
2507 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2508 return false;
2510 break;
2515 // Never create dust outputs; if we would, just
2516 // add the dust to the fee.
2517 if (newTxOut.IsDust(dustRelayFee))
2519 nChangePosInOut = -1;
2520 nFeeRet += nChange;
2521 reservekey.ReturnKey();
2523 else
2525 if (nChangePosInOut == -1)
2527 // Insert change txn at random position:
2528 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2530 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2532 strFailReason = _("Change index out of range");
2533 return false;
2536 std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2537 txNew.vout.insert(position, newTxOut);
2540 else
2541 reservekey.ReturnKey();
2543 // Fill vin
2545 // Note how the sequence number is set to non-maxint so that
2546 // the nLockTime set above actually works.
2548 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2549 // we use the highest possible value in that range (maxint-2)
2550 // to avoid conflicting with other possible uses of nSequence,
2551 // and in the spirit of "smallest possible change from prior
2552 // behavior."
2553 bool rbf = coinControl ? coinControl->signalRbf : fWalletRbf;
2554 for (const auto& coin : setCoins)
2555 txNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second,CScript(),
2556 std::numeric_limits<unsigned int>::max() - (rbf ? 2 : 1)));
2558 // Fill in dummy signatures for fee calculation.
2559 if (!DummySignTx(txNew, setCoins)) {
2560 strFailReason = _("Signing transaction failed");
2561 return false;
2564 unsigned int nBytes = GetVirtualTransactionSize(txNew);
2566 CTransaction txNewConst(txNew);
2568 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2569 for (auto& vin : txNew.vin) {
2570 vin.scriptSig = CScript();
2571 vin.scriptWitness.SetNull();
2574 // Allow to override the default confirmation target over the CoinControl instance
2575 int currentConfirmationTarget = nTxConfirmTarget;
2576 if (coinControl && coinControl->nConfirmTarget > 0)
2577 currentConfirmationTarget = coinControl->nConfirmTarget;
2579 CAmount nFeeNeeded = GetMinimumFee(nBytes, currentConfirmationTarget, mempool);
2580 if (coinControl && nFeeNeeded > 0 && coinControl->nMinimumTotalFee > nFeeNeeded) {
2581 nFeeNeeded = coinControl->nMinimumTotalFee;
2583 if (coinControl && coinControl->fOverrideFeeRate)
2584 nFeeNeeded = coinControl->nFeeRate.GetFee(nBytes);
2586 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2587 // because we must be at the maximum allowed fee.
2588 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2590 strFailReason = _("Transaction too large for fee policy");
2591 return false;
2594 if (nFeeRet >= nFeeNeeded) {
2595 // Reduce fee to only the needed amount if we have change
2596 // output to increase. This prevents potential overpayment
2597 // in fees if the coins selected to meet nFeeNeeded result
2598 // in a transaction that requires less fee than the prior
2599 // iteration.
2600 // TODO: The case where nSubtractFeeFromAmount > 0 remains
2601 // to be addressed because it requires returning the fee to
2602 // the payees and not the change output.
2603 // TODO: The case where there is no change output remains
2604 // to be addressed so we avoid creating too small an output.
2605 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2606 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2607 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2608 change_position->nValue += extraFeePaid;
2609 nFeeRet -= extraFeePaid;
2611 break; // Done, enough fee included.
2614 // Try to reduce change to include necessary fee
2615 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2616 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2617 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2618 // Only reduce change if remaining amount is still a large enough output.
2619 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2620 change_position->nValue -= additionalFeeNeeded;
2621 nFeeRet += additionalFeeNeeded;
2622 break; // Done, able to increase fee from change
2626 // Include more fee and try again.
2627 nFeeRet = nFeeNeeded;
2628 continue;
2632 if (sign)
2634 CTransaction txNewConst(txNew);
2635 int nIn = 0;
2636 for (const auto& coin : setCoins)
2638 const CScript& scriptPubKey = coin.first->tx->vout[coin.second].scriptPubKey;
2639 SignatureData sigdata;
2641 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.first->tx->vout[coin.second].nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2643 strFailReason = _("Signing transaction failed");
2644 return false;
2645 } else {
2646 UpdateTransaction(txNew, nIn, sigdata);
2649 nIn++;
2653 // Embed the constructed transaction data in wtxNew.
2654 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2656 // Limit size
2657 if (GetTransactionWeight(wtxNew) >= MAX_STANDARD_TX_WEIGHT)
2659 strFailReason = _("Transaction too large");
2660 return false;
2664 if (GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2665 // Lastly, ensure this tx will pass the mempool's chain limits
2666 LockPoints lp;
2667 CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
2668 CTxMemPool::setEntries setAncestors;
2669 size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2670 size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2671 size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2672 size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2673 std::string errString;
2674 if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2675 strFailReason = _("Transaction has too long of a mempool chain");
2676 return false;
2679 return true;
2683 * Call after CreateTransaction unless you want to abort
2685 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
2688 LOCK2(cs_main, cs_wallet);
2689 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
2691 // Take key pair from key pool so it won't be used again
2692 reservekey.KeepKey();
2694 // Add tx to wallet, because if it has change it's also ours,
2695 // otherwise just for transaction history.
2696 AddToWallet(wtxNew);
2698 // Notify that old coins are spent
2699 BOOST_FOREACH(const CTxIn& txin, wtxNew.tx->vin)
2701 CWalletTx &coin = mapWallet[txin.prevout.hash];
2702 coin.BindWallet(this);
2703 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2707 // Track how many getdata requests our transaction gets
2708 mapRequestCount[wtxNew.GetHash()] = 0;
2710 if (fBroadcastTransactions)
2712 // Broadcast
2713 if (!wtxNew.AcceptToMemoryPool(maxTxFee, state)) {
2714 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
2715 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2716 } else {
2717 wtxNew.RelayWalletTransaction(connman);
2721 return true;
2724 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
2725 CWalletDB walletdb(strWalletFile);
2726 return walletdb.ListAccountCreditDebit(strAccount, entries);
2729 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
2731 CWalletDB walletdb(strWalletFile);
2733 return AddAccountingEntry(acentry, &walletdb);
2736 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
2738 if (!pwalletdb->WriteAccountingEntry_Backend(acentry))
2739 return false;
2741 laccentries.push_back(acentry);
2742 CAccountingEntry & entry = laccentries.back();
2743 wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
2745 return true;
2748 CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
2750 return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
2753 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool)
2755 // payTxFee is the user-set global for desired feerate
2756 return GetMinimumFee(nTxBytes, nConfirmTarget, pool, payTxFee.GetFee(nTxBytes));
2759 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool, CAmount targetFee)
2761 CAmount nFeeNeeded = targetFee;
2762 // User didn't set: use -txconfirmtarget to estimate...
2763 if (nFeeNeeded == 0) {
2764 int estimateFoundTarget = nConfirmTarget;
2765 nFeeNeeded = pool.estimateSmartFee(nConfirmTarget, &estimateFoundTarget).GetFee(nTxBytes);
2766 // ... unless we don't have enough mempool data for estimatefee, then use fallbackFee
2767 if (nFeeNeeded == 0)
2768 nFeeNeeded = fallbackFee.GetFee(nTxBytes);
2770 // prevent user from paying a fee below minRelayTxFee or minTxFee
2771 nFeeNeeded = std::max(nFeeNeeded, GetRequiredFee(nTxBytes));
2772 // But always obey the maximum
2773 if (nFeeNeeded > maxTxFee)
2774 nFeeNeeded = maxTxFee;
2775 return nFeeNeeded;
2781 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2783 if (!fFileBacked)
2784 return DB_LOAD_OK;
2785 fFirstRunRet = false;
2786 DBErrors nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this);
2787 if (nLoadWalletRet == DB_NEED_REWRITE)
2789 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2791 LOCK(cs_wallet);
2792 setKeyPool.clear();
2793 // Note: can't top-up keypool here, because wallet is locked.
2794 // User will be prompted to unlock wallet the next operation
2795 // that requires a new key.
2799 if (nLoadWalletRet != DB_LOAD_OK)
2800 return nLoadWalletRet;
2801 fFirstRunRet = !vchDefaultKey.IsValid();
2803 uiInterface.LoadWallet(this);
2805 return DB_LOAD_OK;
2808 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
2810 if (!fFileBacked)
2811 return DB_LOAD_OK;
2812 AssertLockHeld(cs_wallet); // mapWallet
2813 vchDefaultKey = CPubKey();
2814 DBErrors nZapSelectTxRet = CWalletDB(strWalletFile,"cr+").ZapSelectTx(vHashIn, vHashOut);
2815 for (uint256 hash : vHashOut)
2816 mapWallet.erase(hash);
2818 if (nZapSelectTxRet == DB_NEED_REWRITE)
2820 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2822 setKeyPool.clear();
2823 // Note: can't top-up keypool here, because wallet is locked.
2824 // User will be prompted to unlock wallet the next operation
2825 // that requires a new key.
2829 if (nZapSelectTxRet != DB_LOAD_OK)
2830 return nZapSelectTxRet;
2832 MarkDirty();
2834 return DB_LOAD_OK;
2838 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
2840 if (!fFileBacked)
2841 return DB_LOAD_OK;
2842 vchDefaultKey = CPubKey();
2843 DBErrors nZapWalletTxRet = CWalletDB(strWalletFile,"cr+").ZapWalletTx(vWtx);
2844 if (nZapWalletTxRet == DB_NEED_REWRITE)
2846 if (CDB::Rewrite(strWalletFile, "\x04pool"))
2848 LOCK(cs_wallet);
2849 setKeyPool.clear();
2850 // Note: can't top-up keypool here, because wallet is locked.
2851 // User will be prompted to unlock wallet the next operation
2852 // that requires a new key.
2856 if (nZapWalletTxRet != DB_LOAD_OK)
2857 return nZapWalletTxRet;
2859 return DB_LOAD_OK;
2863 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
2865 bool fUpdated = false;
2867 LOCK(cs_wallet); // mapAddressBook
2868 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
2869 fUpdated = mi != mapAddressBook.end();
2870 mapAddressBook[address].name = strName;
2871 if (!strPurpose.empty()) /* update purpose only if requested */
2872 mapAddressBook[address].purpose = strPurpose;
2874 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
2875 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
2876 if (!fFileBacked)
2877 return false;
2878 if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
2879 return false;
2880 return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName);
2883 bool CWallet::DelAddressBook(const CTxDestination& address)
2886 LOCK(cs_wallet); // mapAddressBook
2888 if(fFileBacked)
2890 // Delete destdata tuples associated with address
2891 std::string strAddress = CBitcoinAddress(address).ToString();
2892 BOOST_FOREACH(const PAIRTYPE(std::string, std::string) &item, mapAddressBook[address].destdata)
2894 CWalletDB(strWalletFile).EraseDestData(strAddress, item.first);
2897 mapAddressBook.erase(address);
2900 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
2902 if (!fFileBacked)
2903 return false;
2904 CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString());
2905 return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString());
2908 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2910 if (fFileBacked)
2912 if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey))
2913 return false;
2915 vchDefaultKey = vchPubKey;
2916 return true;
2920 * Mark old keypool keys as used,
2921 * and generate all new keys
2923 bool CWallet::NewKeyPool()
2926 LOCK(cs_wallet);
2927 CWalletDB walletdb(strWalletFile);
2928 BOOST_FOREACH(int64_t nIndex, setKeyPool)
2929 walletdb.ErasePool(nIndex);
2930 setKeyPool.clear();
2932 if (!TopUpKeyPool()) {
2933 return false;
2935 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
2937 return true;
2940 size_t CWallet::KeypoolCountExternalKeys()
2942 AssertLockHeld(cs_wallet); // setKeyPool
2944 // immediately return setKeyPool's size if HD or HD_SPLIT is disabled or not supported
2945 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
2946 return setKeyPool.size();
2948 CWalletDB walletdb(strWalletFile);
2950 // count amount of external keys
2951 size_t amountE = 0;
2952 for(const int64_t& id : setKeyPool)
2954 CKeyPool tmpKeypool;
2955 if (!walletdb.ReadPool(id, tmpKeypool))
2956 throw std::runtime_error(std::string(__func__) + ": read failed");
2957 amountE += !tmpKeypool.fInternal;
2960 return amountE;
2963 bool CWallet::TopUpKeyPool(unsigned int kpSize)
2966 LOCK(cs_wallet);
2968 if (IsLocked())
2969 return false;
2971 // Top up key pool
2972 unsigned int nTargetSize;
2973 if (kpSize > 0)
2974 nTargetSize = kpSize;
2975 else
2976 nTargetSize = std::max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
2978 // count amount of available keys (internal, external)
2979 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
2980 int64_t amountExternal = KeypoolCountExternalKeys();
2981 int64_t amountInternal = setKeyPool.size() - amountExternal;
2982 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - amountExternal, (int64_t) 0);
2983 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - amountInternal, (int64_t) 0);
2985 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
2987 // don't create extra internal keys
2988 missingInternal = 0;
2990 bool internal = false;
2991 CWalletDB walletdb(strWalletFile);
2992 for (int64_t i = missingInternal + missingExternal; i--;)
2994 int64_t nEnd = 1;
2995 if (i < missingInternal)
2996 internal = true;
2997 if (!setKeyPool.empty())
2998 nEnd = *(--setKeyPool.end()) + 1;
2999 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey(internal), internal)))
3000 throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3001 setKeyPool.insert(nEnd);
3002 LogPrintf("keypool added key %d, size=%u, internal=%d\n", nEnd, setKeyPool.size(), internal);
3005 return true;
3008 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool internal)
3010 nIndex = -1;
3011 keypool.vchPubKey = CPubKey();
3013 LOCK(cs_wallet);
3015 if (!IsLocked())
3016 TopUpKeyPool();
3018 // Get the oldest key
3019 if(setKeyPool.empty())
3020 return;
3022 CWalletDB walletdb(strWalletFile);
3024 // try to find a key that matches the internal/external filter
3025 for(const int64_t& id : setKeyPool)
3027 CKeyPool tmpKeypool;
3028 if (!walletdb.ReadPool(id, tmpKeypool))
3029 throw std::runtime_error(std::string(__func__) + ": read failed");
3030 if (!HaveKey(tmpKeypool.vchPubKey.GetID()))
3031 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3032 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT) || tmpKeypool.fInternal == internal)
3034 nIndex = id;
3035 keypool = tmpKeypool;
3036 setKeyPool.erase(id);
3037 assert(keypool.vchPubKey.IsValid());
3038 LogPrintf("keypool reserve %d\n", nIndex);
3039 return;
3045 void CWallet::KeepKey(int64_t nIndex)
3047 // Remove from key pool
3048 if (fFileBacked)
3050 CWalletDB walletdb(strWalletFile);
3051 walletdb.ErasePool(nIndex);
3053 LogPrintf("keypool keep %d\n", nIndex);
3056 void CWallet::ReturnKey(int64_t nIndex)
3058 // Return to key pool
3060 LOCK(cs_wallet);
3061 setKeyPool.insert(nIndex);
3063 LogPrintf("keypool return %d\n", nIndex);
3066 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3068 int64_t nIndex = 0;
3069 CKeyPool keypool;
3071 LOCK(cs_wallet);
3072 ReserveKeyFromKeyPool(nIndex, keypool, internal);
3073 if (nIndex == -1)
3075 if (IsLocked()) return false;
3076 result = GenerateNewKey(internal);
3077 return true;
3079 KeepKey(nIndex);
3080 result = keypool.vchPubKey;
3082 return true;
3085 int64_t CWallet::GetOldestKeyPoolTime()
3087 LOCK(cs_wallet);
3089 // if the keypool is empty, return <NOW>
3090 if (setKeyPool.empty())
3091 return GetTime();
3093 CKeyPool keypool;
3094 CWalletDB walletdb(strWalletFile);
3096 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT))
3098 // if HD & HD Chain Split is enabled, response max(oldest-internal-key, oldest-external-key)
3099 int64_t now = GetTime();
3100 int64_t oldest_external = now, oldest_internal = now;
3102 for(const int64_t& id : setKeyPool)
3104 if (!walletdb.ReadPool(id, keypool)) {
3105 throw std::runtime_error(std::string(__func__) + ": read failed");
3107 if (keypool.fInternal && keypool.nTime < oldest_internal) {
3108 oldest_internal = keypool.nTime;
3110 else if (!keypool.fInternal && keypool.nTime < oldest_external) {
3111 oldest_external = keypool.nTime;
3113 if (oldest_internal != now && oldest_external != now) {
3114 break;
3117 return std::max(oldest_internal, oldest_external);
3119 // load oldest key from keypool, get time and return
3120 int64_t nIndex = *(setKeyPool.begin());
3121 if (!walletdb.ReadPool(nIndex, keypool))
3122 throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3123 assert(keypool.vchPubKey.IsValid());
3124 return keypool.nTime;
3127 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3129 std::map<CTxDestination, CAmount> balances;
3132 LOCK(cs_wallet);
3133 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3135 CWalletTx *pcoin = &walletEntry.second;
3137 if (!pcoin->IsTrusted())
3138 continue;
3140 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3141 continue;
3143 int nDepth = pcoin->GetDepthInMainChain();
3144 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3145 continue;
3147 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3149 CTxDestination addr;
3150 if (!IsMine(pcoin->tx->vout[i]))
3151 continue;
3152 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3153 continue;
3155 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3157 if (!balances.count(addr))
3158 balances[addr] = 0;
3159 balances[addr] += n;
3164 return balances;
3167 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3169 AssertLockHeld(cs_wallet); // mapWallet
3170 std::set< std::set<CTxDestination> > groupings;
3171 std::set<CTxDestination> grouping;
3173 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3175 CWalletTx *pcoin = &walletEntry.second;
3177 if (pcoin->tx->vin.size() > 0)
3179 bool any_mine = false;
3180 // group all input addresses with each other
3181 BOOST_FOREACH(CTxIn txin, pcoin->tx->vin)
3183 CTxDestination address;
3184 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3185 continue;
3186 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3187 continue;
3188 grouping.insert(address);
3189 any_mine = true;
3192 // group change with input addresses
3193 if (any_mine)
3195 BOOST_FOREACH(CTxOut txout, pcoin->tx->vout)
3196 if (IsChange(txout))
3198 CTxDestination txoutAddr;
3199 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3200 continue;
3201 grouping.insert(txoutAddr);
3204 if (grouping.size() > 0)
3206 groupings.insert(grouping);
3207 grouping.clear();
3211 // group lone addrs by themselves
3212 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3213 if (IsMine(pcoin->tx->vout[i]))
3215 CTxDestination address;
3216 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, address))
3217 continue;
3218 grouping.insert(address);
3219 groupings.insert(grouping);
3220 grouping.clear();
3224 std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3225 std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3226 BOOST_FOREACH(std::set<CTxDestination> _grouping, groupings)
3228 // make a set of all the groups hit by this new group
3229 std::set< std::set<CTxDestination>* > hits;
3230 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3231 BOOST_FOREACH(CTxDestination address, _grouping)
3232 if ((it = setmap.find(address)) != setmap.end())
3233 hits.insert((*it).second);
3235 // merge all hit groups into a new single group and delete old groups
3236 std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3237 BOOST_FOREACH(std::set<CTxDestination>* hit, hits)
3239 merged->insert(hit->begin(), hit->end());
3240 uniqueGroupings.erase(hit);
3241 delete hit;
3243 uniqueGroupings.insert(merged);
3245 // update setmap
3246 BOOST_FOREACH(CTxDestination element, *merged)
3247 setmap[element] = merged;
3250 std::set< std::set<CTxDestination> > ret;
3251 BOOST_FOREACH(std::set<CTxDestination>* uniqueGrouping, uniqueGroupings)
3253 ret.insert(*uniqueGrouping);
3254 delete uniqueGrouping;
3257 return ret;
3260 CAmount CWallet::GetAccountBalance(const std::string& strAccount, int nMinDepth, const isminefilter& filter)
3262 CWalletDB walletdb(strWalletFile);
3263 return GetAccountBalance(walletdb, strAccount, nMinDepth, filter);
3266 CAmount CWallet::GetAccountBalance(CWalletDB& walletdb, const std::string& strAccount, int nMinDepth, const isminefilter& filter)
3268 CAmount nBalance = 0;
3270 // Tally wallet transactions
3271 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
3273 const CWalletTx& wtx = (*it).second;
3274 if (!CheckFinalTx(wtx) || wtx.GetBlocksToMaturity() > 0 || wtx.GetDepthInMainChain() < 0)
3275 continue;
3277 CAmount nReceived, nSent, nFee;
3278 wtx.GetAccountAmounts(strAccount, nReceived, nSent, nFee, filter);
3280 if (nReceived != 0 && wtx.GetDepthInMainChain() >= nMinDepth)
3281 nBalance += nReceived;
3282 nBalance -= nSent + nFee;
3285 // Tally internal accounting entries
3286 nBalance += walletdb.GetAccountCreditDebit(strAccount);
3288 return nBalance;
3291 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3293 LOCK(cs_wallet);
3294 std::set<CTxDestination> result;
3295 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
3297 const CTxDestination& address = item.first;
3298 const std::string& strName = item.second.name;
3299 if (strName == strAccount)
3300 result.insert(address);
3302 return result;
3305 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3307 if (nIndex == -1)
3309 CKeyPool keypool;
3310 pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3311 if (nIndex != -1)
3312 vchPubKey = keypool.vchPubKey;
3313 else {
3314 return false;
3317 assert(vchPubKey.IsValid());
3318 pubkey = vchPubKey;
3319 return true;
3322 void CReserveKey::KeepKey()
3324 if (nIndex != -1)
3325 pwallet->KeepKey(nIndex);
3326 nIndex = -1;
3327 vchPubKey = CPubKey();
3330 void CReserveKey::ReturnKey()
3332 if (nIndex != -1)
3333 pwallet->ReturnKey(nIndex);
3334 nIndex = -1;
3335 vchPubKey = CPubKey();
3338 void CWallet::GetAllReserveKeys(std::set<CKeyID>& setAddress) const
3340 setAddress.clear();
3342 CWalletDB walletdb(strWalletFile);
3344 LOCK2(cs_main, cs_wallet);
3345 BOOST_FOREACH(const int64_t& id, setKeyPool)
3347 CKeyPool keypool;
3348 if (!walletdb.ReadPool(id, keypool))
3349 throw std::runtime_error(std::string(__func__) + ": read failed");
3350 assert(keypool.vchPubKey.IsValid());
3351 CKeyID keyID = keypool.vchPubKey.GetID();
3352 if (!HaveKey(keyID))
3353 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3354 setAddress.insert(keyID);
3358 void CWallet::UpdatedTransaction(const uint256 &hashTx)
3361 LOCK(cs_wallet);
3362 // Only notify UI if this transaction is in this wallet
3363 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx);
3364 if (mi != mapWallet.end())
3365 NotifyTransactionChanged(this, hashTx, CT_UPDATED);
3369 void CWallet::GetScriptForMining(boost::shared_ptr<CReserveScript> &script)
3371 boost::shared_ptr<CReserveKey> rKey(new CReserveKey(this));
3372 CPubKey pubkey;
3373 if (!rKey->GetReservedKey(pubkey))
3374 return;
3376 script = rKey;
3377 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3380 void CWallet::LockCoin(const COutPoint& output)
3382 AssertLockHeld(cs_wallet); // setLockedCoins
3383 setLockedCoins.insert(output);
3386 void CWallet::UnlockCoin(const COutPoint& output)
3388 AssertLockHeld(cs_wallet); // setLockedCoins
3389 setLockedCoins.erase(output);
3392 void CWallet::UnlockAllCoins()
3394 AssertLockHeld(cs_wallet); // setLockedCoins
3395 setLockedCoins.clear();
3398 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3400 AssertLockHeld(cs_wallet); // setLockedCoins
3401 COutPoint outpt(hash, n);
3403 return (setLockedCoins.count(outpt) > 0);
3406 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
3408 AssertLockHeld(cs_wallet); // setLockedCoins
3409 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3410 it != setLockedCoins.end(); it++) {
3411 COutPoint outpt = (*it);
3412 vOutpts.push_back(outpt);
3416 /** @} */ // end of Actions
3418 class CAffectedKeysVisitor : public boost::static_visitor<void> {
3419 private:
3420 const CKeyStore &keystore;
3421 std::vector<CKeyID> &vKeys;
3423 public:
3424 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
3426 void Process(const CScript &script) {
3427 txnouttype type;
3428 std::vector<CTxDestination> vDest;
3429 int nRequired;
3430 if (ExtractDestinations(script, type, vDest, nRequired)) {
3431 BOOST_FOREACH(const CTxDestination &dest, vDest)
3432 boost::apply_visitor(*this, dest);
3436 void operator()(const CKeyID &keyId) {
3437 if (keystore.HaveKey(keyId))
3438 vKeys.push_back(keyId);
3441 void operator()(const CScriptID &scriptId) {
3442 CScript script;
3443 if (keystore.GetCScript(scriptId, script))
3444 Process(script);
3447 void operator()(const CNoDestination &none) {}
3450 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3451 AssertLockHeld(cs_wallet); // mapKeyMetadata
3452 mapKeyBirth.clear();
3454 // get birth times for keys with metadata
3455 for (const auto& entry : mapKeyMetadata) {
3456 if (entry.second.nCreateTime) {
3457 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3461 // map in which we'll infer heights of other keys
3462 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3463 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3464 std::set<CKeyID> setKeys;
3465 GetKeys(setKeys);
3466 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
3467 if (mapKeyBirth.count(keyid) == 0)
3468 mapKeyFirstBlock[keyid] = pindexMax;
3470 setKeys.clear();
3472 // if there are no such keys, we're done
3473 if (mapKeyFirstBlock.empty())
3474 return;
3476 // find first block that affects those keys, if there are any left
3477 std::vector<CKeyID> vAffected;
3478 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3479 // iterate over all wallet transactions...
3480 const CWalletTx &wtx = (*it).second;
3481 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3482 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3483 // ... which are already in a block
3484 int nHeight = blit->second->nHeight;
3485 BOOST_FOREACH(const CTxOut &txout, wtx.tx->vout) {
3486 // iterate over all their outputs
3487 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3488 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
3489 // ... and all their affected keys
3490 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3491 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3492 rit->second = blit->second;
3494 vAffected.clear();
3499 // Extract block timestamps for those keys
3500 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3501 mapKeyBirth[it->first] = it->second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3505 * Compute smart timestamp for a transaction being added to the wallet.
3507 * Logic:
3508 * - If sending a transaction, assign its timestamp to the current time.
3509 * - If receiving a transaction outside a block, assign its timestamp to the
3510 * current time.
3511 * - If receiving a block with a future timestamp, assign all its (not already
3512 * known) transactions' timestamps to the current time.
3513 * - If receiving a block with a past timestamp, before the most recent known
3514 * transaction (that we care about), assign all its (not already known)
3515 * transactions' timestamps to the same timestamp as that most-recent-known
3516 * transaction.
3517 * - If receiving a block with a past timestamp, but after the most recent known
3518 * transaction, assign all its (not already known) transactions' timestamps to
3519 * the block time.
3521 * For more information see CWalletTx::nTimeSmart,
3522 * https://bitcointalk.org/?topic=54527, or
3523 * https://github.com/bitcoin/bitcoin/pull/1393.
3525 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3527 unsigned int nTimeSmart = wtx.nTimeReceived;
3528 if (!wtx.hashUnset()) {
3529 if (mapBlockIndex.count(wtx.hashBlock)) {
3530 int64_t latestNow = wtx.nTimeReceived;
3531 int64_t latestEntry = 0;
3533 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3534 int64_t latestTolerated = latestNow + 300;
3535 const TxItems& txOrdered = wtxOrdered;
3536 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3537 CWalletTx* const pwtx = it->second.first;
3538 if (pwtx == &wtx) {
3539 continue;
3541 CAccountingEntry* const pacentry = it->second.second;
3542 int64_t nSmartTime;
3543 if (pwtx) {
3544 nSmartTime = pwtx->nTimeSmart;
3545 if (!nSmartTime) {
3546 nSmartTime = pwtx->nTimeReceived;
3548 } else {
3549 nSmartTime = pacentry->nTime;
3551 if (nSmartTime <= latestTolerated) {
3552 latestEntry = nSmartTime;
3553 if (nSmartTime > latestNow) {
3554 latestNow = nSmartTime;
3556 break;
3560 int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3561 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3562 } else {
3563 LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3566 return nTimeSmart;
3569 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3571 if (boost::get<CNoDestination>(&dest))
3572 return false;
3574 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3575 if (!fFileBacked)
3576 return true;
3577 return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
3580 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3582 if (!mapAddressBook[dest].destdata.erase(key))
3583 return false;
3584 if (!fFileBacked)
3585 return true;
3586 return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key);
3589 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3591 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3592 return true;
3595 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3597 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3598 if(i != mapAddressBook.end())
3600 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3601 if(j != i->second.destdata.end())
3603 if(value)
3604 *value = j->second;
3605 return true;
3608 return false;
3611 std::string CWallet::GetWalletHelpString(bool showDebug)
3613 std::string strUsage = HelpMessageGroup(_("Wallet options:"));
3614 strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
3615 strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE));
3616 strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
3617 CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)));
3618 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
3619 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)));
3620 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
3621 CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
3622 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
3623 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup"));
3624 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE));
3625 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));
3626 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));
3627 strUsage += HelpMessageOpt("-walletrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (default: %u)"), DEFAULT_WALLET_RBF));
3628 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
3629 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT));
3630 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST));
3631 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
3632 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
3633 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
3635 if (showDebug)
3637 strUsage += HelpMessageGroup(_("Wallet debugging/testing options:"));
3639 strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE));
3640 strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET));
3641 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB));
3642 strUsage += HelpMessageOpt("-walletrejectlongchains", strprintf(_("Wallet will not create transactions that violate mempool chain limits (default: %u)"), DEFAULT_WALLET_REJECT_LONG_CHAINS));
3645 return strUsage;
3648 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
3650 // needed to restore wallet transaction meta data after -zapwallettxes
3651 std::vector<CWalletTx> vWtx;
3653 if (GetBoolArg("-zapwallettxes", false)) {
3654 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3656 CWallet *tempWallet = new CWallet(walletFile);
3657 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3658 if (nZapWalletRet != DB_LOAD_OK) {
3659 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3660 return NULL;
3663 delete tempWallet;
3664 tempWallet = NULL;
3667 uiInterface.InitMessage(_("Loading wallet..."));
3669 int64_t nStart = GetTimeMillis();
3670 bool fFirstRun = true;
3671 CWallet *walletInstance = new CWallet(walletFile);
3672 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3673 if (nLoadWalletRet != DB_LOAD_OK)
3675 if (nLoadWalletRet == DB_CORRUPT) {
3676 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3677 return NULL;
3679 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3681 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3682 " or address book entries might be missing or incorrect."),
3683 walletFile));
3685 else if (nLoadWalletRet == DB_TOO_NEW) {
3686 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
3687 return NULL;
3689 else if (nLoadWalletRet == DB_NEED_REWRITE)
3691 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3692 return NULL;
3694 else {
3695 InitError(strprintf(_("Error loading %s"), walletFile));
3696 return NULL;
3700 if (GetBoolArg("-upgradewallet", fFirstRun))
3702 int nMaxVersion = GetArg("-upgradewallet", 0);
3703 if (nMaxVersion == 0) // the -upgradewallet without argument case
3705 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3706 nMaxVersion = CLIENT_VERSION;
3707 walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3709 else
3710 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3711 if (nMaxVersion < walletInstance->GetVersion())
3713 InitError(_("Cannot downgrade wallet"));
3714 return NULL;
3716 walletInstance->SetMaxVersion(nMaxVersion);
3719 if (fFirstRun)
3721 // Create new keyUser and set as default key
3722 if (GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && !walletInstance->IsHDEnabled()) {
3724 // ensure this wallet.dat can only be opened by clients supporting HD with chain split
3725 walletInstance->SetMinVersion(FEATURE_HD_SPLIT);
3727 // generate a new master key
3728 CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
3729 if (!walletInstance->SetHDMasterKey(masterPubKey))
3730 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
3732 CPubKey newDefaultKey;
3733 if (walletInstance->GetKeyFromPool(newDefaultKey, false)) {
3734 walletInstance->SetDefaultKey(newDefaultKey);
3735 if (!walletInstance->SetAddressBook(walletInstance->vchDefaultKey.GetID(), "", "receive")) {
3736 InitError(_("Cannot write default address") += "\n");
3737 return NULL;
3741 walletInstance->SetBestChain(chainActive.GetLocator());
3743 else if (IsArgSet("-usehd")) {
3744 bool useHD = GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
3745 if (walletInstance->IsHDEnabled() && !useHD) {
3746 InitError(strprintf(_("Error loading %s: You can't disable HD on a already existing HD wallet"), walletFile));
3747 return NULL;
3749 if (!walletInstance->IsHDEnabled() && useHD) {
3750 InitError(strprintf(_("Error loading %s: You can't enable HD on a already existing non-HD wallet"), walletFile));
3751 return NULL;
3755 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
3757 RegisterValidationInterface(walletInstance);
3759 CBlockIndex *pindexRescan = chainActive.Genesis();
3760 if (!GetBoolArg("-rescan", false))
3762 CWalletDB walletdb(walletFile);
3763 CBlockLocator locator;
3764 if (walletdb.ReadBestBlock(locator))
3765 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
3767 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
3769 //We can't rescan beyond non-pruned blocks, stop and throw an error
3770 //this might happen if a user uses a old wallet within a pruned node
3771 // or if he ran -disablewallet for a longer time, then decided to re-enable
3772 if (fPruneMode)
3774 CBlockIndex *block = chainActive.Tip();
3775 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
3776 block = block->pprev;
3778 if (pindexRescan != block) {
3779 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3780 return NULL;
3784 uiInterface.InitMessage(_("Rescanning..."));
3785 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
3786 nStart = GetTimeMillis();
3787 walletInstance->ScanForWalletTransactions(pindexRescan, true);
3788 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
3789 walletInstance->SetBestChain(chainActive.GetLocator());
3790 CWalletDB::IncrementUpdateCounter();
3792 // Restore wallet transaction metadata after -zapwallettxes=1
3793 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
3795 CWalletDB walletdb(walletFile);
3797 BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
3799 uint256 hash = wtxOld.GetHash();
3800 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
3801 if (mi != walletInstance->mapWallet.end())
3803 const CWalletTx* copyFrom = &wtxOld;
3804 CWalletTx* copyTo = &mi->second;
3805 copyTo->mapValue = copyFrom->mapValue;
3806 copyTo->vOrderForm = copyFrom->vOrderForm;
3807 copyTo->nTimeReceived = copyFrom->nTimeReceived;
3808 copyTo->nTimeSmart = copyFrom->nTimeSmart;
3809 copyTo->fFromMe = copyFrom->fFromMe;
3810 copyTo->strFromAccount = copyFrom->strFromAccount;
3811 copyTo->nOrderPos = copyFrom->nOrderPos;
3812 walletdb.WriteTx(*copyTo);
3817 walletInstance->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
3820 LOCK(walletInstance->cs_wallet);
3821 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
3822 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
3823 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
3826 return walletInstance;
3829 bool CWallet::InitLoadWallet()
3831 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
3832 pwalletMain = NULL;
3833 LogPrintf("Wallet disabled!\n");
3834 return true;
3837 std::string walletFile = GetArg("-wallet", DEFAULT_WALLET_DAT);
3839 if (walletFile.find_first_of("/\\") != std::string::npos) {
3840 return InitError(_("-wallet parameter must only specify a filename (not a path)"));
3841 } else if (SanitizeString(walletFile, SAFE_CHARS_FILENAME) != walletFile) {
3842 return InitError(_("Invalid characters in -wallet filename"));
3845 CWallet * const pwallet = CreateWalletFromFile(walletFile);
3846 if (!pwallet) {
3847 return false;
3849 pwalletMain = pwallet;
3851 return true;
3854 std::atomic<bool> CWallet::fFlushScheduled(false);
3856 void CWallet::postInitProcess(CScheduler& scheduler)
3858 // Add wallet transactions that aren't already in a block to mempool
3859 // Do this here as mempool requires genesis block to be loaded
3860 ReacceptWalletTransactions();
3862 // Run a thread to flush wallet periodically
3863 if (!CWallet::fFlushScheduled.exchange(true)) {
3864 scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
3868 bool CWallet::ParameterInteraction()
3870 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
3871 return true;
3873 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && SoftSetBoolArg("-walletbroadcast", false)) {
3874 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
3877 if (GetBoolArg("-salvagewallet", false) && SoftSetBoolArg("-rescan", true)) {
3878 // Rewrite just private keys: rescan to find transactions
3879 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
3882 // -zapwallettx implies a rescan
3883 if (GetBoolArg("-zapwallettxes", false) && SoftSetBoolArg("-rescan", true)) {
3884 LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
3887 if (GetBoolArg("-sysperms", false))
3888 return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
3889 if (GetArg("-prune", 0) && GetBoolArg("-rescan", false))
3890 return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
3892 if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB)
3893 InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
3894 _("The wallet will avoid paying less than the minimum relay fee."));
3896 if (IsArgSet("-mintxfee"))
3898 CAmount n = 0;
3899 if (!ParseMoney(GetArg("-mintxfee", ""), n) || 0 == n)
3900 return InitError(AmountErrMsg("mintxfee", GetArg("-mintxfee", "")));
3901 if (n > HIGH_TX_FEE_PER_KB)
3902 InitWarning(AmountHighWarn("-mintxfee") + " " +
3903 _("This is the minimum transaction fee you pay on every transaction."));
3904 CWallet::minTxFee = CFeeRate(n);
3906 if (IsArgSet("-fallbackfee"))
3908 CAmount nFeePerK = 0;
3909 if (!ParseMoney(GetArg("-fallbackfee", ""), nFeePerK))
3910 return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), GetArg("-fallbackfee", "")));
3911 if (nFeePerK > HIGH_TX_FEE_PER_KB)
3912 InitWarning(AmountHighWarn("-fallbackfee") + " " +
3913 _("This is the transaction fee you may pay when fee estimates are not available."));
3914 CWallet::fallbackFee = CFeeRate(nFeePerK);
3916 if (IsArgSet("-paytxfee"))
3918 CAmount nFeePerK = 0;
3919 if (!ParseMoney(GetArg("-paytxfee", ""), nFeePerK))
3920 return InitError(AmountErrMsg("paytxfee", GetArg("-paytxfee", "")));
3921 if (nFeePerK > HIGH_TX_FEE_PER_KB)
3922 InitWarning(AmountHighWarn("-paytxfee") + " " +
3923 _("This is the transaction fee you will pay if you send a transaction."));
3925 payTxFee = CFeeRate(nFeePerK, 1000);
3926 if (payTxFee < ::minRelayTxFee)
3928 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
3929 GetArg("-paytxfee", ""), ::minRelayTxFee.ToString()));
3932 if (IsArgSet("-maxtxfee"))
3934 CAmount nMaxFee = 0;
3935 if (!ParseMoney(GetArg("-maxtxfee", ""), nMaxFee))
3936 return InitError(AmountErrMsg("maxtxfee", GetArg("-maxtxfee", "")));
3937 if (nMaxFee > HIGH_MAX_TX_FEE)
3938 InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
3939 maxTxFee = nMaxFee;
3940 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
3942 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
3943 GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString()));
3946 nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
3947 bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
3948 fWalletRbf = GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
3950 return true;
3953 bool CWallet::BackupWallet(const std::string& strDest)
3955 if (!fFileBacked)
3956 return false;
3957 while (true)
3960 LOCK(bitdb.cs_db);
3961 if (!bitdb.mapFileUseCount.count(strWalletFile) || bitdb.mapFileUseCount[strWalletFile] == 0)
3963 // Flush log data to the dat file
3964 bitdb.CloseDb(strWalletFile);
3965 bitdb.CheckpointLSN(strWalletFile);
3966 bitdb.mapFileUseCount.erase(strWalletFile);
3968 // Copy wallet file
3969 boost::filesystem::path pathSrc = GetDataDir() / strWalletFile;
3970 boost::filesystem::path pathDest(strDest);
3971 if (boost::filesystem::is_directory(pathDest))
3972 pathDest /= strWalletFile;
3974 try {
3975 boost::filesystem::copy_file(pathSrc, pathDest, boost::filesystem::copy_option::overwrite_if_exists);
3976 LogPrintf("copied %s to %s\n", strWalletFile, pathDest.string());
3977 return true;
3978 } catch (const boost::filesystem::filesystem_error& e) {
3979 LogPrintf("error copying %s to %s - %s\n", strWalletFile, pathDest.string(), e.what());
3980 return false;
3984 MilliSleep(100);
3986 return false;
3989 CKeyPool::CKeyPool()
3991 nTime = GetTime();
3992 fInternal = false;
3995 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
3997 nTime = GetTime();
3998 vchPubKey = vchPubKeyIn;
3999 fInternal = internalIn;
4002 CWalletKey::CWalletKey(int64_t nExpires)
4004 nTimeCreated = (nExpires ? GetTime() : 0);
4005 nTimeExpires = nExpires;
4008 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
4010 // Update the tx's hashBlock
4011 hashBlock = pindex->GetBlockHash();
4013 // set the position of the transaction in the block
4014 nIndex = posInBlock;
4017 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4019 if (hashUnset())
4020 return 0;
4022 AssertLockHeld(cs_main);
4024 // Find the block it claims to be in
4025 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4026 if (mi == mapBlockIndex.end())
4027 return 0;
4028 CBlockIndex* pindex = (*mi).second;
4029 if (!pindex || !chainActive.Contains(pindex))
4030 return 0;
4032 pindexRet = pindex;
4033 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4036 int CMerkleTx::GetBlocksToMaturity() const
4038 if (!IsCoinBase())
4039 return 0;
4040 return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4044 bool CMerkleTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
4046 return ::AcceptToMemoryPool(mempool, state, tx, true, NULL, NULL, false, nAbsurdFee);