Merge #8694: Basic multiwallet support
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blobeb6de4870fa1f0bf11af91e0b311fe4f5465732b
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 "fs.h"
15 #include "key.h"
16 #include "keystore.h"
17 #include "validation.h"
18 #include "net.h"
19 #include "policy/fees.h"
20 #include "policy/policy.h"
21 #include "policy/rbf.h"
22 #include "primitives/block.h"
23 #include "primitives/transaction.h"
24 #include "script/script.h"
25 #include "script/sign.h"
26 #include "scheduler.h"
27 #include "timedata.h"
28 #include "txmempool.h"
29 #include "util.h"
30 #include "ui_interface.h"
31 #include "utilmoneystr.h"
33 #include <assert.h>
35 #include <boost/algorithm/string/replace.hpp>
36 #include <boost/thread.hpp>
38 std::vector<CWalletRef> vpwallets;
39 /** Transaction fee set by the user */
40 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
41 unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
42 bool bSpendZeroConfChange = DEFAULT_SPEND_ZEROCONF_CHANGE;
43 bool fWalletRbf = DEFAULT_WALLET_RBF;
45 const char * DEFAULT_WALLET_DAT = "wallet.dat";
46 const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
48 /**
49 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
50 * Override with -mintxfee
52 CFeeRate CWallet::minTxFee = CFeeRate(DEFAULT_TRANSACTION_MINFEE);
53 /**
54 * If fee estimation does not have enough data to provide estimates, use this fee instead.
55 * Has no effect if not using fee estimation
56 * Override with -fallbackfee
58 CFeeRate CWallet::fallbackFee = CFeeRate(DEFAULT_FALLBACK_FEE);
60 const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
62 /** @defgroup mapWallet
64 * @{
67 struct CompareValueOnly
69 bool operator()(const CInputCoin& t1,
70 const CInputCoin& t2) const
72 return t1.txout.nValue < t2.txout.nValue;
76 std::string COutput::ToString() const
78 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
81 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
83 LOCK(cs_wallet);
84 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
85 if (it == mapWallet.end())
86 return NULL;
87 return &(it->second);
90 CPubKey CWallet::GenerateNewKey(bool internal)
92 AssertLockHeld(cs_wallet); // mapKeyMetadata
93 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
95 CKey secret;
97 // Create new metadata
98 int64_t nCreationTime = GetTime();
99 CKeyMetadata metadata(nCreationTime);
101 // use HD key derivation if HD was enabled during wallet creation
102 if (IsHDEnabled()) {
103 DeriveNewChildKey(metadata, secret, (CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
104 } else {
105 secret.MakeNewKey(fCompressed);
108 // Compressed public keys were introduced in version 0.6.0
109 if (fCompressed)
110 SetMinVersion(FEATURE_COMPRPUBKEY);
112 CPubKey pubkey = secret.GetPubKey();
113 assert(secret.VerifyPubKey(pubkey));
115 mapKeyMetadata[pubkey.GetID()] = metadata;
116 UpdateTimeFirstKey(nCreationTime);
118 if (!AddKeyPubKey(secret, pubkey))
119 throw std::runtime_error(std::string(__func__) + ": AddKey failed");
120 return pubkey;
123 void CWallet::DeriveNewChildKey(CKeyMetadata& metadata, CKey& secret, bool internal)
125 // for now we use a fixed keypath scheme of m/0'/0'/k
126 CKey key; //master key seed (256bit)
127 CExtKey masterKey; //hd master key
128 CExtKey accountKey; //key at m/0'
129 CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
130 CExtKey childKey; //key at m/0'/0'/<n>'
132 // try to get the master key
133 if (!GetKey(hdChain.masterKeyID, key))
134 throw std::runtime_error(std::string(__func__) + ": Master key not found");
136 masterKey.SetMaster(key.begin(), key.size());
138 // derive m/0'
139 // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
140 masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
142 // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
143 assert(internal ? CanSupportFeature(FEATURE_HD_SPLIT) : true);
144 accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
146 // derive child key at next index, skip keys already known to the wallet
147 do {
148 // always derive hardened keys
149 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
150 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
151 if (internal) {
152 chainChildKey.Derive(childKey, hdChain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
153 metadata.hdKeypath = "m/0'/1'/" + std::to_string(hdChain.nInternalChainCounter) + "'";
154 hdChain.nInternalChainCounter++;
156 else {
157 chainChildKey.Derive(childKey, hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
158 metadata.hdKeypath = "m/0'/0'/" + std::to_string(hdChain.nExternalChainCounter) + "'";
159 hdChain.nExternalChainCounter++;
161 } while (HaveKey(childKey.key.GetPubKey().GetID()));
162 secret = childKey.key;
163 metadata.hdMasterKeyID = hdChain.masterKeyID;
164 // update the chain model in the database
165 if (!CWalletDB(*dbw).WriteHDChain(hdChain))
166 throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
169 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
171 AssertLockHeld(cs_wallet); // mapKeyMetadata
172 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
173 return false;
175 // check if we need to remove from watch-only
176 CScript script;
177 script = GetScriptForDestination(pubkey.GetID());
178 if (HaveWatchOnly(script))
179 RemoveWatchOnly(script);
180 script = GetScriptForRawPubKey(pubkey);
181 if (HaveWatchOnly(script))
182 RemoveWatchOnly(script);
184 if (!IsCrypted()) {
185 return CWalletDB(*dbw).WriteKey(pubkey,
186 secret.GetPrivKey(),
187 mapKeyMetadata[pubkey.GetID()]);
189 return true;
192 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
193 const std::vector<unsigned char> &vchCryptedSecret)
195 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
196 return false;
198 LOCK(cs_wallet);
199 if (pwalletdbEncryption)
200 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
201 vchCryptedSecret,
202 mapKeyMetadata[vchPubKey.GetID()]);
203 else
204 return CWalletDB(*dbw).WriteCryptedKey(vchPubKey,
205 vchCryptedSecret,
206 mapKeyMetadata[vchPubKey.GetID()]);
208 return false;
211 bool CWallet::LoadKeyMetadata(const CTxDestination& keyID, const CKeyMetadata &meta)
213 AssertLockHeld(cs_wallet); // mapKeyMetadata
214 UpdateTimeFirstKey(meta.nCreateTime);
215 mapKeyMetadata[keyID] = meta;
216 return true;
219 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
221 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
224 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
226 AssertLockHeld(cs_wallet);
227 if (nCreateTime <= 1) {
228 // Cannot determine birthday information, so set the wallet birthday to
229 // the beginning of time.
230 nTimeFirstKey = 1;
231 } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
232 nTimeFirstKey = nCreateTime;
236 bool CWallet::AddCScript(const CScript& redeemScript)
238 if (!CCryptoKeyStore::AddCScript(redeemScript))
239 return false;
240 return CWalletDB(*dbw).WriteCScript(Hash160(redeemScript), redeemScript);
243 bool CWallet::LoadCScript(const CScript& redeemScript)
245 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
246 * that never can be redeemed. However, old wallets may still contain
247 * these. Do not add them to the wallet and warn. */
248 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
250 std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
251 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",
252 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
253 return true;
256 return CCryptoKeyStore::AddCScript(redeemScript);
259 bool CWallet::AddWatchOnly(const CScript& dest)
261 if (!CCryptoKeyStore::AddWatchOnly(dest))
262 return false;
263 const CKeyMetadata& meta = mapKeyMetadata[CScriptID(dest)];
264 UpdateTimeFirstKey(meta.nCreateTime);
265 NotifyWatchonlyChanged(true);
266 return CWalletDB(*dbw).WriteWatchOnly(dest, meta);
269 bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
271 mapKeyMetadata[CScriptID(dest)].nCreateTime = nCreateTime;
272 return AddWatchOnly(dest);
275 bool CWallet::RemoveWatchOnly(const CScript &dest)
277 AssertLockHeld(cs_wallet);
278 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
279 return false;
280 if (!HaveWatchOnly())
281 NotifyWatchonlyChanged(false);
282 if (!CWalletDB(*dbw).EraseWatchOnly(dest))
283 return false;
285 return true;
288 bool CWallet::LoadWatchOnly(const CScript &dest)
290 return CCryptoKeyStore::AddWatchOnly(dest);
293 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
295 CCrypter crypter;
296 CKeyingMaterial _vMasterKey;
299 LOCK(cs_wallet);
300 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
302 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
303 return false;
304 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
305 continue; // try another master key
306 if (CCryptoKeyStore::Unlock(_vMasterKey))
307 return true;
310 return false;
313 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
315 bool fWasLocked = IsLocked();
318 LOCK(cs_wallet);
319 Lock();
321 CCrypter crypter;
322 CKeyingMaterial _vMasterKey;
323 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
325 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
326 return false;
327 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
328 return false;
329 if (CCryptoKeyStore::Unlock(_vMasterKey))
331 int64_t nStartTime = GetTimeMillis();
332 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
333 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
335 nStartTime = GetTimeMillis();
336 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
337 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
339 if (pMasterKey.second.nDeriveIterations < 25000)
340 pMasterKey.second.nDeriveIterations = 25000;
342 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
344 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
345 return false;
346 if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
347 return false;
348 CWalletDB(*dbw).WriteMasterKey(pMasterKey.first, pMasterKey.second);
349 if (fWasLocked)
350 Lock();
351 return true;
356 return false;
359 void CWallet::SetBestChain(const CBlockLocator& loc)
361 CWalletDB walletdb(*dbw);
362 walletdb.WriteBestBlock(loc);
365 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
367 LOCK(cs_wallet); // nWalletVersion
368 if (nWalletVersion >= nVersion)
369 return true;
371 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
372 if (fExplicit && nVersion > nWalletMaxVersion)
373 nVersion = FEATURE_LATEST;
375 nWalletVersion = nVersion;
377 if (nVersion > nWalletMaxVersion)
378 nWalletMaxVersion = nVersion;
381 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(*dbw);
382 if (nWalletVersion > 40000)
383 pwalletdb->WriteMinVersion(nWalletVersion);
384 if (!pwalletdbIn)
385 delete pwalletdb;
388 return true;
391 bool CWallet::SetMaxVersion(int nVersion)
393 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
394 // cannot downgrade below current version
395 if (nWalletVersion > nVersion)
396 return false;
398 nWalletMaxVersion = nVersion;
400 return true;
403 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
405 std::set<uint256> result;
406 AssertLockHeld(cs_wallet);
408 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
409 if (it == mapWallet.end())
410 return result;
411 const CWalletTx& wtx = it->second;
413 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
415 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
417 if (mapTxSpends.count(txin.prevout) <= 1)
418 continue; // No conflict if zero or one spends
419 range = mapTxSpends.equal_range(txin.prevout);
420 for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
421 result.insert(_it->second);
423 return result;
426 bool CWallet::HasWalletSpend(const uint256& txid) const
428 AssertLockHeld(cs_wallet);
429 auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
430 return (iter != mapTxSpends.end() && iter->first.hash == txid);
433 void CWallet::Flush(bool shutdown)
435 dbw->Flush(shutdown);
438 bool CWallet::Verify()
440 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
441 return true;
443 uiInterface.InitMessage(_("Verifying wallet(s)..."));
445 for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
446 if (boost::filesystem::path(walletFile).filename() != walletFile) {
447 return InitError(_("-wallet parameter must only specify a filename (not a path)"));
448 } else if (SanitizeString(walletFile, SAFE_CHARS_FILENAME) != walletFile) {
449 return InitError(_("Invalid characters in -wallet filename"));
452 std::string strError;
453 if (!CWalletDB::VerifyEnvironment(walletFile, GetDataDir().string(), strError)) {
454 return InitError(strError);
457 if (GetBoolArg("-salvagewallet", false)) {
458 // Recover readable keypairs:
459 CWallet dummyWallet;
460 std::string backup_filename;
461 if (!CWalletDB::Recover(walletFile, (void *)&dummyWallet, CWalletDB::RecoverKeysOnlyFilter, backup_filename)) {
462 return false;
466 std::string strWarning;
467 bool dbV = CWalletDB::VerifyDatabaseFile(walletFile, GetDataDir().string(), strWarning, strError);
468 if (!strWarning.empty()) {
469 InitWarning(strWarning);
471 if (!dbV) {
472 InitError(strError);
473 return false;
477 return true;
480 void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
482 // We want all the wallet transactions in range to have the same metadata as
483 // the oldest (smallest nOrderPos).
484 // So: find smallest nOrderPos:
486 int nMinOrderPos = std::numeric_limits<int>::max();
487 const CWalletTx* copyFrom = NULL;
488 for (TxSpends::iterator it = range.first; it != range.second; ++it)
490 const uint256& hash = it->second;
491 int n = mapWallet[hash].nOrderPos;
492 if (n < nMinOrderPos)
494 nMinOrderPos = n;
495 copyFrom = &mapWallet[hash];
498 // Now copy data from copyFrom to rest:
499 for (TxSpends::iterator it = range.first; it != range.second; ++it)
501 const uint256& hash = it->second;
502 CWalletTx* copyTo = &mapWallet[hash];
503 if (copyFrom == copyTo) continue;
504 if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
505 copyTo->mapValue = copyFrom->mapValue;
506 copyTo->vOrderForm = copyFrom->vOrderForm;
507 // fTimeReceivedIsTxTime not copied on purpose
508 // nTimeReceived not copied on purpose
509 copyTo->nTimeSmart = copyFrom->nTimeSmart;
510 copyTo->fFromMe = copyFrom->fFromMe;
511 copyTo->strFromAccount = copyFrom->strFromAccount;
512 // nOrderPos not copied on purpose
513 // cached members not copied on purpose
518 * Outpoint is spent if any non-conflicted transaction
519 * spends it:
521 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
523 const COutPoint outpoint(hash, n);
524 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
525 range = mapTxSpends.equal_range(outpoint);
527 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
529 const uint256& wtxid = it->second;
530 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
531 if (mit != mapWallet.end()) {
532 int depth = mit->second.GetDepthInMainChain();
533 if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
534 return true; // Spent
537 return false;
540 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
542 mapTxSpends.insert(std::make_pair(outpoint, wtxid));
544 std::pair<TxSpends::iterator, TxSpends::iterator> range;
545 range = mapTxSpends.equal_range(outpoint);
546 SyncMetaData(range);
550 void CWallet::AddToSpends(const uint256& wtxid)
552 assert(mapWallet.count(wtxid));
553 CWalletTx& thisTx = mapWallet[wtxid];
554 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
555 return;
557 BOOST_FOREACH(const CTxIn& txin, thisTx.tx->vin)
558 AddToSpends(txin.prevout, wtxid);
561 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
563 if (IsCrypted())
564 return false;
566 CKeyingMaterial _vMasterKey;
568 _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
569 GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
571 CMasterKey kMasterKey;
573 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
574 GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
576 CCrypter crypter;
577 int64_t nStartTime = GetTimeMillis();
578 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
579 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
581 nStartTime = GetTimeMillis();
582 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
583 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
585 if (kMasterKey.nDeriveIterations < 25000)
586 kMasterKey.nDeriveIterations = 25000;
588 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
590 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
591 return false;
592 if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
593 return false;
596 LOCK(cs_wallet);
597 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
598 assert(!pwalletdbEncryption);
599 pwalletdbEncryption = new CWalletDB(*dbw);
600 if (!pwalletdbEncryption->TxnBegin()) {
601 delete pwalletdbEncryption;
602 pwalletdbEncryption = NULL;
603 return false;
605 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
607 if (!EncryptKeys(_vMasterKey))
609 pwalletdbEncryption->TxnAbort();
610 delete pwalletdbEncryption;
611 // We now probably have half of our keys encrypted in memory, and half not...
612 // die and let the user reload the unencrypted wallet.
613 assert(false);
616 // Encryption was introduced in version 0.4.0
617 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
619 if (!pwalletdbEncryption->TxnCommit()) {
620 delete pwalletdbEncryption;
621 // We now have keys encrypted in memory, but not on disk...
622 // die to avoid confusion and let the user reload the unencrypted wallet.
623 assert(false);
626 delete pwalletdbEncryption;
627 pwalletdbEncryption = NULL;
629 Lock();
630 Unlock(strWalletPassphrase);
632 // if we are using HD, replace the HD master key (seed) with a new one
633 if (IsHDEnabled()) {
634 if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
635 return false;
639 NewKeyPool();
640 Lock();
642 // Need to completely rewrite the wallet file; if we don't, bdb might keep
643 // bits of the unencrypted private key in slack space in the database file.
644 dbw->Rewrite();
647 NotifyStatusChanged(this);
649 return true;
652 DBErrors CWallet::ReorderTransactions()
654 LOCK(cs_wallet);
655 CWalletDB walletdb(*dbw);
657 // Old wallets didn't have any defined order for transactions
658 // Probably a bad idea to change the output of this
660 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
661 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
662 typedef std::multimap<int64_t, TxPair > TxItems;
663 TxItems txByTime;
665 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
667 CWalletTx* wtx = &((*it).second);
668 txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
670 std::list<CAccountingEntry> acentries;
671 walletdb.ListAccountCreditDebit("", acentries);
672 BOOST_FOREACH(CAccountingEntry& entry, acentries)
674 txByTime.insert(std::make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
677 nOrderPosNext = 0;
678 std::vector<int64_t> nOrderPosOffsets;
679 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
681 CWalletTx *const pwtx = (*it).second.first;
682 CAccountingEntry *const pacentry = (*it).second.second;
683 int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
685 if (nOrderPos == -1)
687 nOrderPos = nOrderPosNext++;
688 nOrderPosOffsets.push_back(nOrderPos);
690 if (pwtx)
692 if (!walletdb.WriteTx(*pwtx))
693 return DB_LOAD_FAIL;
695 else
696 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
697 return DB_LOAD_FAIL;
699 else
701 int64_t nOrderPosOff = 0;
702 BOOST_FOREACH(const int64_t& nOffsetStart, nOrderPosOffsets)
704 if (nOrderPos >= nOffsetStart)
705 ++nOrderPosOff;
707 nOrderPos += nOrderPosOff;
708 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
710 if (!nOrderPosOff)
711 continue;
713 // Since we're changing the order, write it back
714 if (pwtx)
716 if (!walletdb.WriteTx(*pwtx))
717 return DB_LOAD_FAIL;
719 else
720 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
721 return DB_LOAD_FAIL;
724 walletdb.WriteOrderPosNext(nOrderPosNext);
726 return DB_LOAD_OK;
729 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
731 AssertLockHeld(cs_wallet); // nOrderPosNext
732 int64_t nRet = nOrderPosNext++;
733 if (pwalletdb) {
734 pwalletdb->WriteOrderPosNext(nOrderPosNext);
735 } else {
736 CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
738 return nRet;
741 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
743 CWalletDB walletdb(*dbw);
744 if (!walletdb.TxnBegin())
745 return false;
747 int64_t nNow = GetAdjustedTime();
749 // Debit
750 CAccountingEntry debit;
751 debit.nOrderPos = IncOrderPosNext(&walletdb);
752 debit.strAccount = strFrom;
753 debit.nCreditDebit = -nAmount;
754 debit.nTime = nNow;
755 debit.strOtherAccount = strTo;
756 debit.strComment = strComment;
757 AddAccountingEntry(debit, &walletdb);
759 // Credit
760 CAccountingEntry credit;
761 credit.nOrderPos = IncOrderPosNext(&walletdb);
762 credit.strAccount = strTo;
763 credit.nCreditDebit = nAmount;
764 credit.nTime = nNow;
765 credit.strOtherAccount = strFrom;
766 credit.strComment = strComment;
767 AddAccountingEntry(credit, &walletdb);
769 if (!walletdb.TxnCommit())
770 return false;
772 return true;
775 bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
777 CWalletDB walletdb(*dbw);
779 CAccount account;
780 walletdb.ReadAccount(strAccount, account);
782 if (!bForceNew) {
783 if (!account.vchPubKey.IsValid())
784 bForceNew = true;
785 else {
786 // Check if the current key has been used
787 CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
788 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
789 it != mapWallet.end() && account.vchPubKey.IsValid();
790 ++it)
791 BOOST_FOREACH(const CTxOut& txout, (*it).second.tx->vout)
792 if (txout.scriptPubKey == scriptPubKey) {
793 bForceNew = true;
794 break;
799 // Generate a new key
800 if (bForceNew) {
801 if (!GetKeyFromPool(account.vchPubKey, false))
802 return false;
804 SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
805 walletdb.WriteAccount(strAccount, account);
808 pubKey = account.vchPubKey;
810 return true;
813 void CWallet::MarkDirty()
816 LOCK(cs_wallet);
817 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
818 item.second.MarkDirty();
822 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
824 LOCK(cs_wallet);
826 auto mi = mapWallet.find(originalHash);
828 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
829 assert(mi != mapWallet.end());
831 CWalletTx& wtx = (*mi).second;
833 // Ensure for now that we're not overwriting data
834 assert(wtx.mapValue.count("replaced_by_txid") == 0);
836 wtx.mapValue["replaced_by_txid"] = newHash.ToString();
838 CWalletDB walletdb(*dbw, "r+");
840 bool success = true;
841 if (!walletdb.WriteTx(wtx)) {
842 LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
843 success = false;
846 NotifyTransactionChanged(this, originalHash, CT_UPDATED);
848 return success;
851 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
853 LOCK(cs_wallet);
855 CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
857 uint256 hash = wtxIn.GetHash();
859 // Inserts only if not already there, returns tx inserted or tx found
860 std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
861 CWalletTx& wtx = (*ret.first).second;
862 wtx.BindWallet(this);
863 bool fInsertedNew = ret.second;
864 if (fInsertedNew)
866 wtx.nTimeReceived = GetAdjustedTime();
867 wtx.nOrderPos = IncOrderPosNext(&walletdb);
868 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
869 wtx.nTimeSmart = ComputeTimeSmart(wtx);
870 AddToSpends(hash);
873 bool fUpdated = false;
874 if (!fInsertedNew)
876 // Merge
877 if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
879 wtx.hashBlock = wtxIn.hashBlock;
880 fUpdated = true;
882 // If no longer abandoned, update
883 if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
885 wtx.hashBlock = wtxIn.hashBlock;
886 fUpdated = true;
888 if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
890 wtx.nIndex = wtxIn.nIndex;
891 fUpdated = true;
893 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
895 wtx.fFromMe = wtxIn.fFromMe;
896 fUpdated = true;
900 //// debug print
901 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
903 // Write to disk
904 if (fInsertedNew || fUpdated)
905 if (!walletdb.WriteTx(wtx))
906 return false;
908 // Break debit/credit balance caches:
909 wtx.MarkDirty();
911 // Notify UI of new or updated transaction
912 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
914 // notify an external script when a wallet transaction comes in or is updated
915 std::string strCmd = GetArg("-walletnotify", "");
917 if ( !strCmd.empty())
919 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
920 boost::thread t(runCommand, strCmd); // thread runs free
923 return true;
926 bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
928 uint256 hash = wtxIn.GetHash();
930 mapWallet[hash] = wtxIn;
931 CWalletTx& wtx = mapWallet[hash];
932 wtx.BindWallet(this);
933 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
934 AddToSpends(hash);
935 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin) {
936 if (mapWallet.count(txin.prevout.hash)) {
937 CWalletTx& prevtx = mapWallet[txin.prevout.hash];
938 if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
939 MarkConflicted(prevtx.hashBlock, wtx.GetHash());
944 return true;
948 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
949 * be set when the transaction was known to be included in a block. When
950 * pIndex == NULL, then wallet state is not updated in AddToWallet, but
951 * notifications happen and cached balances are marked dirty.
953 * If fUpdate is true, existing transactions will be updated.
954 * TODO: One exception to this is that the abandoned state is cleared under the
955 * assumption that any further notification of a transaction that was considered
956 * abandoned is an indication that it is not safe to be considered abandoned.
957 * Abandoned state should probably be more carefully tracked via different
958 * posInBlock signals or by checking mempool presence when necessary.
960 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
962 const CTransaction& tx = *ptx;
964 AssertLockHeld(cs_wallet);
966 if (pIndex != NULL) {
967 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
968 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
969 while (range.first != range.second) {
970 if (range.first->second != tx.GetHash()) {
971 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);
972 MarkConflicted(pIndex->GetBlockHash(), range.first->second);
974 range.first++;
979 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
980 if (fExisted && !fUpdate) return false;
981 if (fExisted || IsMine(tx) || IsFromMe(tx))
983 CWalletTx wtx(this, ptx);
985 // Get merkle branch if transaction was found in a block
986 if (pIndex != NULL)
987 wtx.SetMerkleBranch(pIndex, posInBlock);
989 return AddToWallet(wtx, false);
992 return false;
995 bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
997 LOCK2(cs_main, cs_wallet);
998 const CWalletTx* wtx = GetWalletTx(hashTx);
999 return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() <= 0 && !wtx->InMempool();
1002 bool CWallet::AbandonTransaction(const uint256& hashTx)
1004 LOCK2(cs_main, cs_wallet);
1006 CWalletDB walletdb(*dbw, "r+");
1008 std::set<uint256> todo;
1009 std::set<uint256> done;
1011 // Can't mark abandoned if confirmed or in mempool
1012 assert(mapWallet.count(hashTx));
1013 CWalletTx& origtx = mapWallet[hashTx];
1014 if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
1015 return false;
1018 todo.insert(hashTx);
1020 while (!todo.empty()) {
1021 uint256 now = *todo.begin();
1022 todo.erase(now);
1023 done.insert(now);
1024 assert(mapWallet.count(now));
1025 CWalletTx& wtx = mapWallet[now];
1026 int currentconfirm = wtx.GetDepthInMainChain();
1027 // If the orig tx was not in block, none of its spends can be
1028 assert(currentconfirm <= 0);
1029 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1030 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1031 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1032 assert(!wtx.InMempool());
1033 wtx.nIndex = -1;
1034 wtx.setAbandoned();
1035 wtx.MarkDirty();
1036 walletdb.WriteTx(wtx);
1037 NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1038 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1039 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1040 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1041 if (!done.count(iter->second)) {
1042 todo.insert(iter->second);
1044 iter++;
1046 // If a transaction changes 'conflicted' state, that changes the balance
1047 // available of the outputs it spends. So force those to be recomputed
1048 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
1050 if (mapWallet.count(txin.prevout.hash))
1051 mapWallet[txin.prevout.hash].MarkDirty();
1056 return true;
1059 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1061 LOCK2(cs_main, cs_wallet);
1063 int conflictconfirms = 0;
1064 if (mapBlockIndex.count(hashBlock)) {
1065 CBlockIndex* pindex = mapBlockIndex[hashBlock];
1066 if (chainActive.Contains(pindex)) {
1067 conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1070 // If number of conflict confirms cannot be determined, this means
1071 // that the block is still unknown or not yet part of the main chain,
1072 // for example when loading the wallet during a reindex. Do nothing in that
1073 // case.
1074 if (conflictconfirms >= 0)
1075 return;
1077 // Do not flush the wallet here for performance reasons
1078 CWalletDB walletdb(*dbw, "r+", false);
1080 std::set<uint256> todo;
1081 std::set<uint256> done;
1083 todo.insert(hashTx);
1085 while (!todo.empty()) {
1086 uint256 now = *todo.begin();
1087 todo.erase(now);
1088 done.insert(now);
1089 assert(mapWallet.count(now));
1090 CWalletTx& wtx = mapWallet[now];
1091 int currentconfirm = wtx.GetDepthInMainChain();
1092 if (conflictconfirms < currentconfirm) {
1093 // Block is 'more conflicted' than current confirm; update.
1094 // Mark transaction as conflicted with this block.
1095 wtx.nIndex = -1;
1096 wtx.hashBlock = hashBlock;
1097 wtx.MarkDirty();
1098 walletdb.WriteTx(wtx);
1099 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1100 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1101 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1102 if (!done.count(iter->second)) {
1103 todo.insert(iter->second);
1105 iter++;
1107 // If a transaction changes 'conflicted' state, that changes the balance
1108 // available of the outputs it spends. So force those to be recomputed
1109 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
1111 if (mapWallet.count(txin.prevout.hash))
1112 mapWallet[txin.prevout.hash].MarkDirty();
1118 void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
1119 const CTransaction& tx = *ptx;
1121 if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
1122 return; // Not one of ours
1124 // If a transaction changes 'conflicted' state, that changes the balance
1125 // available of the outputs it spends. So force those to be
1126 // recomputed, also:
1127 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1129 if (mapWallet.count(txin.prevout.hash))
1130 mapWallet[txin.prevout.hash].MarkDirty();
1134 void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx) {
1135 LOCK2(cs_main, cs_wallet);
1136 SyncTransaction(ptx);
1139 void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
1140 LOCK2(cs_main, cs_wallet);
1141 // TODO: Temporarily ensure that mempool removals are notified before
1142 // connected transactions. This shouldn't matter, but the abandoned
1143 // state of transactions in our wallet is currently cleared when we
1144 // receive another notification and there is a race condition where
1145 // notification of a connected conflict might cause an outside process
1146 // to abandon a transaction and then have it inadvertently cleared by
1147 // the notification that the conflicted transaction was evicted.
1149 for (const CTransactionRef& ptx : vtxConflicted) {
1150 SyncTransaction(ptx);
1152 for (size_t i = 0; i < pblock->vtx.size(); i++) {
1153 SyncTransaction(pblock->vtx[i], pindex, i);
1157 void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
1158 LOCK2(cs_main, cs_wallet);
1160 for (const CTransactionRef& ptx : pblock->vtx) {
1161 SyncTransaction(ptx);
1167 isminetype CWallet::IsMine(const CTxIn &txin) const
1170 LOCK(cs_wallet);
1171 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1172 if (mi != mapWallet.end())
1174 const CWalletTx& prev = (*mi).second;
1175 if (txin.prevout.n < prev.tx->vout.size())
1176 return IsMine(prev.tx->vout[txin.prevout.n]);
1179 return ISMINE_NO;
1182 // Note that this function doesn't distinguish between a 0-valued input,
1183 // and a not-"is mine" (according to the filter) input.
1184 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1187 LOCK(cs_wallet);
1188 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1189 if (mi != mapWallet.end())
1191 const CWalletTx& prev = (*mi).second;
1192 if (txin.prevout.n < prev.tx->vout.size())
1193 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1194 return prev.tx->vout[txin.prevout.n].nValue;
1197 return 0;
1200 isminetype CWallet::IsMine(const CTxOut& txout) const
1202 return ::IsMine(*this, txout.scriptPubKey);
1205 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1207 if (!MoneyRange(txout.nValue))
1208 throw std::runtime_error(std::string(__func__) + ": value out of range");
1209 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1212 bool CWallet::IsChange(const CTxOut& txout) const
1214 // TODO: fix handling of 'change' outputs. The assumption is that any
1215 // payment to a script that is ours, but is not in the address book
1216 // is change. That assumption is likely to break when we implement multisignature
1217 // wallets that return change back into a multi-signature-protected address;
1218 // a better way of identifying which outputs are 'the send' and which are
1219 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1220 // which output, if any, was change).
1221 if (::IsMine(*this, txout.scriptPubKey))
1223 CTxDestination address;
1224 if (!ExtractDestination(txout.scriptPubKey, address))
1225 return true;
1227 LOCK(cs_wallet);
1228 if (!mapAddressBook.count(address))
1229 return true;
1231 return false;
1234 CAmount CWallet::GetChange(const CTxOut& txout) const
1236 if (!MoneyRange(txout.nValue))
1237 throw std::runtime_error(std::string(__func__) + ": value out of range");
1238 return (IsChange(txout) ? txout.nValue : 0);
1241 bool CWallet::IsMine(const CTransaction& tx) const
1243 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1244 if (IsMine(txout))
1245 return true;
1246 return false;
1249 bool CWallet::IsFromMe(const CTransaction& tx) const
1251 return (GetDebit(tx, ISMINE_ALL) > 0);
1254 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1256 CAmount nDebit = 0;
1257 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1259 nDebit += GetDebit(txin, filter);
1260 if (!MoneyRange(nDebit))
1261 throw std::runtime_error(std::string(__func__) + ": value out of range");
1263 return nDebit;
1266 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1268 LOCK(cs_wallet);
1270 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1272 auto mi = mapWallet.find(txin.prevout.hash);
1273 if (mi == mapWallet.end())
1274 return false; // any unknown inputs can't be from us
1276 const CWalletTx& prev = (*mi).second;
1278 if (txin.prevout.n >= prev.tx->vout.size())
1279 return false; // invalid input!
1281 if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1282 return false;
1284 return true;
1287 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1289 CAmount nCredit = 0;
1290 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1292 nCredit += GetCredit(txout, filter);
1293 if (!MoneyRange(nCredit))
1294 throw std::runtime_error(std::string(__func__) + ": value out of range");
1296 return nCredit;
1299 CAmount CWallet::GetChange(const CTransaction& tx) const
1301 CAmount nChange = 0;
1302 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1304 nChange += GetChange(txout);
1305 if (!MoneyRange(nChange))
1306 throw std::runtime_error(std::string(__func__) + ": value out of range");
1308 return nChange;
1311 CPubKey CWallet::GenerateNewHDMasterKey()
1313 CKey key;
1314 key.MakeNewKey(true);
1316 int64_t nCreationTime = GetTime();
1317 CKeyMetadata metadata(nCreationTime);
1319 // calculate the pubkey
1320 CPubKey pubkey = key.GetPubKey();
1321 assert(key.VerifyPubKey(pubkey));
1323 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1324 metadata.hdKeypath = "m";
1325 metadata.hdMasterKeyID = pubkey.GetID();
1328 LOCK(cs_wallet);
1330 // mem store the metadata
1331 mapKeyMetadata[pubkey.GetID()] = metadata;
1333 // write the key&metadata to the database
1334 if (!AddKeyPubKey(key, pubkey))
1335 throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1338 return pubkey;
1341 bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
1343 LOCK(cs_wallet);
1344 // store the keyid (hash160) together with
1345 // the child index counter in the database
1346 // as a hdchain object
1347 CHDChain newHdChain;
1348 newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1349 newHdChain.masterKeyID = pubkey.GetID();
1350 SetHDChain(newHdChain, false);
1352 return true;
1355 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1357 LOCK(cs_wallet);
1358 if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
1359 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1361 hdChain = chain;
1362 return true;
1365 bool CWallet::IsHDEnabled() const
1367 return !hdChain.masterKeyID.IsNull();
1370 int64_t CWalletTx::GetTxTime() const
1372 int64_t n = nTimeSmart;
1373 return n ? n : nTimeReceived;
1376 int CWalletTx::GetRequestCount() const
1378 // Returns -1 if it wasn't being tracked
1379 int nRequests = -1;
1381 LOCK(pwallet->cs_wallet);
1382 if (IsCoinBase())
1384 // Generated block
1385 if (!hashUnset())
1387 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1388 if (mi != pwallet->mapRequestCount.end())
1389 nRequests = (*mi).second;
1392 else
1394 // Did anyone request this transaction?
1395 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1396 if (mi != pwallet->mapRequestCount.end())
1398 nRequests = (*mi).second;
1400 // How about the block it's in?
1401 if (nRequests == 0 && !hashUnset())
1403 std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1404 if (_mi != pwallet->mapRequestCount.end())
1405 nRequests = (*_mi).second;
1406 else
1407 nRequests = 1; // If it's in someone else's block it must have got out
1412 return nRequests;
1415 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1416 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1418 nFee = 0;
1419 listReceived.clear();
1420 listSent.clear();
1421 strSentAccount = strFromAccount;
1423 // Compute fee:
1424 CAmount nDebit = GetDebit(filter);
1425 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1427 CAmount nValueOut = tx->GetValueOut();
1428 nFee = nDebit - nValueOut;
1431 // Sent/received.
1432 for (unsigned int i = 0; i < tx->vout.size(); ++i)
1434 const CTxOut& txout = tx->vout[i];
1435 isminetype fIsMine = pwallet->IsMine(txout);
1436 // Only need to handle txouts if AT LEAST one of these is true:
1437 // 1) they debit from us (sent)
1438 // 2) the output is to us (received)
1439 if (nDebit > 0)
1441 // Don't report 'change' txouts
1442 if (pwallet->IsChange(txout))
1443 continue;
1445 else if (!(fIsMine & filter))
1446 continue;
1448 // In either case, we need to get the destination address
1449 CTxDestination address;
1451 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1453 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1454 this->GetHash().ToString());
1455 address = CNoDestination();
1458 COutputEntry output = {address, txout.nValue, (int)i};
1460 // If we are debited by the transaction, add the output as a "sent" entry
1461 if (nDebit > 0)
1462 listSent.push_back(output);
1464 // If we are receiving the output, add it as a "received" entry
1465 if (fIsMine & filter)
1466 listReceived.push_back(output);
1472 * Scan the block chain (starting in pindexStart) for transactions
1473 * from or to us. If fUpdate is true, found transactions that already
1474 * exist in the wallet will be updated.
1476 * Returns null if scan was successful. Otherwise, if a complete rescan was not
1477 * possible (due to pruning or corruption), returns pointer to the most recent
1478 * block that could not be scanned.
1480 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1482 int64_t nNow = GetTime();
1483 const CChainParams& chainParams = Params();
1485 CBlockIndex* pindex = pindexStart;
1486 CBlockIndex* ret = nullptr;
1488 LOCK2(cs_main, cs_wallet);
1489 fAbortRescan = false;
1490 fScanningWallet = true;
1492 // no need to read and scan block, if block was created before
1493 // our wallet birthday (as adjusted for block time variability)
1494 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - TIMESTAMP_WINDOW)))
1495 pindex = chainActive.Next(pindex);
1497 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1498 double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
1499 double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
1500 while (pindex && !fAbortRescan)
1502 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1503 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1504 if (GetTime() >= nNow + 60) {
1505 nNow = GetTime();
1506 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1509 CBlock block;
1510 if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
1511 for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1512 AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
1514 } else {
1515 ret = pindex;
1517 pindex = chainActive.Next(pindex);
1519 if (pindex && fAbortRescan) {
1520 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1522 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1524 fScanningWallet = false;
1526 return ret;
1529 void CWallet::ReacceptWalletTransactions()
1531 // If transactions aren't being broadcasted, don't let them into local mempool either
1532 if (!fBroadcastTransactions)
1533 return;
1534 LOCK2(cs_main, cs_wallet);
1535 std::map<int64_t, CWalletTx*> mapSorted;
1537 // Sort pending wallet transactions based on their initial wallet insertion order
1538 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1540 const uint256& wtxid = item.first;
1541 CWalletTx& wtx = item.second;
1542 assert(wtx.GetHash() == wtxid);
1544 int nDepth = wtx.GetDepthInMainChain();
1546 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1547 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1551 // Try to add wallet transactions to memory pool
1552 BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
1554 CWalletTx& wtx = *(item.second);
1556 LOCK(mempool.cs);
1557 CValidationState state;
1558 wtx.AcceptToMemoryPool(maxTxFee, state);
1562 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1564 assert(pwallet->GetBroadcastTransactions());
1565 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1567 CValidationState state;
1568 /* GetDepthInMainChain already catches known conflicts. */
1569 if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1570 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1571 if (connman) {
1572 CInv inv(MSG_TX, GetHash());
1573 connman->ForEachNode([&inv](CNode* pnode)
1575 pnode->PushInventory(inv);
1577 return true;
1581 return false;
1584 std::set<uint256> CWalletTx::GetConflicts() const
1586 std::set<uint256> result;
1587 if (pwallet != NULL)
1589 uint256 myHash = GetHash();
1590 result = pwallet->GetConflicts(myHash);
1591 result.erase(myHash);
1593 return result;
1596 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1598 if (tx->vin.empty())
1599 return 0;
1601 CAmount debit = 0;
1602 if(filter & ISMINE_SPENDABLE)
1604 if (fDebitCached)
1605 debit += nDebitCached;
1606 else
1608 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1609 fDebitCached = true;
1610 debit += nDebitCached;
1613 if(filter & ISMINE_WATCH_ONLY)
1615 if(fWatchDebitCached)
1616 debit += nWatchDebitCached;
1617 else
1619 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1620 fWatchDebitCached = true;
1621 debit += nWatchDebitCached;
1624 return debit;
1627 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1629 // Must wait until coinbase is safely deep enough in the chain before valuing it
1630 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1631 return 0;
1633 CAmount credit = 0;
1634 if (filter & ISMINE_SPENDABLE)
1636 // GetBalance can assume transactions in mapWallet won't change
1637 if (fCreditCached)
1638 credit += nCreditCached;
1639 else
1641 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1642 fCreditCached = true;
1643 credit += nCreditCached;
1646 if (filter & ISMINE_WATCH_ONLY)
1648 if (fWatchCreditCached)
1649 credit += nWatchCreditCached;
1650 else
1652 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1653 fWatchCreditCached = true;
1654 credit += nWatchCreditCached;
1657 return credit;
1660 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1662 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1664 if (fUseCache && fImmatureCreditCached)
1665 return nImmatureCreditCached;
1666 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1667 fImmatureCreditCached = true;
1668 return nImmatureCreditCached;
1671 return 0;
1674 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1676 if (pwallet == 0)
1677 return 0;
1679 // Must wait until coinbase is safely deep enough in the chain before valuing it
1680 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1681 return 0;
1683 if (fUseCache && fAvailableCreditCached)
1684 return nAvailableCreditCached;
1686 CAmount nCredit = 0;
1687 uint256 hashTx = GetHash();
1688 for (unsigned int i = 0; i < tx->vout.size(); i++)
1690 if (!pwallet->IsSpent(hashTx, i))
1692 const CTxOut &txout = tx->vout[i];
1693 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1694 if (!MoneyRange(nCredit))
1695 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1699 nAvailableCreditCached = nCredit;
1700 fAvailableCreditCached = true;
1701 return nCredit;
1704 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1706 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1708 if (fUseCache && fImmatureWatchCreditCached)
1709 return nImmatureWatchCreditCached;
1710 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1711 fImmatureWatchCreditCached = true;
1712 return nImmatureWatchCreditCached;
1715 return 0;
1718 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1720 if (pwallet == 0)
1721 return 0;
1723 // Must wait until coinbase is safely deep enough in the chain before valuing it
1724 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1725 return 0;
1727 if (fUseCache && fAvailableWatchCreditCached)
1728 return nAvailableWatchCreditCached;
1730 CAmount nCredit = 0;
1731 for (unsigned int i = 0; i < tx->vout.size(); i++)
1733 if (!pwallet->IsSpent(GetHash(), i))
1735 const CTxOut &txout = tx->vout[i];
1736 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1737 if (!MoneyRange(nCredit))
1738 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1742 nAvailableWatchCreditCached = nCredit;
1743 fAvailableWatchCreditCached = true;
1744 return nCredit;
1747 CAmount CWalletTx::GetChange() const
1749 if (fChangeCached)
1750 return nChangeCached;
1751 nChangeCached = pwallet->GetChange(*this);
1752 fChangeCached = true;
1753 return nChangeCached;
1756 bool CWalletTx::InMempool() const
1758 LOCK(mempool.cs);
1759 return mempool.exists(GetHash());
1762 bool CWalletTx::IsTrusted() const
1764 // Quick answer in most cases
1765 if (!CheckFinalTx(*this))
1766 return false;
1767 int nDepth = GetDepthInMainChain();
1768 if (nDepth >= 1)
1769 return true;
1770 if (nDepth < 0)
1771 return false;
1772 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1773 return false;
1775 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1776 if (!InMempool())
1777 return false;
1779 // Trusted if all inputs are from us and are in the mempool:
1780 BOOST_FOREACH(const CTxIn& txin, tx->vin)
1782 // Transactions not sent by us: not trusted
1783 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1784 if (parent == NULL)
1785 return false;
1786 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1787 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1788 return false;
1790 return true;
1793 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1795 CMutableTransaction tx1 = *this->tx;
1796 CMutableTransaction tx2 = *_tx.tx;
1797 for (auto& txin : tx1.vin) txin.scriptSig = CScript();
1798 for (auto& txin : tx2.vin) txin.scriptSig = CScript();
1799 return CTransaction(tx1) == CTransaction(tx2);
1802 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1804 std::vector<uint256> result;
1806 LOCK(cs_wallet);
1807 // Sort them in chronological order
1808 std::multimap<unsigned int, CWalletTx*> mapSorted;
1809 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1811 CWalletTx& wtx = item.second;
1812 // Don't rebroadcast if newer than nTime:
1813 if (wtx.nTimeReceived > nTime)
1814 continue;
1815 mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1817 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1819 CWalletTx& wtx = *item.second;
1820 if (wtx.RelayWalletTransaction(connman))
1821 result.push_back(wtx.GetHash());
1823 return result;
1826 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1828 // Do this infrequently and randomly to avoid giving away
1829 // that these are our transactions.
1830 if (GetTime() < nNextResend || !fBroadcastTransactions)
1831 return;
1832 bool fFirst = (nNextResend == 0);
1833 nNextResend = GetTime() + GetRand(30 * 60);
1834 if (fFirst)
1835 return;
1837 // Only do it if there's been a new block since last time
1838 if (nBestBlockTime < nLastResend)
1839 return;
1840 nLastResend = GetTime();
1842 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1843 // block was found:
1844 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
1845 if (!relayed.empty())
1846 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
1849 /** @} */ // end of mapWallet
1854 /** @defgroup Actions
1856 * @{
1860 CAmount CWallet::GetBalance() const
1862 CAmount nTotal = 0;
1864 LOCK2(cs_main, cs_wallet);
1865 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1867 const CWalletTx* pcoin = &(*it).second;
1868 if (pcoin->IsTrusted())
1869 nTotal += pcoin->GetAvailableCredit();
1873 return nTotal;
1876 CAmount CWallet::GetUnconfirmedBalance() const
1878 CAmount nTotal = 0;
1880 LOCK2(cs_main, cs_wallet);
1881 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1883 const CWalletTx* pcoin = &(*it).second;
1884 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1885 nTotal += pcoin->GetAvailableCredit();
1888 return nTotal;
1891 CAmount CWallet::GetImmatureBalance() const
1893 CAmount nTotal = 0;
1895 LOCK2(cs_main, cs_wallet);
1896 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1898 const CWalletTx* pcoin = &(*it).second;
1899 nTotal += pcoin->GetImmatureCredit();
1902 return nTotal;
1905 CAmount CWallet::GetWatchOnlyBalance() const
1907 CAmount nTotal = 0;
1909 LOCK2(cs_main, cs_wallet);
1910 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1912 const CWalletTx* pcoin = &(*it).second;
1913 if (pcoin->IsTrusted())
1914 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1918 return nTotal;
1921 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
1923 CAmount nTotal = 0;
1925 LOCK2(cs_main, cs_wallet);
1926 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1928 const CWalletTx* pcoin = &(*it).second;
1929 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1930 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1933 return nTotal;
1936 CAmount CWallet::GetImmatureWatchOnlyBalance() const
1938 CAmount nTotal = 0;
1940 LOCK2(cs_main, cs_wallet);
1941 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1943 const CWalletTx* pcoin = &(*it).second;
1944 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1947 return nTotal;
1950 // Calculate total balance in a different way from GetBalance. The biggest
1951 // difference is that GetBalance sums up all unspent TxOuts paying to the
1952 // wallet, while this sums up both spent and unspent TxOuts paying to the
1953 // wallet, and then subtracts the values of TxIns spending from the wallet. This
1954 // also has fewer restrictions on which unconfirmed transactions are considered
1955 // trusted.
1956 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
1958 LOCK2(cs_main, cs_wallet);
1960 CAmount balance = 0;
1961 for (const auto& entry : mapWallet) {
1962 const CWalletTx& wtx = entry.second;
1963 const int depth = wtx.GetDepthInMainChain();
1964 if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
1965 continue;
1968 // Loop through tx outputs and add incoming payments. For outgoing txs,
1969 // treat change outputs specially, as part of the amount debited.
1970 CAmount debit = wtx.GetDebit(filter);
1971 const bool outgoing = debit > 0;
1972 for (const CTxOut& out : wtx.tx->vout) {
1973 if (outgoing && IsChange(out)) {
1974 debit -= out.nValue;
1975 } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
1976 balance += out.nValue;
1980 // For outgoing txs, subtract amount debited.
1981 if (outgoing && (!account || *account == wtx.strFromAccount)) {
1982 balance -= debit;
1986 if (account) {
1987 balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
1990 return balance;
1993 CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
1995 LOCK2(cs_main, cs_wallet);
1997 CAmount balance = 0;
1998 std::vector<COutput> vCoins;
1999 AvailableCoins(vCoins, true, coinControl);
2000 for (const COutput& out : vCoins) {
2001 if (out.fSpendable) {
2002 balance += out.tx->tx->vout[out.i].nValue;
2005 return balance;
2008 void CWallet::AvailableCoins(std::vector<COutput> &vCoins, bool fOnlySafe, const CCoinControl *coinControl, const CAmount &nMinimumAmount, const CAmount &nMaximumAmount, const CAmount &nMinimumSumAmount, const uint64_t &nMaximumCount, const int &nMinDepth, const int &nMaxDepth) const
2010 vCoins.clear();
2013 LOCK2(cs_main, cs_wallet);
2015 CAmount nTotal = 0;
2017 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2019 const uint256& wtxid = it->first;
2020 const CWalletTx* pcoin = &(*it).second;
2022 if (!CheckFinalTx(*pcoin))
2023 continue;
2025 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2026 continue;
2028 int nDepth = pcoin->GetDepthInMainChain();
2029 if (nDepth < 0)
2030 continue;
2032 // We should not consider coins which aren't at least in our mempool
2033 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2034 if (nDepth == 0 && !pcoin->InMempool())
2035 continue;
2037 bool safeTx = pcoin->IsTrusted();
2039 // We should not consider coins from transactions that are replacing
2040 // other transactions.
2042 // Example: There is a transaction A which is replaced by bumpfee
2043 // transaction B. In this case, we want to prevent creation of
2044 // a transaction B' which spends an output of B.
2046 // Reason: If transaction A were initially confirmed, transactions B
2047 // and B' would no longer be valid, so the user would have to create
2048 // a new transaction C to replace B'. However, in the case of a
2049 // one-block reorg, transactions B' and C might BOTH be accepted,
2050 // when the user only wanted one of them. Specifically, there could
2051 // be a 1-block reorg away from the chain where transactions A and C
2052 // were accepted to another chain where B, B', and C were all
2053 // accepted.
2054 if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2055 safeTx = false;
2058 // Similarly, we should not consider coins from transactions that
2059 // have been replaced. In the example above, we would want to prevent
2060 // creation of a transaction A' spending an output of A, because if
2061 // transaction B were initially confirmed, conflicting with A and
2062 // A', we wouldn't want to the user to create a transaction D
2063 // intending to replace A', but potentially resulting in a scenario
2064 // where A, A', and D could all be accepted (instead of just B and
2065 // D, or just A and A' like the user would want).
2066 if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2067 safeTx = false;
2070 if (fOnlySafe && !safeTx) {
2071 continue;
2074 if (nDepth < nMinDepth || nDepth > nMaxDepth)
2075 continue;
2077 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2078 if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2079 continue;
2081 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint((*it).first, i)))
2082 continue;
2084 if (IsLockedCoin((*it).first, i))
2085 continue;
2087 if (IsSpent(wtxid, i))
2088 continue;
2090 isminetype mine = IsMine(pcoin->tx->vout[i]);
2092 if (mine == ISMINE_NO) {
2093 continue;
2096 bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2097 bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2099 vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2101 // Checks the sum amount of all UTXO's.
2102 if (nMinimumSumAmount != MAX_MONEY) {
2103 nTotal += pcoin->tx->vout[i].nValue;
2105 if (nTotal >= nMinimumSumAmount) {
2106 return;
2110 // Checks the maximum number of UTXO's.
2111 if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2112 return;
2119 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2121 // TODO: Add AssertLockHeld(cs_wallet) here.
2123 // Because the return value from this function contains pointers to
2124 // CWalletTx objects, callers to this function really should acquire the
2125 // cs_wallet lock before calling it. However, the current caller doesn't
2126 // acquire this lock yet. There was an attempt to add the missing lock in
2127 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2128 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2129 // avoid adding some extra complexity to the Qt code.
2131 std::map<CTxDestination, std::vector<COutput>> result;
2133 std::vector<COutput> availableCoins;
2134 AvailableCoins(availableCoins);
2136 LOCK2(cs_main, cs_wallet);
2137 for (auto& coin : availableCoins) {
2138 CTxDestination address;
2139 if (coin.fSpendable &&
2140 ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2141 result[address].emplace_back(std::move(coin));
2145 std::vector<COutPoint> lockedCoins;
2146 ListLockedCoins(lockedCoins);
2147 for (const auto& output : lockedCoins) {
2148 auto it = mapWallet.find(output.hash);
2149 if (it != mapWallet.end()) {
2150 int depth = it->second.GetDepthInMainChain();
2151 if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2152 IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2153 CTxDestination address;
2154 if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2155 result[address].emplace_back(
2156 &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2162 return result;
2165 const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
2167 const CTransaction* ptx = &tx;
2168 int n = output;
2169 while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2170 const COutPoint& prevout = ptx->vin[0].prevout;
2171 auto it = mapWallet.find(prevout.hash);
2172 if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2173 !IsMine(it->second.tx->vout[prevout.n])) {
2174 break;
2176 ptx = it->second.tx.get();
2177 n = prevout.n;
2179 return ptx->vout[n];
2182 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2183 std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2185 std::vector<char> vfIncluded;
2187 vfBest.assign(vValue.size(), true);
2188 nBest = nTotalLower;
2190 FastRandomContext insecure_rand;
2192 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2194 vfIncluded.assign(vValue.size(), false);
2195 CAmount nTotal = 0;
2196 bool fReachedTarget = false;
2197 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2199 for (unsigned int i = 0; i < vValue.size(); i++)
2201 //The solver here uses a randomized algorithm,
2202 //the randomness serves no real security purpose but is just
2203 //needed to prevent degenerate behavior and it is important
2204 //that the rng is fast. We do not use a constant random sequence,
2205 //because there may be some privacy improvement by making
2206 //the selection random.
2207 if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2209 nTotal += vValue[i].txout.nValue;
2210 vfIncluded[i] = true;
2211 if (nTotal >= nTargetValue)
2213 fReachedTarget = true;
2214 if (nTotal < nBest)
2216 nBest = nTotal;
2217 vfBest = vfIncluded;
2219 nTotal -= vValue[i].txout.nValue;
2220 vfIncluded[i] = false;
2228 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2229 std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
2231 setCoinsRet.clear();
2232 nValueRet = 0;
2234 // List of values less than target
2235 boost::optional<CInputCoin> coinLowestLarger;
2236 std::vector<CInputCoin> vValue;
2237 CAmount nTotalLower = 0;
2239 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2241 BOOST_FOREACH(const COutput &output, vCoins)
2243 if (!output.fSpendable)
2244 continue;
2246 const CWalletTx *pcoin = output.tx;
2248 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2249 continue;
2251 if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2252 continue;
2254 int i = output.i;
2256 CInputCoin coin = CInputCoin(pcoin, i);
2258 if (coin.txout.nValue == nTargetValue)
2260 setCoinsRet.insert(coin);
2261 nValueRet += coin.txout.nValue;
2262 return true;
2264 else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
2266 vValue.push_back(coin);
2267 nTotalLower += coin.txout.nValue;
2269 else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
2271 coinLowestLarger = coin;
2275 if (nTotalLower == nTargetValue)
2277 for (const auto& input : vValue)
2279 setCoinsRet.insert(input);
2280 nValueRet += input.txout.nValue;
2282 return true;
2285 if (nTotalLower < nTargetValue)
2287 if (!coinLowestLarger)
2288 return false;
2289 setCoinsRet.insert(coinLowestLarger.get());
2290 nValueRet += coinLowestLarger->txout.nValue;
2291 return true;
2294 // Solve subset sum by stochastic approximation
2295 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2296 std::reverse(vValue.begin(), vValue.end());
2297 std::vector<char> vfBest;
2298 CAmount nBest;
2300 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2301 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2302 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2304 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2305 // or the next bigger coin is closer), return the bigger coin
2306 if (coinLowestLarger &&
2307 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
2309 setCoinsRet.insert(coinLowestLarger.get());
2310 nValueRet += coinLowestLarger->txout.nValue;
2312 else {
2313 for (unsigned int i = 0; i < vValue.size(); i++)
2314 if (vfBest[i])
2316 setCoinsRet.insert(vValue[i]);
2317 nValueRet += vValue[i].txout.nValue;
2320 if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2321 LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2322 for (unsigned int i = 0; i < vValue.size(); i++) {
2323 if (vfBest[i]) {
2324 LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
2327 LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2331 return true;
2334 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2336 std::vector<COutput> vCoins(vAvailableCoins);
2338 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2339 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2341 BOOST_FOREACH(const COutput& out, vCoins)
2343 if (!out.fSpendable)
2344 continue;
2345 nValueRet += out.tx->tx->vout[out.i].nValue;
2346 setCoinsRet.insert(CInputCoin(out.tx, out.i));
2348 return (nValueRet >= nTargetValue);
2351 // calculate value from preset inputs and store them
2352 std::set<CInputCoin> setPresetCoins;
2353 CAmount nValueFromPresetInputs = 0;
2355 std::vector<COutPoint> vPresetInputs;
2356 if (coinControl)
2357 coinControl->ListSelected(vPresetInputs);
2358 BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
2360 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2361 if (it != mapWallet.end())
2363 const CWalletTx* pcoin = &it->second;
2364 // Clearly invalid input, fail
2365 if (pcoin->tx->vout.size() <= outpoint.n)
2366 return false;
2367 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2368 setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
2369 } else
2370 return false; // TODO: Allow non-wallet inputs
2373 // remove preset inputs from vCoins
2374 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2376 if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
2377 it = vCoins.erase(it);
2378 else
2379 ++it;
2382 size_t nMaxChainLength = std::min(GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2383 bool fRejectLongChains = GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2385 bool res = nTargetValue <= nValueFromPresetInputs ||
2386 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2387 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2388 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2389 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2390 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2391 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2392 (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2394 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2395 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2397 // add preset inputs to the total value selected
2398 nValueRet += nValueFromPresetInputs;
2400 return res;
2403 bool CWallet::SignTransaction(CMutableTransaction &tx)
2405 AssertLockHeld(cs_wallet); // mapWallet
2407 // sign the new tx
2408 CTransaction txNewConst(tx);
2409 int nIn = 0;
2410 for (const auto& input : tx.vin) {
2411 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2412 if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2413 return false;
2415 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2416 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2417 SignatureData sigdata;
2418 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2419 return false;
2421 UpdateTransaction(tx, nIn, sigdata);
2422 nIn++;
2424 return true;
2427 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl, bool keepReserveKey)
2429 std::vector<CRecipient> vecSend;
2431 // Turn the txout set into a CRecipient vector
2432 for (size_t idx = 0; idx < tx.vout.size(); idx++)
2434 const CTxOut& txOut = tx.vout[idx];
2435 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2436 vecSend.push_back(recipient);
2439 coinControl.fAllowOtherInputs = true;
2441 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2442 coinControl.Select(txin.prevout);
2444 CReserveKey reservekey(this);
2445 CWalletTx wtx;
2446 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, &coinControl, false))
2447 return false;
2449 if (nChangePosInOut != -1)
2450 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2452 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2453 for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
2454 tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2456 // Add new txins (keeping original txin scriptSig/order)
2457 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
2459 if (!coinControl.IsSelected(txin.prevout))
2461 tx.vin.push_back(txin);
2463 if (lockUnspents)
2465 LOCK2(cs_main, cs_wallet);
2466 LockCoin(txin.prevout);
2471 // optionally keep the change output key
2472 if (keepReserveKey)
2473 reservekey.KeepKey();
2475 return true;
2478 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2479 int& nChangePosInOut, std::string& strFailReason, const CCoinControl* coinControl, bool sign)
2481 CAmount nValue = 0;
2482 int nChangePosRequest = nChangePosInOut;
2483 unsigned int nSubtractFeeFromAmount = 0;
2484 for (const auto& recipient : vecSend)
2486 if (nValue < 0 || recipient.nAmount < 0)
2488 strFailReason = _("Transaction amounts must not be negative");
2489 return false;
2491 nValue += recipient.nAmount;
2493 if (recipient.fSubtractFeeFromAmount)
2494 nSubtractFeeFromAmount++;
2496 if (vecSend.empty())
2498 strFailReason = _("Transaction must have at least one recipient");
2499 return false;
2502 wtxNew.fTimeReceivedIsTxTime = true;
2503 wtxNew.BindWallet(this);
2504 CMutableTransaction txNew;
2506 // Discourage fee sniping.
2508 // For a large miner the value of the transactions in the best block and
2509 // the mempool can exceed the cost of deliberately attempting to mine two
2510 // blocks to orphan the current best block. By setting nLockTime such that
2511 // only the next block can include the transaction, we discourage this
2512 // practice as the height restricted and limited blocksize gives miners
2513 // considering fee sniping fewer options for pulling off this attack.
2515 // A simple way to think about this is from the wallet's point of view we
2516 // always want the blockchain to move forward. By setting nLockTime this
2517 // way we're basically making the statement that we only want this
2518 // transaction to appear in the next block; we don't want to potentially
2519 // encourage reorgs by allowing transactions to appear at lower heights
2520 // than the next block in forks of the best chain.
2522 // Of course, the subsidy is high enough, and transaction volume low
2523 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2524 // now we ensure code won't be written that makes assumptions about
2525 // nLockTime that preclude a fix later.
2526 txNew.nLockTime = chainActive.Height();
2528 // Secondly occasionally randomly pick a nLockTime even further back, so
2529 // that transactions that are delayed after signing for whatever reason,
2530 // e.g. high-latency mix networks and some CoinJoin implementations, have
2531 // better privacy.
2532 if (GetRandInt(10) == 0)
2533 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2535 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2536 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2539 std::set<CInputCoin> setCoins;
2540 LOCK2(cs_main, cs_wallet);
2542 std::vector<COutput> vAvailableCoins;
2543 AvailableCoins(vAvailableCoins, true, coinControl);
2545 nFeeRet = 0;
2546 // Start with no fee and loop until there is enough fee
2547 while (true)
2549 nChangePosInOut = nChangePosRequest;
2550 txNew.vin.clear();
2551 txNew.vout.clear();
2552 wtxNew.fFromMe = true;
2553 bool fFirst = true;
2555 CAmount nValueToSelect = nValue;
2556 if (nSubtractFeeFromAmount == 0)
2557 nValueToSelect += nFeeRet;
2558 // vouts to the payees
2559 for (const auto& recipient : vecSend)
2561 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2563 if (recipient.fSubtractFeeFromAmount)
2565 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2567 if (fFirst) // first receiver pays the remainder not divisible by output count
2569 fFirst = false;
2570 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2574 if (IsDust(txout, ::dustRelayFee))
2576 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2578 if (txout.nValue < 0)
2579 strFailReason = _("The transaction amount is too small to pay the fee");
2580 else
2581 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2583 else
2584 strFailReason = _("Transaction amount too small");
2585 return false;
2587 txNew.vout.push_back(txout);
2590 // Choose coins to use
2591 CAmount nValueIn = 0;
2592 setCoins.clear();
2593 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, coinControl))
2595 strFailReason = _("Insufficient funds");
2596 return false;
2599 const CAmount nChange = nValueIn - nValueToSelect;
2600 if (nChange > 0)
2602 // Fill a vout to ourself
2603 // TODO: pass in scriptChange instead of reservekey so
2604 // change transaction isn't always pay-to-bitcoin-address
2605 CScript scriptChange;
2607 // coin control: send change to custom address
2608 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
2609 scriptChange = GetScriptForDestination(coinControl->destChange);
2611 // no coin control: send change to newly generated address
2612 else
2614 // Note: We use a new key here to keep it from being obvious which side is the change.
2615 // The drawback is that by not reusing a previous key, the change may be lost if a
2616 // backup is restored, if the backup doesn't have the new private key for the change.
2617 // If we reused the old key, it would be possible to add code to look for and
2618 // rediscover unknown transactions that were written with keys of ours to recover
2619 // post-backup change.
2621 // Reserve a new key pair from key pool
2622 CPubKey vchPubKey;
2623 bool ret;
2624 ret = reservekey.GetReservedKey(vchPubKey, true);
2625 if (!ret)
2627 strFailReason = _("Keypool ran out, please call keypoolrefill first");
2628 return false;
2631 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2634 CTxOut newTxOut(nChange, scriptChange);
2636 // We do not move dust-change to fees, because the sender would end up paying more than requested.
2637 // This would be against the purpose of the all-inclusive feature.
2638 // So instead we raise the change and deduct from the recipient.
2639 if (nSubtractFeeFromAmount > 0 && IsDust(newTxOut, ::dustRelayFee))
2641 CAmount nDust = GetDustThreshold(newTxOut, ::dustRelayFee) - newTxOut.nValue;
2642 newTxOut.nValue += nDust; // raise change until no more dust
2643 for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
2645 if (vecSend[i].fSubtractFeeFromAmount)
2647 txNew.vout[i].nValue -= nDust;
2648 if (IsDust(txNew.vout[i], ::dustRelayFee))
2650 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2651 return false;
2653 break;
2658 // Never create dust outputs; if we would, just
2659 // add the dust to the fee.
2660 if (IsDust(newTxOut, ::dustRelayFee))
2662 nChangePosInOut = -1;
2663 nFeeRet += nChange;
2664 reservekey.ReturnKey();
2666 else
2668 if (nChangePosInOut == -1)
2670 // Insert change txn at random position:
2671 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2673 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2675 strFailReason = _("Change index out of range");
2676 return false;
2679 std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2680 txNew.vout.insert(position, newTxOut);
2682 } else {
2683 reservekey.ReturnKey();
2684 nChangePosInOut = -1;
2687 // Fill vin
2689 // Note how the sequence number is set to non-maxint so that
2690 // the nLockTime set above actually works.
2692 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2693 // we use the highest possible value in that range (maxint-2)
2694 // to avoid conflicting with other possible uses of nSequence,
2695 // and in the spirit of "smallest possible change from prior
2696 // behavior."
2697 bool rbf = coinControl ? coinControl->signalRbf : fWalletRbf;
2698 const uint32_t nSequence = rbf ? MAX_BIP125_RBF_SEQUENCE : (std::numeric_limits<unsigned int>::max() - 1);
2699 for (const auto& coin : setCoins)
2700 txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
2701 nSequence));
2703 // Fill in dummy signatures for fee calculation.
2704 if (!DummySignTx(txNew, setCoins)) {
2705 strFailReason = _("Signing transaction failed");
2706 return false;
2709 unsigned int nBytes = GetVirtualTransactionSize(txNew);
2711 CTransaction txNewConst(txNew);
2713 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2714 for (auto& vin : txNew.vin) {
2715 vin.scriptSig = CScript();
2716 vin.scriptWitness.SetNull();
2719 // Allow to override the default confirmation target over the CoinControl instance
2720 int currentConfirmationTarget = nTxConfirmTarget;
2721 if (coinControl && coinControl->nConfirmTarget > 0)
2722 currentConfirmationTarget = coinControl->nConfirmTarget;
2724 CAmount nFeeNeeded = GetMinimumFee(nBytes, currentConfirmationTarget, ::mempool, ::feeEstimator);
2725 if (coinControl && coinControl->fOverrideFeeRate)
2726 nFeeNeeded = coinControl->nFeeRate.GetFee(nBytes);
2728 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2729 // because we must be at the maximum allowed fee.
2730 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2732 strFailReason = _("Transaction too large for fee policy");
2733 return false;
2736 if (nFeeRet >= nFeeNeeded) {
2737 // Reduce fee to only the needed amount if we have change
2738 // output to increase. This prevents potential overpayment
2739 // in fees if the coins selected to meet nFeeNeeded result
2740 // in a transaction that requires less fee than the prior
2741 // iteration.
2742 // TODO: The case where nSubtractFeeFromAmount > 0 remains
2743 // to be addressed because it requires returning the fee to
2744 // the payees and not the change output.
2745 // TODO: The case where there is no change output remains
2746 // to be addressed so we avoid creating too small an output.
2747 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2748 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2749 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2750 change_position->nValue += extraFeePaid;
2751 nFeeRet -= extraFeePaid;
2753 break; // Done, enough fee included.
2756 // Try to reduce change to include necessary fee
2757 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2758 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2759 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2760 // Only reduce change if remaining amount is still a large enough output.
2761 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2762 change_position->nValue -= additionalFeeNeeded;
2763 nFeeRet += additionalFeeNeeded;
2764 break; // Done, able to increase fee from change
2768 // Include more fee and try again.
2769 nFeeRet = nFeeNeeded;
2770 continue;
2774 if (sign)
2776 CTransaction txNewConst(txNew);
2777 int nIn = 0;
2778 for (const auto& coin : setCoins)
2780 const CScript& scriptPubKey = coin.txout.scriptPubKey;
2781 SignatureData sigdata;
2783 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2785 strFailReason = _("Signing transaction failed");
2786 return false;
2787 } else {
2788 UpdateTransaction(txNew, nIn, sigdata);
2791 nIn++;
2795 // Embed the constructed transaction data in wtxNew.
2796 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2798 // Limit size
2799 if (GetTransactionWeight(wtxNew) >= MAX_STANDARD_TX_WEIGHT)
2801 strFailReason = _("Transaction too large");
2802 return false;
2806 if (GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2807 // Lastly, ensure this tx will pass the mempool's chain limits
2808 LockPoints lp;
2809 CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
2810 CTxMemPool::setEntries setAncestors;
2811 size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2812 size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2813 size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2814 size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2815 std::string errString;
2816 if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2817 strFailReason = _("Transaction has too long of a mempool chain");
2818 return false;
2821 return true;
2825 * Call after CreateTransaction unless you want to abort
2827 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
2830 LOCK2(cs_main, cs_wallet);
2831 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
2833 // Take key pair from key pool so it won't be used again
2834 reservekey.KeepKey();
2836 // Add tx to wallet, because if it has change it's also ours,
2837 // otherwise just for transaction history.
2838 AddToWallet(wtxNew);
2840 // Notify that old coins are spent
2841 BOOST_FOREACH(const CTxIn& txin, wtxNew.tx->vin)
2843 CWalletTx &coin = mapWallet[txin.prevout.hash];
2844 coin.BindWallet(this);
2845 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2849 // Track how many getdata requests our transaction gets
2850 mapRequestCount[wtxNew.GetHash()] = 0;
2852 if (fBroadcastTransactions)
2854 // Broadcast
2855 if (!wtxNew.AcceptToMemoryPool(maxTxFee, state)) {
2856 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
2857 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2858 } else {
2859 wtxNew.RelayWalletTransaction(connman);
2863 return true;
2866 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
2867 CWalletDB walletdb(*dbw);
2868 return walletdb.ListAccountCreditDebit(strAccount, entries);
2871 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
2873 CWalletDB walletdb(*dbw);
2875 return AddAccountingEntry(acentry, &walletdb);
2878 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
2880 if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
2881 return false;
2884 laccentries.push_back(acentry);
2885 CAccountingEntry & entry = laccentries.back();
2886 wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
2888 return true;
2891 CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
2893 return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
2896 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, bool ignoreGlobalPayTxFee)
2898 // payTxFee is the user-set global for desired feerate
2899 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
2900 // User didn't set: use -txconfirmtarget to estimate...
2901 if (nFeeNeeded == 0 || ignoreGlobalPayTxFee) {
2902 int estimateFoundTarget = nConfirmTarget;
2903 nFeeNeeded = estimator.estimateSmartFee(nConfirmTarget, &estimateFoundTarget, pool).GetFee(nTxBytes);
2904 // ... unless we don't have enough mempool data for estimatefee, then use fallbackFee
2905 if (nFeeNeeded == 0)
2906 nFeeNeeded = fallbackFee.GetFee(nTxBytes);
2908 // prevent user from paying a fee below minRelayTxFee or minTxFee
2909 nFeeNeeded = std::max(nFeeNeeded, GetRequiredFee(nTxBytes));
2910 // But always obey the maximum
2911 if (nFeeNeeded > maxTxFee)
2912 nFeeNeeded = maxTxFee;
2913 return nFeeNeeded;
2919 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2921 fFirstRunRet = false;
2922 DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
2923 if (nLoadWalletRet == DB_NEED_REWRITE)
2925 if (dbw->Rewrite("\x04pool"))
2927 LOCK(cs_wallet);
2928 setKeyPool.clear();
2929 // Note: can't top-up keypool here, because wallet is locked.
2930 // User will be prompted to unlock wallet the next operation
2931 // that requires a new key.
2935 if (nLoadWalletRet != DB_LOAD_OK)
2936 return nLoadWalletRet;
2937 fFirstRunRet = !vchDefaultKey.IsValid();
2939 uiInterface.LoadWallet(this);
2941 return DB_LOAD_OK;
2944 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
2946 AssertLockHeld(cs_wallet); // mapWallet
2947 vchDefaultKey = CPubKey();
2948 DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
2949 for (uint256 hash : vHashOut)
2950 mapWallet.erase(hash);
2952 if (nZapSelectTxRet == DB_NEED_REWRITE)
2954 if (dbw->Rewrite("\x04pool"))
2956 setKeyPool.clear();
2957 // Note: can't top-up keypool here, because wallet is locked.
2958 // User will be prompted to unlock wallet the next operation
2959 // that requires a new key.
2963 if (nZapSelectTxRet != DB_LOAD_OK)
2964 return nZapSelectTxRet;
2966 MarkDirty();
2968 return DB_LOAD_OK;
2972 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
2974 vchDefaultKey = CPubKey();
2975 DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
2976 if (nZapWalletTxRet == DB_NEED_REWRITE)
2978 if (dbw->Rewrite("\x04pool"))
2980 LOCK(cs_wallet);
2981 setKeyPool.clear();
2982 // Note: can't top-up keypool here, because wallet is locked.
2983 // User will be prompted to unlock wallet the next operation
2984 // that requires a new key.
2988 if (nZapWalletTxRet != DB_LOAD_OK)
2989 return nZapWalletTxRet;
2991 return DB_LOAD_OK;
2995 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
2997 bool fUpdated = false;
2999 LOCK(cs_wallet); // mapAddressBook
3000 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
3001 fUpdated = mi != mapAddressBook.end();
3002 mapAddressBook[address].name = strName;
3003 if (!strPurpose.empty()) /* update purpose only if requested */
3004 mapAddressBook[address].purpose = strPurpose;
3006 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3007 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3008 if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
3009 return false;
3010 return CWalletDB(*dbw).WriteName(CBitcoinAddress(address).ToString(), strName);
3013 bool CWallet::DelAddressBook(const CTxDestination& address)
3016 LOCK(cs_wallet); // mapAddressBook
3018 // Delete destdata tuples associated with address
3019 std::string strAddress = CBitcoinAddress(address).ToString();
3020 BOOST_FOREACH(const PAIRTYPE(std::string, std::string) &item, mapAddressBook[address].destdata)
3022 CWalletDB(*dbw).EraseDestData(strAddress, item.first);
3024 mapAddressBook.erase(address);
3027 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3029 CWalletDB(*dbw).ErasePurpose(CBitcoinAddress(address).ToString());
3030 return CWalletDB(*dbw).EraseName(CBitcoinAddress(address).ToString());
3033 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
3035 CTxDestination address;
3036 if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
3037 auto mi = mapAddressBook.find(address);
3038 if (mi != mapAddressBook.end()) {
3039 return mi->second.name;
3042 // A scriptPubKey that doesn't have an entry in the address book is
3043 // associated with the default account ("").
3044 const static std::string DEFAULT_ACCOUNT_NAME;
3045 return DEFAULT_ACCOUNT_NAME;
3048 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
3050 if (!CWalletDB(*dbw).WriteDefaultKey(vchPubKey))
3051 return false;
3052 vchDefaultKey = vchPubKey;
3053 return true;
3057 * Mark old keypool keys as used,
3058 * and generate all new keys
3060 bool CWallet::NewKeyPool()
3063 LOCK(cs_wallet);
3064 CWalletDB walletdb(*dbw);
3065 BOOST_FOREACH(int64_t nIndex, setKeyPool)
3066 walletdb.ErasePool(nIndex);
3067 setKeyPool.clear();
3069 if (!TopUpKeyPool()) {
3070 return false;
3072 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3074 return true;
3077 size_t CWallet::KeypoolCountExternalKeys()
3079 AssertLockHeld(cs_wallet); // setKeyPool
3081 // immediately return setKeyPool's size if HD or HD_SPLIT is disabled or not supported
3082 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3083 return setKeyPool.size();
3085 CWalletDB walletdb(*dbw);
3087 // count amount of external keys
3088 size_t amountE = 0;
3089 for(const int64_t& id : setKeyPool)
3091 CKeyPool tmpKeypool;
3092 if (!walletdb.ReadPool(id, tmpKeypool))
3093 throw std::runtime_error(std::string(__func__) + ": read failed");
3094 amountE += !tmpKeypool.fInternal;
3097 return amountE;
3100 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3103 LOCK(cs_wallet);
3105 if (IsLocked())
3106 return false;
3108 // Top up key pool
3109 unsigned int nTargetSize;
3110 if (kpSize > 0)
3111 nTargetSize = kpSize;
3112 else
3113 nTargetSize = std::max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3115 // count amount of available keys (internal, external)
3116 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3117 int64_t amountExternal = KeypoolCountExternalKeys();
3118 int64_t amountInternal = setKeyPool.size() - amountExternal;
3119 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - amountExternal, (int64_t) 0);
3120 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - amountInternal, (int64_t) 0);
3122 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3124 // don't create extra internal keys
3125 missingInternal = 0;
3127 bool internal = false;
3128 CWalletDB walletdb(*dbw);
3129 for (int64_t i = missingInternal + missingExternal; i--;)
3131 int64_t nEnd = 1;
3132 if (i < missingInternal)
3133 internal = true;
3134 if (!setKeyPool.empty())
3135 nEnd = *(--setKeyPool.end()) + 1;
3136 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey(internal), internal)))
3137 throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3138 setKeyPool.insert(nEnd);
3139 LogPrintf("keypool added key %d, size=%u, internal=%d\n", nEnd, setKeyPool.size(), internal);
3142 return true;
3145 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool internal)
3147 nIndex = -1;
3148 keypool.vchPubKey = CPubKey();
3150 LOCK(cs_wallet);
3152 if (!IsLocked())
3153 TopUpKeyPool();
3155 // Get the oldest key
3156 if(setKeyPool.empty())
3157 return;
3159 CWalletDB walletdb(*dbw);
3161 // try to find a key that matches the internal/external filter
3162 for(const int64_t& id : setKeyPool)
3164 CKeyPool tmpKeypool;
3165 if (!walletdb.ReadPool(id, tmpKeypool))
3166 throw std::runtime_error(std::string(__func__) + ": read failed");
3167 if (!HaveKey(tmpKeypool.vchPubKey.GetID()))
3168 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3169 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT) || tmpKeypool.fInternal == internal)
3171 nIndex = id;
3172 keypool = tmpKeypool;
3173 setKeyPool.erase(id);
3174 assert(keypool.vchPubKey.IsValid());
3175 LogPrintf("keypool reserve %d\n", nIndex);
3176 return;
3182 void CWallet::KeepKey(int64_t nIndex)
3184 // Remove from key pool
3185 CWalletDB walletdb(*dbw);
3186 walletdb.ErasePool(nIndex);
3187 LogPrintf("keypool keep %d\n", nIndex);
3190 void CWallet::ReturnKey(int64_t nIndex)
3192 // Return to key pool
3194 LOCK(cs_wallet);
3195 setKeyPool.insert(nIndex);
3197 LogPrintf("keypool return %d\n", nIndex);
3200 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3202 CKeyPool keypool;
3204 LOCK(cs_wallet);
3205 int64_t nIndex = 0;
3206 ReserveKeyFromKeyPool(nIndex, keypool, internal);
3207 if (nIndex == -1)
3209 if (IsLocked()) return false;
3210 result = GenerateNewKey(internal);
3211 return true;
3213 KeepKey(nIndex);
3214 result = keypool.vchPubKey;
3216 return true;
3219 int64_t CWallet::GetOldestKeyPoolTime()
3221 LOCK(cs_wallet);
3223 // if the keypool is empty, return <NOW>
3224 if (setKeyPool.empty())
3225 return GetTime();
3227 CKeyPool keypool;
3228 CWalletDB walletdb(*dbw);
3230 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT))
3232 // if HD & HD Chain Split is enabled, response max(oldest-internal-key, oldest-external-key)
3233 int64_t now = GetTime();
3234 int64_t oldest_external = now, oldest_internal = now;
3236 for(const int64_t& id : setKeyPool)
3238 if (!walletdb.ReadPool(id, keypool)) {
3239 throw std::runtime_error(std::string(__func__) + ": read failed");
3241 if (keypool.fInternal && keypool.nTime < oldest_internal) {
3242 oldest_internal = keypool.nTime;
3244 else if (!keypool.fInternal && keypool.nTime < oldest_external) {
3245 oldest_external = keypool.nTime;
3247 if (oldest_internal != now && oldest_external != now) {
3248 break;
3251 return std::max(oldest_internal, oldest_external);
3253 // load oldest key from keypool, get time and return
3254 int64_t nIndex = *(setKeyPool.begin());
3255 if (!walletdb.ReadPool(nIndex, keypool))
3256 throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3257 assert(keypool.vchPubKey.IsValid());
3258 return keypool.nTime;
3261 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3263 std::map<CTxDestination, CAmount> balances;
3266 LOCK(cs_wallet);
3267 for (const auto& walletEntry : mapWallet)
3269 const CWalletTx *pcoin = &walletEntry.second;
3271 if (!pcoin->IsTrusted())
3272 continue;
3274 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3275 continue;
3277 int nDepth = pcoin->GetDepthInMainChain();
3278 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3279 continue;
3281 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3283 CTxDestination addr;
3284 if (!IsMine(pcoin->tx->vout[i]))
3285 continue;
3286 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3287 continue;
3289 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3291 if (!balances.count(addr))
3292 balances[addr] = 0;
3293 balances[addr] += n;
3298 return balances;
3301 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3303 AssertLockHeld(cs_wallet); // mapWallet
3304 std::set< std::set<CTxDestination> > groupings;
3305 std::set<CTxDestination> grouping;
3307 for (const auto& walletEntry : mapWallet)
3309 const CWalletTx *pcoin = &walletEntry.second;
3311 if (pcoin->tx->vin.size() > 0)
3313 bool any_mine = false;
3314 // group all input addresses with each other
3315 BOOST_FOREACH(CTxIn txin, pcoin->tx->vin)
3317 CTxDestination address;
3318 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3319 continue;
3320 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3321 continue;
3322 grouping.insert(address);
3323 any_mine = true;
3326 // group change with input addresses
3327 if (any_mine)
3329 BOOST_FOREACH(CTxOut txout, pcoin->tx->vout)
3330 if (IsChange(txout))
3332 CTxDestination txoutAddr;
3333 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3334 continue;
3335 grouping.insert(txoutAddr);
3338 if (grouping.size() > 0)
3340 groupings.insert(grouping);
3341 grouping.clear();
3345 // group lone addrs by themselves
3346 for (const auto& txout : pcoin->tx->vout)
3347 if (IsMine(txout))
3349 CTxDestination address;
3350 if(!ExtractDestination(txout.scriptPubKey, address))
3351 continue;
3352 grouping.insert(address);
3353 groupings.insert(grouping);
3354 grouping.clear();
3358 std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3359 std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3360 BOOST_FOREACH(std::set<CTxDestination> _grouping, groupings)
3362 // make a set of all the groups hit by this new group
3363 std::set< std::set<CTxDestination>* > hits;
3364 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3365 BOOST_FOREACH(CTxDestination address, _grouping)
3366 if ((it = setmap.find(address)) != setmap.end())
3367 hits.insert((*it).second);
3369 // merge all hit groups into a new single group and delete old groups
3370 std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3371 BOOST_FOREACH(std::set<CTxDestination>* hit, hits)
3373 merged->insert(hit->begin(), hit->end());
3374 uniqueGroupings.erase(hit);
3375 delete hit;
3377 uniqueGroupings.insert(merged);
3379 // update setmap
3380 BOOST_FOREACH(CTxDestination element, *merged)
3381 setmap[element] = merged;
3384 std::set< std::set<CTxDestination> > ret;
3385 BOOST_FOREACH(std::set<CTxDestination>* uniqueGrouping, uniqueGroupings)
3387 ret.insert(*uniqueGrouping);
3388 delete uniqueGrouping;
3391 return ret;
3394 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3396 LOCK(cs_wallet);
3397 std::set<CTxDestination> result;
3398 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
3400 const CTxDestination& address = item.first;
3401 const std::string& strName = item.second.name;
3402 if (strName == strAccount)
3403 result.insert(address);
3405 return result;
3408 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3410 if (nIndex == -1)
3412 CKeyPool keypool;
3413 pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3414 if (nIndex != -1)
3415 vchPubKey = keypool.vchPubKey;
3416 else {
3417 return false;
3420 assert(vchPubKey.IsValid());
3421 pubkey = vchPubKey;
3422 return true;
3425 void CReserveKey::KeepKey()
3427 if (nIndex != -1)
3428 pwallet->KeepKey(nIndex);
3429 nIndex = -1;
3430 vchPubKey = CPubKey();
3433 void CReserveKey::ReturnKey()
3435 if (nIndex != -1)
3436 pwallet->ReturnKey(nIndex);
3437 nIndex = -1;
3438 vchPubKey = CPubKey();
3441 void CWallet::GetAllReserveKeys(std::set<CKeyID>& setAddress) const
3443 setAddress.clear();
3445 CWalletDB walletdb(*dbw);
3447 LOCK2(cs_main, cs_wallet);
3448 BOOST_FOREACH(const int64_t& id, setKeyPool)
3450 CKeyPool keypool;
3451 if (!walletdb.ReadPool(id, keypool))
3452 throw std::runtime_error(std::string(__func__) + ": read failed");
3453 assert(keypool.vchPubKey.IsValid());
3454 CKeyID keyID = keypool.vchPubKey.GetID();
3455 if (!HaveKey(keyID))
3456 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3457 setAddress.insert(keyID);
3461 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
3463 std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
3464 CPubKey pubkey;
3465 if (!rKey->GetReservedKey(pubkey))
3466 return;
3468 script = rKey;
3469 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3472 void CWallet::LockCoin(const COutPoint& output)
3474 AssertLockHeld(cs_wallet); // setLockedCoins
3475 setLockedCoins.insert(output);
3478 void CWallet::UnlockCoin(const COutPoint& output)
3480 AssertLockHeld(cs_wallet); // setLockedCoins
3481 setLockedCoins.erase(output);
3484 void CWallet::UnlockAllCoins()
3486 AssertLockHeld(cs_wallet); // setLockedCoins
3487 setLockedCoins.clear();
3490 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3492 AssertLockHeld(cs_wallet); // setLockedCoins
3493 COutPoint outpt(hash, n);
3495 return (setLockedCoins.count(outpt) > 0);
3498 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3500 AssertLockHeld(cs_wallet); // setLockedCoins
3501 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3502 it != setLockedCoins.end(); it++) {
3503 COutPoint outpt = (*it);
3504 vOutpts.push_back(outpt);
3508 /** @} */ // end of Actions
3510 class CAffectedKeysVisitor : public boost::static_visitor<void> {
3511 private:
3512 const CKeyStore &keystore;
3513 std::vector<CKeyID> &vKeys;
3515 public:
3516 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
3518 void Process(const CScript &script) {
3519 txnouttype type;
3520 std::vector<CTxDestination> vDest;
3521 int nRequired;
3522 if (ExtractDestinations(script, type, vDest, nRequired)) {
3523 BOOST_FOREACH(const CTxDestination &dest, vDest)
3524 boost::apply_visitor(*this, dest);
3528 void operator()(const CKeyID &keyId) {
3529 if (keystore.HaveKey(keyId))
3530 vKeys.push_back(keyId);
3533 void operator()(const CScriptID &scriptId) {
3534 CScript script;
3535 if (keystore.GetCScript(scriptId, script))
3536 Process(script);
3539 void operator()(const CNoDestination &none) {}
3542 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3543 AssertLockHeld(cs_wallet); // mapKeyMetadata
3544 mapKeyBirth.clear();
3546 // get birth times for keys with metadata
3547 for (const auto& entry : mapKeyMetadata) {
3548 if (entry.second.nCreateTime) {
3549 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3553 // map in which we'll infer heights of other keys
3554 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3555 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3556 std::set<CKeyID> setKeys;
3557 GetKeys(setKeys);
3558 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
3559 if (mapKeyBirth.count(keyid) == 0)
3560 mapKeyFirstBlock[keyid] = pindexMax;
3562 setKeys.clear();
3564 // if there are no such keys, we're done
3565 if (mapKeyFirstBlock.empty())
3566 return;
3568 // find first block that affects those keys, if there are any left
3569 std::vector<CKeyID> vAffected;
3570 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3571 // iterate over all wallet transactions...
3572 const CWalletTx &wtx = (*it).second;
3573 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3574 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3575 // ... which are already in a block
3576 int nHeight = blit->second->nHeight;
3577 BOOST_FOREACH(const CTxOut &txout, wtx.tx->vout) {
3578 // iterate over all their outputs
3579 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3580 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
3581 // ... and all their affected keys
3582 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3583 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3584 rit->second = blit->second;
3586 vAffected.clear();
3591 // Extract block timestamps for those keys
3592 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3593 mapKeyBirth[it->first] = it->second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3597 * Compute smart timestamp for a transaction being added to the wallet.
3599 * Logic:
3600 * - If sending a transaction, assign its timestamp to the current time.
3601 * - If receiving a transaction outside a block, assign its timestamp to the
3602 * current time.
3603 * - If receiving a block with a future timestamp, assign all its (not already
3604 * known) transactions' timestamps to the current time.
3605 * - If receiving a block with a past timestamp, before the most recent known
3606 * transaction (that we care about), assign all its (not already known)
3607 * transactions' timestamps to the same timestamp as that most-recent-known
3608 * transaction.
3609 * - If receiving a block with a past timestamp, but after the most recent known
3610 * transaction, assign all its (not already known) transactions' timestamps to
3611 * the block time.
3613 * For more information see CWalletTx::nTimeSmart,
3614 * https://bitcointalk.org/?topic=54527, or
3615 * https://github.com/bitcoin/bitcoin/pull/1393.
3617 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3619 unsigned int nTimeSmart = wtx.nTimeReceived;
3620 if (!wtx.hashUnset()) {
3621 if (mapBlockIndex.count(wtx.hashBlock)) {
3622 int64_t latestNow = wtx.nTimeReceived;
3623 int64_t latestEntry = 0;
3625 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3626 int64_t latestTolerated = latestNow + 300;
3627 const TxItems& txOrdered = wtxOrdered;
3628 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3629 CWalletTx* const pwtx = it->second.first;
3630 if (pwtx == &wtx) {
3631 continue;
3633 CAccountingEntry* const pacentry = it->second.second;
3634 int64_t nSmartTime;
3635 if (pwtx) {
3636 nSmartTime = pwtx->nTimeSmart;
3637 if (!nSmartTime) {
3638 nSmartTime = pwtx->nTimeReceived;
3640 } else {
3641 nSmartTime = pacentry->nTime;
3643 if (nSmartTime <= latestTolerated) {
3644 latestEntry = nSmartTime;
3645 if (nSmartTime > latestNow) {
3646 latestNow = nSmartTime;
3648 break;
3652 int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3653 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3654 } else {
3655 LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3658 return nTimeSmart;
3661 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3663 if (boost::get<CNoDestination>(&dest))
3664 return false;
3666 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3667 return CWalletDB(*dbw).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
3670 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3672 if (!mapAddressBook[dest].destdata.erase(key))
3673 return false;
3674 return CWalletDB(*dbw).EraseDestData(CBitcoinAddress(dest).ToString(), key);
3677 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3679 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3680 return true;
3683 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3685 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3686 if(i != mapAddressBook.end())
3688 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3689 if(j != i->second.destdata.end())
3691 if(value)
3692 *value = j->second;
3693 return true;
3696 return false;
3699 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3701 LOCK(cs_wallet);
3702 std::vector<std::string> values;
3703 for (const auto& address : mapAddressBook) {
3704 for (const auto& data : address.second.destdata) {
3705 if (!data.first.compare(0, prefix.size(), prefix)) {
3706 values.emplace_back(data.second);
3710 return values;
3713 std::string CWallet::GetWalletHelpString(bool showDebug)
3715 std::string strUsage = HelpMessageGroup(_("Wallet options:"));
3716 strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
3717 strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE));
3718 strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
3719 CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)));
3720 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
3721 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)));
3722 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
3723 CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
3724 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
3725 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup"));
3726 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE));
3727 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));
3728 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));
3729 strUsage += HelpMessageOpt("-walletrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (default: %u)"), DEFAULT_WALLET_RBF));
3730 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
3731 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT));
3732 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST));
3733 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
3734 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
3735 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
3737 if (showDebug)
3739 strUsage += HelpMessageGroup(_("Wallet debugging/testing options:"));
3741 strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE));
3742 strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET));
3743 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB));
3744 strUsage += HelpMessageOpt("-walletrejectlongchains", strprintf(_("Wallet will not create transactions that violate mempool chain limits (default: %u)"), DEFAULT_WALLET_REJECT_LONG_CHAINS));
3747 return strUsage;
3750 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
3752 // needed to restore wallet transaction meta data after -zapwallettxes
3753 std::vector<CWalletTx> vWtx;
3755 if (GetBoolArg("-zapwallettxes", false)) {
3756 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3758 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3759 CWallet *tempWallet = new CWallet(std::move(dbw));
3760 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3761 if (nZapWalletRet != DB_LOAD_OK) {
3762 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3763 return NULL;
3766 delete tempWallet;
3767 tempWallet = NULL;
3770 uiInterface.InitMessage(_("Loading wallet..."));
3772 int64_t nStart = GetTimeMillis();
3773 bool fFirstRun = true;
3774 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3775 CWallet *walletInstance = new CWallet(std::move(dbw));
3776 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3777 if (nLoadWalletRet != DB_LOAD_OK)
3779 if (nLoadWalletRet == DB_CORRUPT) {
3780 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3781 return NULL;
3783 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3785 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3786 " or address book entries might be missing or incorrect."),
3787 walletFile));
3789 else if (nLoadWalletRet == DB_TOO_NEW) {
3790 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
3791 return NULL;
3793 else if (nLoadWalletRet == DB_NEED_REWRITE)
3795 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3796 return NULL;
3798 else {
3799 InitError(strprintf(_("Error loading %s"), walletFile));
3800 return NULL;
3804 if (GetBoolArg("-upgradewallet", fFirstRun))
3806 int nMaxVersion = GetArg("-upgradewallet", 0);
3807 if (nMaxVersion == 0) // the -upgradewallet without argument case
3809 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3810 nMaxVersion = CLIENT_VERSION;
3811 walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3813 else
3814 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3815 if (nMaxVersion < walletInstance->GetVersion())
3817 InitError(_("Cannot downgrade wallet"));
3818 return NULL;
3820 walletInstance->SetMaxVersion(nMaxVersion);
3823 if (fFirstRun)
3825 // Create new keyUser and set as default key
3826 if (GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && !walletInstance->IsHDEnabled()) {
3828 // ensure this wallet.dat can only be opened by clients supporting HD with chain split
3829 walletInstance->SetMinVersion(FEATURE_HD_SPLIT);
3831 // generate a new master key
3832 CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
3833 if (!walletInstance->SetHDMasterKey(masterPubKey))
3834 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
3836 CPubKey newDefaultKey;
3837 if (walletInstance->GetKeyFromPool(newDefaultKey, false)) {
3838 walletInstance->SetDefaultKey(newDefaultKey);
3839 if (!walletInstance->SetAddressBook(walletInstance->vchDefaultKey.GetID(), "", "receive")) {
3840 InitError(_("Cannot write default address") += "\n");
3841 return NULL;
3845 walletInstance->SetBestChain(chainActive.GetLocator());
3847 else if (IsArgSet("-usehd")) {
3848 bool useHD = GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
3849 if (walletInstance->IsHDEnabled() && !useHD) {
3850 InitError(strprintf(_("Error loading %s: You can't disable HD on a already existing HD wallet"), walletFile));
3851 return NULL;
3853 if (!walletInstance->IsHDEnabled() && useHD) {
3854 InitError(strprintf(_("Error loading %s: You can't enable HD on a already existing non-HD wallet"), walletFile));
3855 return NULL;
3859 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
3861 RegisterValidationInterface(walletInstance);
3863 CBlockIndex *pindexRescan = chainActive.Genesis();
3864 if (!GetBoolArg("-rescan", false))
3866 CWalletDB walletdb(*walletInstance->dbw);
3867 CBlockLocator locator;
3868 if (walletdb.ReadBestBlock(locator))
3869 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
3871 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
3873 //We can't rescan beyond non-pruned blocks, stop and throw an error
3874 //this might happen if a user uses a old wallet within a pruned node
3875 // or if he ran -disablewallet for a longer time, then decided to re-enable
3876 if (fPruneMode)
3878 CBlockIndex *block = chainActive.Tip();
3879 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
3880 block = block->pprev;
3882 if (pindexRescan != block) {
3883 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3884 return NULL;
3888 uiInterface.InitMessage(_("Rescanning..."));
3889 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
3890 nStart = GetTimeMillis();
3891 walletInstance->ScanForWalletTransactions(pindexRescan, true);
3892 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
3893 walletInstance->SetBestChain(chainActive.GetLocator());
3894 walletInstance->dbw->IncrementUpdateCounter();
3896 // Restore wallet transaction metadata after -zapwallettxes=1
3897 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
3899 CWalletDB walletdb(*walletInstance->dbw);
3901 BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
3903 uint256 hash = wtxOld.GetHash();
3904 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
3905 if (mi != walletInstance->mapWallet.end())
3907 const CWalletTx* copyFrom = &wtxOld;
3908 CWalletTx* copyTo = &mi->second;
3909 copyTo->mapValue = copyFrom->mapValue;
3910 copyTo->vOrderForm = copyFrom->vOrderForm;
3911 copyTo->nTimeReceived = copyFrom->nTimeReceived;
3912 copyTo->nTimeSmart = copyFrom->nTimeSmart;
3913 copyTo->fFromMe = copyFrom->fFromMe;
3914 copyTo->strFromAccount = copyFrom->strFromAccount;
3915 copyTo->nOrderPos = copyFrom->nOrderPos;
3916 walletdb.WriteTx(*copyTo);
3921 walletInstance->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
3924 LOCK(walletInstance->cs_wallet);
3925 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
3926 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
3927 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
3930 return walletInstance;
3933 bool CWallet::InitLoadWallet()
3935 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
3936 LogPrintf("Wallet disabled!\n");
3937 return true;
3940 for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
3941 CWallet * const pwallet = CreateWalletFromFile(walletFile);
3942 if (!pwallet) {
3943 return false;
3945 vpwallets.push_back(pwallet);
3948 return true;
3951 std::atomic<bool> CWallet::fFlushScheduled(false);
3953 void CWallet::postInitProcess(CScheduler& scheduler)
3955 // Add wallet transactions that aren't already in a block to mempool
3956 // Do this here as mempool requires genesis block to be loaded
3957 ReacceptWalletTransactions();
3959 // Run a thread to flush wallet periodically
3960 if (!CWallet::fFlushScheduled.exchange(true)) {
3961 scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
3965 bool CWallet::ParameterInteraction()
3967 SoftSetArg("-wallet", DEFAULT_WALLET_DAT);
3968 const bool is_multiwallet = gArgs.GetArgs("-wallet").size() > 1;
3970 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
3971 return true;
3973 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && SoftSetBoolArg("-walletbroadcast", false)) {
3974 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
3977 if (GetBoolArg("-salvagewallet", false) && SoftSetBoolArg("-rescan", true)) {
3978 if (is_multiwallet) {
3979 return InitError(strprintf("%s is only allowed with a single wallet file", "-salvagewallet"));
3981 // Rewrite just private keys: rescan to find transactions
3982 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
3985 // -zapwallettx implies a rescan
3986 if (GetBoolArg("-zapwallettxes", false) && SoftSetBoolArg("-rescan", true)) {
3987 if (is_multiwallet) {
3988 return InitError(strprintf("%s is only allowed with a single wallet file", "-zapwallettxes"));
3990 LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
3993 if (is_multiwallet) {
3994 if (GetBoolArg("-upgradewallet", false)) {
3995 return InitError(strprintf("%s is only allowed with a single wallet file", "-upgradewallet"));
3999 if (GetBoolArg("-sysperms", false))
4000 return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
4001 if (GetArg("-prune", 0) && GetBoolArg("-rescan", false))
4002 return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
4004 if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB)
4005 InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
4006 _("The wallet will avoid paying less than the minimum relay fee."));
4008 if (IsArgSet("-mintxfee"))
4010 CAmount n = 0;
4011 if (!ParseMoney(GetArg("-mintxfee", ""), n) || 0 == n)
4012 return InitError(AmountErrMsg("mintxfee", GetArg("-mintxfee", "")));
4013 if (n > HIGH_TX_FEE_PER_KB)
4014 InitWarning(AmountHighWarn("-mintxfee") + " " +
4015 _("This is the minimum transaction fee you pay on every transaction."));
4016 CWallet::minTxFee = CFeeRate(n);
4018 if (IsArgSet("-fallbackfee"))
4020 CAmount nFeePerK = 0;
4021 if (!ParseMoney(GetArg("-fallbackfee", ""), nFeePerK))
4022 return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), GetArg("-fallbackfee", "")));
4023 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4024 InitWarning(AmountHighWarn("-fallbackfee") + " " +
4025 _("This is the transaction fee you may pay when fee estimates are not available."));
4026 CWallet::fallbackFee = CFeeRate(nFeePerK);
4028 if (IsArgSet("-paytxfee"))
4030 CAmount nFeePerK = 0;
4031 if (!ParseMoney(GetArg("-paytxfee", ""), nFeePerK))
4032 return InitError(AmountErrMsg("paytxfee", GetArg("-paytxfee", "")));
4033 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4034 InitWarning(AmountHighWarn("-paytxfee") + " " +
4035 _("This is the transaction fee you will pay if you send a transaction."));
4037 payTxFee = CFeeRate(nFeePerK, 1000);
4038 if (payTxFee < ::minRelayTxFee)
4040 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
4041 GetArg("-paytxfee", ""), ::minRelayTxFee.ToString()));
4044 if (IsArgSet("-maxtxfee"))
4046 CAmount nMaxFee = 0;
4047 if (!ParseMoney(GetArg("-maxtxfee", ""), nMaxFee))
4048 return InitError(AmountErrMsg("maxtxfee", GetArg("-maxtxfee", "")));
4049 if (nMaxFee > HIGH_MAX_TX_FEE)
4050 InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
4051 maxTxFee = nMaxFee;
4052 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
4054 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
4055 GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString()));
4058 nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
4059 bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
4060 fWalletRbf = GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
4062 return true;
4065 bool CWallet::BackupWallet(const std::string& strDest)
4067 return dbw->Backup(strDest);
4070 CKeyPool::CKeyPool()
4072 nTime = GetTime();
4073 fInternal = false;
4076 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
4078 nTime = GetTime();
4079 vchPubKey = vchPubKeyIn;
4080 fInternal = internalIn;
4083 CWalletKey::CWalletKey(int64_t nExpires)
4085 nTimeCreated = (nExpires ? GetTime() : 0);
4086 nTimeExpires = nExpires;
4089 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
4091 // Update the tx's hashBlock
4092 hashBlock = pindex->GetBlockHash();
4094 // set the position of the transaction in the block
4095 nIndex = posInBlock;
4098 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4100 if (hashUnset())
4101 return 0;
4103 AssertLockHeld(cs_main);
4105 // Find the block it claims to be in
4106 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4107 if (mi == mapBlockIndex.end())
4108 return 0;
4109 CBlockIndex* pindex = (*mi).second;
4110 if (!pindex || !chainActive.Contains(pindex))
4111 return 0;
4113 pindexRet = pindex;
4114 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4117 int CMerkleTx::GetBlocksToMaturity() const
4119 if (!IsCoinBase())
4120 return 0;
4121 return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4125 bool CMerkleTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
4127 return ::AcceptToMemoryPool(mempool, state, tx, true, NULL, NULL, false, nAbsurdFee);