Remove unreachable or otherwise redundant code
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blobe95a8c809f2df3357c56f106179b303081e94465
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()]);
210 bool CWallet::LoadKeyMetadata(const CTxDestination& keyID, const CKeyMetadata &meta)
212 AssertLockHeld(cs_wallet); // mapKeyMetadata
213 UpdateTimeFirstKey(meta.nCreateTime);
214 mapKeyMetadata[keyID] = meta;
215 return true;
218 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
220 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
223 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
225 AssertLockHeld(cs_wallet);
226 if (nCreateTime <= 1) {
227 // Cannot determine birthday information, so set the wallet birthday to
228 // the beginning of time.
229 nTimeFirstKey = 1;
230 } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
231 nTimeFirstKey = nCreateTime;
235 bool CWallet::AddCScript(const CScript& redeemScript)
237 if (!CCryptoKeyStore::AddCScript(redeemScript))
238 return false;
239 return CWalletDB(*dbw).WriteCScript(Hash160(redeemScript), redeemScript);
242 bool CWallet::LoadCScript(const CScript& redeemScript)
244 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
245 * that never can be redeemed. However, old wallets may still contain
246 * these. Do not add them to the wallet and warn. */
247 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
249 std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
250 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",
251 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
252 return true;
255 return CCryptoKeyStore::AddCScript(redeemScript);
258 bool CWallet::AddWatchOnly(const CScript& dest)
260 if (!CCryptoKeyStore::AddWatchOnly(dest))
261 return false;
262 const CKeyMetadata& meta = mapKeyMetadata[CScriptID(dest)];
263 UpdateTimeFirstKey(meta.nCreateTime);
264 NotifyWatchonlyChanged(true);
265 return CWalletDB(*dbw).WriteWatchOnly(dest, meta);
268 bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
270 mapKeyMetadata[CScriptID(dest)].nCreateTime = nCreateTime;
271 return AddWatchOnly(dest);
274 bool CWallet::RemoveWatchOnly(const CScript &dest)
276 AssertLockHeld(cs_wallet);
277 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
278 return false;
279 if (!HaveWatchOnly())
280 NotifyWatchonlyChanged(false);
281 if (!CWalletDB(*dbw).EraseWatchOnly(dest))
282 return false;
284 return true;
287 bool CWallet::LoadWatchOnly(const CScript &dest)
289 return CCryptoKeyStore::AddWatchOnly(dest);
292 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
294 CCrypter crypter;
295 CKeyingMaterial _vMasterKey;
298 LOCK(cs_wallet);
299 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
301 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
302 return false;
303 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
304 continue; // try another master key
305 if (CCryptoKeyStore::Unlock(_vMasterKey))
306 return true;
309 return false;
312 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
314 bool fWasLocked = IsLocked();
317 LOCK(cs_wallet);
318 Lock();
320 CCrypter crypter;
321 CKeyingMaterial _vMasterKey;
322 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
324 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
325 return false;
326 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
327 return false;
328 if (CCryptoKeyStore::Unlock(_vMasterKey))
330 int64_t nStartTime = GetTimeMillis();
331 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
332 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
334 nStartTime = GetTimeMillis();
335 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
336 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
338 if (pMasterKey.second.nDeriveIterations < 25000)
339 pMasterKey.second.nDeriveIterations = 25000;
341 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
343 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
344 return false;
345 if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
346 return false;
347 CWalletDB(*dbw).WriteMasterKey(pMasterKey.first, pMasterKey.second);
348 if (fWasLocked)
349 Lock();
350 return true;
355 return false;
358 void CWallet::SetBestChain(const CBlockLocator& loc)
360 CWalletDB walletdb(*dbw);
361 walletdb.WriteBestBlock(loc);
364 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
366 LOCK(cs_wallet); // nWalletVersion
367 if (nWalletVersion >= nVersion)
368 return true;
370 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
371 if (fExplicit && nVersion > nWalletMaxVersion)
372 nVersion = FEATURE_LATEST;
374 nWalletVersion = nVersion;
376 if (nVersion > nWalletMaxVersion)
377 nWalletMaxVersion = nVersion;
380 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(*dbw);
381 if (nWalletVersion > 40000)
382 pwalletdb->WriteMinVersion(nWalletVersion);
383 if (!pwalletdbIn)
384 delete pwalletdb;
387 return true;
390 bool CWallet::SetMaxVersion(int nVersion)
392 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
393 // cannot downgrade below current version
394 if (nWalletVersion > nVersion)
395 return false;
397 nWalletMaxVersion = nVersion;
399 return true;
402 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
404 std::set<uint256> result;
405 AssertLockHeld(cs_wallet);
407 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
408 if (it == mapWallet.end())
409 return result;
410 const CWalletTx& wtx = it->second;
412 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
414 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
416 if (mapTxSpends.count(txin.prevout) <= 1)
417 continue; // No conflict if zero or one spends
418 range = mapTxSpends.equal_range(txin.prevout);
419 for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
420 result.insert(_it->second);
422 return result;
425 bool CWallet::HasWalletSpend(const uint256& txid) const
427 AssertLockHeld(cs_wallet);
428 auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
429 return (iter != mapTxSpends.end() && iter->first.hash == txid);
432 void CWallet::Flush(bool shutdown)
434 dbw->Flush(shutdown);
437 bool CWallet::Verify()
439 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
440 return true;
442 uiInterface.InitMessage(_("Verifying wallet(s)..."));
444 for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
445 if (boost::filesystem::path(walletFile).filename() != walletFile) {
446 return InitError(_("-wallet parameter must only specify a filename (not a path)"));
447 } else if (SanitizeString(walletFile, SAFE_CHARS_FILENAME) != walletFile) {
448 return InitError(_("Invalid characters in -wallet filename"));
451 std::string strError;
452 if (!CWalletDB::VerifyEnvironment(walletFile, GetDataDir().string(), strError)) {
453 return InitError(strError);
456 if (GetBoolArg("-salvagewallet", false)) {
457 // Recover readable keypairs:
458 CWallet dummyWallet;
459 std::string backup_filename;
460 if (!CWalletDB::Recover(walletFile, (void *)&dummyWallet, CWalletDB::RecoverKeysOnlyFilter, backup_filename)) {
461 return false;
465 std::string strWarning;
466 bool dbV = CWalletDB::VerifyDatabaseFile(walletFile, GetDataDir().string(), strWarning, strError);
467 if (!strWarning.empty()) {
468 InitWarning(strWarning);
470 if (!dbV) {
471 InitError(strError);
472 return false;
476 return true;
479 void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
481 // We want all the wallet transactions in range to have the same metadata as
482 // the oldest (smallest nOrderPos).
483 // So: find smallest nOrderPos:
485 int nMinOrderPos = std::numeric_limits<int>::max();
486 const CWalletTx* copyFrom = NULL;
487 for (TxSpends::iterator it = range.first; it != range.second; ++it)
489 const uint256& hash = it->second;
490 int n = mapWallet[hash].nOrderPos;
491 if (n < nMinOrderPos)
493 nMinOrderPos = n;
494 copyFrom = &mapWallet[hash];
497 // Now copy data from copyFrom to rest:
498 for (TxSpends::iterator it = range.first; it != range.second; ++it)
500 const uint256& hash = it->second;
501 CWalletTx* copyTo = &mapWallet[hash];
502 if (copyFrom == copyTo) continue;
503 if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
504 copyTo->mapValue = copyFrom->mapValue;
505 copyTo->vOrderForm = copyFrom->vOrderForm;
506 // fTimeReceivedIsTxTime not copied on purpose
507 // nTimeReceived not copied on purpose
508 copyTo->nTimeSmart = copyFrom->nTimeSmart;
509 copyTo->fFromMe = copyFrom->fFromMe;
510 copyTo->strFromAccount = copyFrom->strFromAccount;
511 // nOrderPos not copied on purpose
512 // cached members not copied on purpose
517 * Outpoint is spent if any non-conflicted transaction
518 * spends it:
520 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
522 const COutPoint outpoint(hash, n);
523 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
524 range = mapTxSpends.equal_range(outpoint);
526 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
528 const uint256& wtxid = it->second;
529 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
530 if (mit != mapWallet.end()) {
531 int depth = mit->second.GetDepthInMainChain();
532 if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
533 return true; // Spent
536 return false;
539 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
541 mapTxSpends.insert(std::make_pair(outpoint, wtxid));
543 std::pair<TxSpends::iterator, TxSpends::iterator> range;
544 range = mapTxSpends.equal_range(outpoint);
545 SyncMetaData(range);
549 void CWallet::AddToSpends(const uint256& wtxid)
551 assert(mapWallet.count(wtxid));
552 CWalletTx& thisTx = mapWallet[wtxid];
553 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
554 return;
556 BOOST_FOREACH(const CTxIn& txin, thisTx.tx->vin)
557 AddToSpends(txin.prevout, wtxid);
560 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
562 if (IsCrypted())
563 return false;
565 CKeyingMaterial _vMasterKey;
567 _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
568 GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
570 CMasterKey kMasterKey;
572 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
573 GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
575 CCrypter crypter;
576 int64_t nStartTime = GetTimeMillis();
577 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
578 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
580 nStartTime = GetTimeMillis();
581 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
582 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
584 if (kMasterKey.nDeriveIterations < 25000)
585 kMasterKey.nDeriveIterations = 25000;
587 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
589 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
590 return false;
591 if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
592 return false;
595 LOCK(cs_wallet);
596 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
597 assert(!pwalletdbEncryption);
598 pwalletdbEncryption = new CWalletDB(*dbw);
599 if (!pwalletdbEncryption->TxnBegin()) {
600 delete pwalletdbEncryption;
601 pwalletdbEncryption = NULL;
602 return false;
604 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
606 if (!EncryptKeys(_vMasterKey))
608 pwalletdbEncryption->TxnAbort();
609 delete pwalletdbEncryption;
610 // We now probably have half of our keys encrypted in memory, and half not...
611 // die and let the user reload the unencrypted wallet.
612 assert(false);
615 // Encryption was introduced in version 0.4.0
616 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
618 if (!pwalletdbEncryption->TxnCommit()) {
619 delete pwalletdbEncryption;
620 // We now have keys encrypted in memory, but not on disk...
621 // die to avoid confusion and let the user reload the unencrypted wallet.
622 assert(false);
625 delete pwalletdbEncryption;
626 pwalletdbEncryption = NULL;
628 Lock();
629 Unlock(strWalletPassphrase);
631 // if we are using HD, replace the HD master key (seed) with a new one
632 if (IsHDEnabled()) {
633 if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
634 return false;
638 NewKeyPool();
639 Lock();
641 // Need to completely rewrite the wallet file; if we don't, bdb might keep
642 // bits of the unencrypted private key in slack space in the database file.
643 dbw->Rewrite();
646 NotifyStatusChanged(this);
648 return true;
651 DBErrors CWallet::ReorderTransactions()
653 LOCK(cs_wallet);
654 CWalletDB walletdb(*dbw);
656 // Old wallets didn't have any defined order for transactions
657 // Probably a bad idea to change the output of this
659 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
660 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
661 typedef std::multimap<int64_t, TxPair > TxItems;
662 TxItems txByTime;
664 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
666 CWalletTx* wtx = &((*it).second);
667 txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
669 std::list<CAccountingEntry> acentries;
670 walletdb.ListAccountCreditDebit("", acentries);
671 BOOST_FOREACH(CAccountingEntry& entry, acentries)
673 txByTime.insert(std::make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
676 nOrderPosNext = 0;
677 std::vector<int64_t> nOrderPosOffsets;
678 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
680 CWalletTx *const pwtx = (*it).second.first;
681 CAccountingEntry *const pacentry = (*it).second.second;
682 int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
684 if (nOrderPos == -1)
686 nOrderPos = nOrderPosNext++;
687 nOrderPosOffsets.push_back(nOrderPos);
689 if (pwtx)
691 if (!walletdb.WriteTx(*pwtx))
692 return DB_LOAD_FAIL;
694 else
695 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
696 return DB_LOAD_FAIL;
698 else
700 int64_t nOrderPosOff = 0;
701 BOOST_FOREACH(const int64_t& nOffsetStart, nOrderPosOffsets)
703 if (nOrderPos >= nOffsetStart)
704 ++nOrderPosOff;
706 nOrderPos += nOrderPosOff;
707 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
709 if (!nOrderPosOff)
710 continue;
712 // Since we're changing the order, write it back
713 if (pwtx)
715 if (!walletdb.WriteTx(*pwtx))
716 return DB_LOAD_FAIL;
718 else
719 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
720 return DB_LOAD_FAIL;
723 walletdb.WriteOrderPosNext(nOrderPosNext);
725 return DB_LOAD_OK;
728 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
730 AssertLockHeld(cs_wallet); // nOrderPosNext
731 int64_t nRet = nOrderPosNext++;
732 if (pwalletdb) {
733 pwalletdb->WriteOrderPosNext(nOrderPosNext);
734 } else {
735 CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
737 return nRet;
740 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
742 CWalletDB walletdb(*dbw);
743 if (!walletdb.TxnBegin())
744 return false;
746 int64_t nNow = GetAdjustedTime();
748 // Debit
749 CAccountingEntry debit;
750 debit.nOrderPos = IncOrderPosNext(&walletdb);
751 debit.strAccount = strFrom;
752 debit.nCreditDebit = -nAmount;
753 debit.nTime = nNow;
754 debit.strOtherAccount = strTo;
755 debit.strComment = strComment;
756 AddAccountingEntry(debit, &walletdb);
758 // Credit
759 CAccountingEntry credit;
760 credit.nOrderPos = IncOrderPosNext(&walletdb);
761 credit.strAccount = strTo;
762 credit.nCreditDebit = nAmount;
763 credit.nTime = nNow;
764 credit.strOtherAccount = strFrom;
765 credit.strComment = strComment;
766 AddAccountingEntry(credit, &walletdb);
768 if (!walletdb.TxnCommit())
769 return false;
771 return true;
774 bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
776 CWalletDB walletdb(*dbw);
778 CAccount account;
779 walletdb.ReadAccount(strAccount, account);
781 if (!bForceNew) {
782 if (!account.vchPubKey.IsValid())
783 bForceNew = true;
784 else {
785 // Check if the current key has been used
786 CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
787 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
788 it != mapWallet.end() && account.vchPubKey.IsValid();
789 ++it)
790 BOOST_FOREACH(const CTxOut& txout, (*it).second.tx->vout)
791 if (txout.scriptPubKey == scriptPubKey) {
792 bForceNew = true;
793 break;
798 // Generate a new key
799 if (bForceNew) {
800 if (!GetKeyFromPool(account.vchPubKey, false))
801 return false;
803 SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
804 walletdb.WriteAccount(strAccount, account);
807 pubKey = account.vchPubKey;
809 return true;
812 void CWallet::MarkDirty()
815 LOCK(cs_wallet);
816 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
817 item.second.MarkDirty();
821 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
823 LOCK(cs_wallet);
825 auto mi = mapWallet.find(originalHash);
827 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
828 assert(mi != mapWallet.end());
830 CWalletTx& wtx = (*mi).second;
832 // Ensure for now that we're not overwriting data
833 assert(wtx.mapValue.count("replaced_by_txid") == 0);
835 wtx.mapValue["replaced_by_txid"] = newHash.ToString();
837 CWalletDB walletdb(*dbw, "r+");
839 bool success = true;
840 if (!walletdb.WriteTx(wtx)) {
841 LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
842 success = false;
845 NotifyTransactionChanged(this, originalHash, CT_UPDATED);
847 return success;
850 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
852 LOCK(cs_wallet);
854 CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
856 uint256 hash = wtxIn.GetHash();
858 // Inserts only if not already there, returns tx inserted or tx found
859 std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
860 CWalletTx& wtx = (*ret.first).second;
861 wtx.BindWallet(this);
862 bool fInsertedNew = ret.second;
863 if (fInsertedNew)
865 wtx.nTimeReceived = GetAdjustedTime();
866 wtx.nOrderPos = IncOrderPosNext(&walletdb);
867 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
868 wtx.nTimeSmart = ComputeTimeSmart(wtx);
869 AddToSpends(hash);
872 bool fUpdated = false;
873 if (!fInsertedNew)
875 // Merge
876 if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
878 wtx.hashBlock = wtxIn.hashBlock;
879 fUpdated = true;
881 // If no longer abandoned, update
882 if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
884 wtx.hashBlock = wtxIn.hashBlock;
885 fUpdated = true;
887 if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
889 wtx.nIndex = wtxIn.nIndex;
890 fUpdated = true;
892 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
894 wtx.fFromMe = wtxIn.fFromMe;
895 fUpdated = true;
899 //// debug print
900 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
902 // Write to disk
903 if (fInsertedNew || fUpdated)
904 if (!walletdb.WriteTx(wtx))
905 return false;
907 // Break debit/credit balance caches:
908 wtx.MarkDirty();
910 // Notify UI of new or updated transaction
911 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
913 // notify an external script when a wallet transaction comes in or is updated
914 std::string strCmd = GetArg("-walletnotify", "");
916 if ( !strCmd.empty())
918 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
919 boost::thread t(runCommand, strCmd); // thread runs free
922 return true;
925 bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
927 uint256 hash = wtxIn.GetHash();
929 mapWallet[hash] = wtxIn;
930 CWalletTx& wtx = mapWallet[hash];
931 wtx.BindWallet(this);
932 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
933 AddToSpends(hash);
934 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin) {
935 if (mapWallet.count(txin.prevout.hash)) {
936 CWalletTx& prevtx = mapWallet[txin.prevout.hash];
937 if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
938 MarkConflicted(prevtx.hashBlock, wtx.GetHash());
943 return true;
947 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
948 * be set when the transaction was known to be included in a block. When
949 * pIndex == NULL, then wallet state is not updated in AddToWallet, but
950 * notifications happen and cached balances are marked dirty.
952 * If fUpdate is true, existing transactions will be updated.
953 * TODO: One exception to this is that the abandoned state is cleared under the
954 * assumption that any further notification of a transaction that was considered
955 * abandoned is an indication that it is not safe to be considered abandoned.
956 * Abandoned state should probably be more carefully tracked via different
957 * posInBlock signals or by checking mempool presence when necessary.
959 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
961 const CTransaction& tx = *ptx;
963 AssertLockHeld(cs_wallet);
965 if (pIndex != NULL) {
966 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
967 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
968 while (range.first != range.second) {
969 if (range.first->second != tx.GetHash()) {
970 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);
971 MarkConflicted(pIndex->GetBlockHash(), range.first->second);
973 range.first++;
978 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
979 if (fExisted && !fUpdate) return false;
980 if (fExisted || IsMine(tx) || IsFromMe(tx))
982 CWalletTx wtx(this, ptx);
984 // Get merkle branch if transaction was found in a block
985 if (pIndex != NULL)
986 wtx.SetMerkleBranch(pIndex, posInBlock);
988 return AddToWallet(wtx, false);
991 return false;
994 bool CWallet::TransactionCanBeAbandoned(const uint256& hashTx) const
996 LOCK2(cs_main, cs_wallet);
997 const CWalletTx* wtx = GetWalletTx(hashTx);
998 return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() <= 0 && !wtx->InMempool();
1001 bool CWallet::AbandonTransaction(const uint256& hashTx)
1003 LOCK2(cs_main, cs_wallet);
1005 CWalletDB walletdb(*dbw, "r+");
1007 std::set<uint256> todo;
1008 std::set<uint256> done;
1010 // Can't mark abandoned if confirmed or in mempool
1011 assert(mapWallet.count(hashTx));
1012 CWalletTx& origtx = mapWallet[hashTx];
1013 if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
1014 return false;
1017 todo.insert(hashTx);
1019 while (!todo.empty()) {
1020 uint256 now = *todo.begin();
1021 todo.erase(now);
1022 done.insert(now);
1023 assert(mapWallet.count(now));
1024 CWalletTx& wtx = mapWallet[now];
1025 int currentconfirm = wtx.GetDepthInMainChain();
1026 // If the orig tx was not in block, none of its spends can be
1027 assert(currentconfirm <= 0);
1028 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1029 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1030 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1031 assert(!wtx.InMempool());
1032 wtx.nIndex = -1;
1033 wtx.setAbandoned();
1034 wtx.MarkDirty();
1035 walletdb.WriteTx(wtx);
1036 NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1037 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1038 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1039 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1040 if (!done.count(iter->second)) {
1041 todo.insert(iter->second);
1043 iter++;
1045 // If a transaction changes 'conflicted' state, that changes the balance
1046 // available of the outputs it spends. So force those to be recomputed
1047 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
1049 if (mapWallet.count(txin.prevout.hash))
1050 mapWallet[txin.prevout.hash].MarkDirty();
1055 return true;
1058 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1060 LOCK2(cs_main, cs_wallet);
1062 int conflictconfirms = 0;
1063 if (mapBlockIndex.count(hashBlock)) {
1064 CBlockIndex* pindex = mapBlockIndex[hashBlock];
1065 if (chainActive.Contains(pindex)) {
1066 conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1069 // If number of conflict confirms cannot be determined, this means
1070 // that the block is still unknown or not yet part of the main chain,
1071 // for example when loading the wallet during a reindex. Do nothing in that
1072 // case.
1073 if (conflictconfirms >= 0)
1074 return;
1076 // Do not flush the wallet here for performance reasons
1077 CWalletDB walletdb(*dbw, "r+", false);
1079 std::set<uint256> todo;
1080 std::set<uint256> done;
1082 todo.insert(hashTx);
1084 while (!todo.empty()) {
1085 uint256 now = *todo.begin();
1086 todo.erase(now);
1087 done.insert(now);
1088 assert(mapWallet.count(now));
1089 CWalletTx& wtx = mapWallet[now];
1090 int currentconfirm = wtx.GetDepthInMainChain();
1091 if (conflictconfirms < currentconfirm) {
1092 // Block is 'more conflicted' than current confirm; update.
1093 // Mark transaction as conflicted with this block.
1094 wtx.nIndex = -1;
1095 wtx.hashBlock = hashBlock;
1096 wtx.MarkDirty();
1097 walletdb.WriteTx(wtx);
1098 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1099 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1100 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1101 if (!done.count(iter->second)) {
1102 todo.insert(iter->second);
1104 iter++;
1106 // If a transaction changes 'conflicted' state, that changes the balance
1107 // available of the outputs it spends. So force those to be recomputed
1108 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
1110 if (mapWallet.count(txin.prevout.hash))
1111 mapWallet[txin.prevout.hash].MarkDirty();
1117 void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
1118 const CTransaction& tx = *ptx;
1120 if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
1121 return; // Not one of ours
1123 // If a transaction changes 'conflicted' state, that changes the balance
1124 // available of the outputs it spends. So force those to be
1125 // recomputed, also:
1126 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1128 if (mapWallet.count(txin.prevout.hash))
1129 mapWallet[txin.prevout.hash].MarkDirty();
1133 void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx) {
1134 LOCK2(cs_main, cs_wallet);
1135 SyncTransaction(ptx);
1138 void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
1139 LOCK2(cs_main, cs_wallet);
1140 // TODO: Temporarily ensure that mempool removals are notified before
1141 // connected transactions. This shouldn't matter, but the abandoned
1142 // state of transactions in our wallet is currently cleared when we
1143 // receive another notification and there is a race condition where
1144 // notification of a connected conflict might cause an outside process
1145 // to abandon a transaction and then have it inadvertently cleared by
1146 // the notification that the conflicted transaction was evicted.
1148 for (const CTransactionRef& ptx : vtxConflicted) {
1149 SyncTransaction(ptx);
1151 for (size_t i = 0; i < pblock->vtx.size(); i++) {
1152 SyncTransaction(pblock->vtx[i], pindex, i);
1156 void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
1157 LOCK2(cs_main, cs_wallet);
1159 for (const CTransactionRef& ptx : pblock->vtx) {
1160 SyncTransaction(ptx);
1166 isminetype CWallet::IsMine(const CTxIn &txin) const
1169 LOCK(cs_wallet);
1170 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1171 if (mi != mapWallet.end())
1173 const CWalletTx& prev = (*mi).second;
1174 if (txin.prevout.n < prev.tx->vout.size())
1175 return IsMine(prev.tx->vout[txin.prevout.n]);
1178 return ISMINE_NO;
1181 // Note that this function doesn't distinguish between a 0-valued input,
1182 // and a not-"is mine" (according to the filter) input.
1183 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1186 LOCK(cs_wallet);
1187 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1188 if (mi != mapWallet.end())
1190 const CWalletTx& prev = (*mi).second;
1191 if (txin.prevout.n < prev.tx->vout.size())
1192 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1193 return prev.tx->vout[txin.prevout.n].nValue;
1196 return 0;
1199 isminetype CWallet::IsMine(const CTxOut& txout) const
1201 return ::IsMine(*this, txout.scriptPubKey);
1204 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1206 if (!MoneyRange(txout.nValue))
1207 throw std::runtime_error(std::string(__func__) + ": value out of range");
1208 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1211 bool CWallet::IsChange(const CTxOut& txout) const
1213 // TODO: fix handling of 'change' outputs. The assumption is that any
1214 // payment to a script that is ours, but is not in the address book
1215 // is change. That assumption is likely to break when we implement multisignature
1216 // wallets that return change back into a multi-signature-protected address;
1217 // a better way of identifying which outputs are 'the send' and which are
1218 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1219 // which output, if any, was change).
1220 if (::IsMine(*this, txout.scriptPubKey))
1222 CTxDestination address;
1223 if (!ExtractDestination(txout.scriptPubKey, address))
1224 return true;
1226 LOCK(cs_wallet);
1227 if (!mapAddressBook.count(address))
1228 return true;
1230 return false;
1233 CAmount CWallet::GetChange(const CTxOut& txout) const
1235 if (!MoneyRange(txout.nValue))
1236 throw std::runtime_error(std::string(__func__) + ": value out of range");
1237 return (IsChange(txout) ? txout.nValue : 0);
1240 bool CWallet::IsMine(const CTransaction& tx) const
1242 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1243 if (IsMine(txout))
1244 return true;
1245 return false;
1248 bool CWallet::IsFromMe(const CTransaction& tx) const
1250 return (GetDebit(tx, ISMINE_ALL) > 0);
1253 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1255 CAmount nDebit = 0;
1256 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1258 nDebit += GetDebit(txin, filter);
1259 if (!MoneyRange(nDebit))
1260 throw std::runtime_error(std::string(__func__) + ": value out of range");
1262 return nDebit;
1265 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1267 LOCK(cs_wallet);
1269 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1271 auto mi = mapWallet.find(txin.prevout.hash);
1272 if (mi == mapWallet.end())
1273 return false; // any unknown inputs can't be from us
1275 const CWalletTx& prev = (*mi).second;
1277 if (txin.prevout.n >= prev.tx->vout.size())
1278 return false; // invalid input!
1280 if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1281 return false;
1283 return true;
1286 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1288 CAmount nCredit = 0;
1289 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1291 nCredit += GetCredit(txout, filter);
1292 if (!MoneyRange(nCredit))
1293 throw std::runtime_error(std::string(__func__) + ": value out of range");
1295 return nCredit;
1298 CAmount CWallet::GetChange(const CTransaction& tx) const
1300 CAmount nChange = 0;
1301 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1303 nChange += GetChange(txout);
1304 if (!MoneyRange(nChange))
1305 throw std::runtime_error(std::string(__func__) + ": value out of range");
1307 return nChange;
1310 CPubKey CWallet::GenerateNewHDMasterKey()
1312 CKey key;
1313 key.MakeNewKey(true);
1315 int64_t nCreationTime = GetTime();
1316 CKeyMetadata metadata(nCreationTime);
1318 // calculate the pubkey
1319 CPubKey pubkey = key.GetPubKey();
1320 assert(key.VerifyPubKey(pubkey));
1322 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1323 metadata.hdKeypath = "m";
1324 metadata.hdMasterKeyID = pubkey.GetID();
1327 LOCK(cs_wallet);
1329 // mem store the metadata
1330 mapKeyMetadata[pubkey.GetID()] = metadata;
1332 // write the key&metadata to the database
1333 if (!AddKeyPubKey(key, pubkey))
1334 throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1337 return pubkey;
1340 bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
1342 LOCK(cs_wallet);
1343 // store the keyid (hash160) together with
1344 // the child index counter in the database
1345 // as a hdchain object
1346 CHDChain newHdChain;
1347 newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1348 newHdChain.masterKeyID = pubkey.GetID();
1349 SetHDChain(newHdChain, false);
1351 return true;
1354 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1356 LOCK(cs_wallet);
1357 if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
1358 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1360 hdChain = chain;
1361 return true;
1364 bool CWallet::IsHDEnabled() const
1366 return !hdChain.masterKeyID.IsNull();
1369 int64_t CWalletTx::GetTxTime() const
1371 int64_t n = nTimeSmart;
1372 return n ? n : nTimeReceived;
1375 int CWalletTx::GetRequestCount() const
1377 // Returns -1 if it wasn't being tracked
1378 int nRequests = -1;
1380 LOCK(pwallet->cs_wallet);
1381 if (IsCoinBase())
1383 // Generated block
1384 if (!hashUnset())
1386 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1387 if (mi != pwallet->mapRequestCount.end())
1388 nRequests = (*mi).second;
1391 else
1393 // Did anyone request this transaction?
1394 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1395 if (mi != pwallet->mapRequestCount.end())
1397 nRequests = (*mi).second;
1399 // How about the block it's in?
1400 if (nRequests == 0 && !hashUnset())
1402 std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1403 if (_mi != pwallet->mapRequestCount.end())
1404 nRequests = (*_mi).second;
1405 else
1406 nRequests = 1; // If it's in someone else's block it must have got out
1411 return nRequests;
1414 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1415 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1417 nFee = 0;
1418 listReceived.clear();
1419 listSent.clear();
1420 strSentAccount = strFromAccount;
1422 // Compute fee:
1423 CAmount nDebit = GetDebit(filter);
1424 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1426 CAmount nValueOut = tx->GetValueOut();
1427 nFee = nDebit - nValueOut;
1430 // Sent/received.
1431 for (unsigned int i = 0; i < tx->vout.size(); ++i)
1433 const CTxOut& txout = tx->vout[i];
1434 isminetype fIsMine = pwallet->IsMine(txout);
1435 // Only need to handle txouts if AT LEAST one of these is true:
1436 // 1) they debit from us (sent)
1437 // 2) the output is to us (received)
1438 if (nDebit > 0)
1440 // Don't report 'change' txouts
1441 if (pwallet->IsChange(txout))
1442 continue;
1444 else if (!(fIsMine & filter))
1445 continue;
1447 // In either case, we need to get the destination address
1448 CTxDestination address;
1450 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1452 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1453 this->GetHash().ToString());
1454 address = CNoDestination();
1457 COutputEntry output = {address, txout.nValue, (int)i};
1459 // If we are debited by the transaction, add the output as a "sent" entry
1460 if (nDebit > 0)
1461 listSent.push_back(output);
1463 // If we are receiving the output, add it as a "received" entry
1464 if (fIsMine & filter)
1465 listReceived.push_back(output);
1471 * Scan the block chain (starting in pindexStart) for transactions
1472 * from or to us. If fUpdate is true, found transactions that already
1473 * exist in the wallet will be updated.
1475 * Returns null if scan was successful. Otherwise, if a complete rescan was not
1476 * possible (due to pruning or corruption), returns pointer to the most recent
1477 * block that could not be scanned.
1479 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1481 int64_t nNow = GetTime();
1482 const CChainParams& chainParams = Params();
1484 CBlockIndex* pindex = pindexStart;
1485 CBlockIndex* ret = nullptr;
1487 LOCK2(cs_main, cs_wallet);
1488 fAbortRescan = false;
1489 fScanningWallet = true;
1491 // no need to read and scan block, if block was created before
1492 // our wallet birthday (as adjusted for block time variability)
1493 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - TIMESTAMP_WINDOW)))
1494 pindex = chainActive.Next(pindex);
1496 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1497 double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
1498 double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
1499 while (pindex && !fAbortRescan)
1501 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1502 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1503 if (GetTime() >= nNow + 60) {
1504 nNow = GetTime();
1505 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1508 CBlock block;
1509 if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
1510 for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1511 AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
1513 } else {
1514 ret = pindex;
1516 pindex = chainActive.Next(pindex);
1518 if (pindex && fAbortRescan) {
1519 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1521 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1523 fScanningWallet = false;
1525 return ret;
1528 void CWallet::ReacceptWalletTransactions()
1530 // If transactions aren't being broadcasted, don't let them into local mempool either
1531 if (!fBroadcastTransactions)
1532 return;
1533 LOCK2(cs_main, cs_wallet);
1534 std::map<int64_t, CWalletTx*> mapSorted;
1536 // Sort pending wallet transactions based on their initial wallet insertion order
1537 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1539 const uint256& wtxid = item.first;
1540 CWalletTx& wtx = item.second;
1541 assert(wtx.GetHash() == wtxid);
1543 int nDepth = wtx.GetDepthInMainChain();
1545 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1546 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1550 // Try to add wallet transactions to memory pool
1551 BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
1553 CWalletTx& wtx = *(item.second);
1555 LOCK(mempool.cs);
1556 CValidationState state;
1557 wtx.AcceptToMemoryPool(maxTxFee, state);
1561 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1563 assert(pwallet->GetBroadcastTransactions());
1564 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1566 CValidationState state;
1567 /* GetDepthInMainChain already catches known conflicts. */
1568 if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1569 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1570 if (connman) {
1571 CInv inv(MSG_TX, GetHash());
1572 connman->ForEachNode([&inv](CNode* pnode)
1574 pnode->PushInventory(inv);
1576 return true;
1580 return false;
1583 std::set<uint256> CWalletTx::GetConflicts() const
1585 std::set<uint256> result;
1586 if (pwallet != NULL)
1588 uint256 myHash = GetHash();
1589 result = pwallet->GetConflicts(myHash);
1590 result.erase(myHash);
1592 return result;
1595 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1597 if (tx->vin.empty())
1598 return 0;
1600 CAmount debit = 0;
1601 if(filter & ISMINE_SPENDABLE)
1603 if (fDebitCached)
1604 debit += nDebitCached;
1605 else
1607 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1608 fDebitCached = true;
1609 debit += nDebitCached;
1612 if(filter & ISMINE_WATCH_ONLY)
1614 if(fWatchDebitCached)
1615 debit += nWatchDebitCached;
1616 else
1618 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1619 fWatchDebitCached = true;
1620 debit += nWatchDebitCached;
1623 return debit;
1626 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1628 // Must wait until coinbase is safely deep enough in the chain before valuing it
1629 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1630 return 0;
1632 CAmount credit = 0;
1633 if (filter & ISMINE_SPENDABLE)
1635 // GetBalance can assume transactions in mapWallet won't change
1636 if (fCreditCached)
1637 credit += nCreditCached;
1638 else
1640 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1641 fCreditCached = true;
1642 credit += nCreditCached;
1645 if (filter & ISMINE_WATCH_ONLY)
1647 if (fWatchCreditCached)
1648 credit += nWatchCreditCached;
1649 else
1651 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1652 fWatchCreditCached = true;
1653 credit += nWatchCreditCached;
1656 return credit;
1659 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1661 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1663 if (fUseCache && fImmatureCreditCached)
1664 return nImmatureCreditCached;
1665 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1666 fImmatureCreditCached = true;
1667 return nImmatureCreditCached;
1670 return 0;
1673 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1675 if (pwallet == 0)
1676 return 0;
1678 // Must wait until coinbase is safely deep enough in the chain before valuing it
1679 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1680 return 0;
1682 if (fUseCache && fAvailableCreditCached)
1683 return nAvailableCreditCached;
1685 CAmount nCredit = 0;
1686 uint256 hashTx = GetHash();
1687 for (unsigned int i = 0; i < tx->vout.size(); i++)
1689 if (!pwallet->IsSpent(hashTx, i))
1691 const CTxOut &txout = tx->vout[i];
1692 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1693 if (!MoneyRange(nCredit))
1694 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1698 nAvailableCreditCached = nCredit;
1699 fAvailableCreditCached = true;
1700 return nCredit;
1703 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1705 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1707 if (fUseCache && fImmatureWatchCreditCached)
1708 return nImmatureWatchCreditCached;
1709 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1710 fImmatureWatchCreditCached = true;
1711 return nImmatureWatchCreditCached;
1714 return 0;
1717 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1719 if (pwallet == 0)
1720 return 0;
1722 // Must wait until coinbase is safely deep enough in the chain before valuing it
1723 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1724 return 0;
1726 if (fUseCache && fAvailableWatchCreditCached)
1727 return nAvailableWatchCreditCached;
1729 CAmount nCredit = 0;
1730 for (unsigned int i = 0; i < tx->vout.size(); i++)
1732 if (!pwallet->IsSpent(GetHash(), i))
1734 const CTxOut &txout = tx->vout[i];
1735 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1736 if (!MoneyRange(nCredit))
1737 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1741 nAvailableWatchCreditCached = nCredit;
1742 fAvailableWatchCreditCached = true;
1743 return nCredit;
1746 CAmount CWalletTx::GetChange() const
1748 if (fChangeCached)
1749 return nChangeCached;
1750 nChangeCached = pwallet->GetChange(*this);
1751 fChangeCached = true;
1752 return nChangeCached;
1755 bool CWalletTx::InMempool() const
1757 LOCK(mempool.cs);
1758 return mempool.exists(GetHash());
1761 bool CWalletTx::IsTrusted() const
1763 // Quick answer in most cases
1764 if (!CheckFinalTx(*this))
1765 return false;
1766 int nDepth = GetDepthInMainChain();
1767 if (nDepth >= 1)
1768 return true;
1769 if (nDepth < 0)
1770 return false;
1771 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1772 return false;
1774 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1775 if (!InMempool())
1776 return false;
1778 // Trusted if all inputs are from us and are in the mempool:
1779 BOOST_FOREACH(const CTxIn& txin, tx->vin)
1781 // Transactions not sent by us: not trusted
1782 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1783 if (parent == NULL)
1784 return false;
1785 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1786 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1787 return false;
1789 return true;
1792 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1794 CMutableTransaction tx1 = *this->tx;
1795 CMutableTransaction tx2 = *_tx.tx;
1796 for (auto& txin : tx1.vin) txin.scriptSig = CScript();
1797 for (auto& txin : tx2.vin) txin.scriptSig = CScript();
1798 return CTransaction(tx1) == CTransaction(tx2);
1801 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1803 std::vector<uint256> result;
1805 LOCK(cs_wallet);
1806 // Sort them in chronological order
1807 std::multimap<unsigned int, CWalletTx*> mapSorted;
1808 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1810 CWalletTx& wtx = item.second;
1811 // Don't rebroadcast if newer than nTime:
1812 if (wtx.nTimeReceived > nTime)
1813 continue;
1814 mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1816 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1818 CWalletTx& wtx = *item.second;
1819 if (wtx.RelayWalletTransaction(connman))
1820 result.push_back(wtx.GetHash());
1822 return result;
1825 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1827 // Do this infrequently and randomly to avoid giving away
1828 // that these are our transactions.
1829 if (GetTime() < nNextResend || !fBroadcastTransactions)
1830 return;
1831 bool fFirst = (nNextResend == 0);
1832 nNextResend = GetTime() + GetRand(30 * 60);
1833 if (fFirst)
1834 return;
1836 // Only do it if there's been a new block since last time
1837 if (nBestBlockTime < nLastResend)
1838 return;
1839 nLastResend = GetTime();
1841 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1842 // block was found:
1843 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
1844 if (!relayed.empty())
1845 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
1848 /** @} */ // end of mapWallet
1853 /** @defgroup Actions
1855 * @{
1859 CAmount CWallet::GetBalance() const
1861 CAmount nTotal = 0;
1863 LOCK2(cs_main, cs_wallet);
1864 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1866 const CWalletTx* pcoin = &(*it).second;
1867 if (pcoin->IsTrusted())
1868 nTotal += pcoin->GetAvailableCredit();
1872 return nTotal;
1875 CAmount CWallet::GetUnconfirmedBalance() const
1877 CAmount nTotal = 0;
1879 LOCK2(cs_main, cs_wallet);
1880 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1882 const CWalletTx* pcoin = &(*it).second;
1883 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1884 nTotal += pcoin->GetAvailableCredit();
1887 return nTotal;
1890 CAmount CWallet::GetImmatureBalance() const
1892 CAmount nTotal = 0;
1894 LOCK2(cs_main, cs_wallet);
1895 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1897 const CWalletTx* pcoin = &(*it).second;
1898 nTotal += pcoin->GetImmatureCredit();
1901 return nTotal;
1904 CAmount CWallet::GetWatchOnlyBalance() const
1906 CAmount nTotal = 0;
1908 LOCK2(cs_main, cs_wallet);
1909 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1911 const CWalletTx* pcoin = &(*it).second;
1912 if (pcoin->IsTrusted())
1913 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1917 return nTotal;
1920 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
1922 CAmount nTotal = 0;
1924 LOCK2(cs_main, cs_wallet);
1925 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1927 const CWalletTx* pcoin = &(*it).second;
1928 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1929 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1932 return nTotal;
1935 CAmount CWallet::GetImmatureWatchOnlyBalance() const
1937 CAmount nTotal = 0;
1939 LOCK2(cs_main, cs_wallet);
1940 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1942 const CWalletTx* pcoin = &(*it).second;
1943 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1946 return nTotal;
1949 // Calculate total balance in a different way from GetBalance. The biggest
1950 // difference is that GetBalance sums up all unspent TxOuts paying to the
1951 // wallet, while this sums up both spent and unspent TxOuts paying to the
1952 // wallet, and then subtracts the values of TxIns spending from the wallet. This
1953 // also has fewer restrictions on which unconfirmed transactions are considered
1954 // trusted.
1955 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
1957 LOCK2(cs_main, cs_wallet);
1959 CAmount balance = 0;
1960 for (const auto& entry : mapWallet) {
1961 const CWalletTx& wtx = entry.second;
1962 const int depth = wtx.GetDepthInMainChain();
1963 if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
1964 continue;
1967 // Loop through tx outputs and add incoming payments. For outgoing txs,
1968 // treat change outputs specially, as part of the amount debited.
1969 CAmount debit = wtx.GetDebit(filter);
1970 const bool outgoing = debit > 0;
1971 for (const CTxOut& out : wtx.tx->vout) {
1972 if (outgoing && IsChange(out)) {
1973 debit -= out.nValue;
1974 } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
1975 balance += out.nValue;
1979 // For outgoing txs, subtract amount debited.
1980 if (outgoing && (!account || *account == wtx.strFromAccount)) {
1981 balance -= debit;
1985 if (account) {
1986 balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
1989 return balance;
1992 CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
1994 LOCK2(cs_main, cs_wallet);
1996 CAmount balance = 0;
1997 std::vector<COutput> vCoins;
1998 AvailableCoins(vCoins, true, coinControl);
1999 for (const COutput& out : vCoins) {
2000 if (out.fSpendable) {
2001 balance += out.tx->tx->vout[out.i].nValue;
2004 return balance;
2007 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
2009 vCoins.clear();
2012 LOCK2(cs_main, cs_wallet);
2014 CAmount nTotal = 0;
2016 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2018 const uint256& wtxid = it->first;
2019 const CWalletTx* pcoin = &(*it).second;
2021 if (!CheckFinalTx(*pcoin))
2022 continue;
2024 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2025 continue;
2027 int nDepth = pcoin->GetDepthInMainChain();
2028 if (nDepth < 0)
2029 continue;
2031 // We should not consider coins which aren't at least in our mempool
2032 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2033 if (nDepth == 0 && !pcoin->InMempool())
2034 continue;
2036 bool safeTx = pcoin->IsTrusted();
2038 // We should not consider coins from transactions that are replacing
2039 // other transactions.
2041 // Example: There is a transaction A which is replaced by bumpfee
2042 // transaction B. In this case, we want to prevent creation of
2043 // a transaction B' which spends an output of B.
2045 // Reason: If transaction A were initially confirmed, transactions B
2046 // and B' would no longer be valid, so the user would have to create
2047 // a new transaction C to replace B'. However, in the case of a
2048 // one-block reorg, transactions B' and C might BOTH be accepted,
2049 // when the user only wanted one of them. Specifically, there could
2050 // be a 1-block reorg away from the chain where transactions A and C
2051 // were accepted to another chain where B, B', and C were all
2052 // accepted.
2053 if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2054 safeTx = false;
2057 // Similarly, we should not consider coins from transactions that
2058 // have been replaced. In the example above, we would want to prevent
2059 // creation of a transaction A' spending an output of A, because if
2060 // transaction B were initially confirmed, conflicting with A and
2061 // A', we wouldn't want to the user to create a transaction D
2062 // intending to replace A', but potentially resulting in a scenario
2063 // where A, A', and D could all be accepted (instead of just B and
2064 // D, or just A and A' like the user would want).
2065 if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2066 safeTx = false;
2069 if (fOnlySafe && !safeTx) {
2070 continue;
2073 if (nDepth < nMinDepth || nDepth > nMaxDepth)
2074 continue;
2076 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2077 if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2078 continue;
2080 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint((*it).first, i)))
2081 continue;
2083 if (IsLockedCoin((*it).first, i))
2084 continue;
2086 if (IsSpent(wtxid, i))
2087 continue;
2089 isminetype mine = IsMine(pcoin->tx->vout[i]);
2091 if (mine == ISMINE_NO) {
2092 continue;
2095 bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2096 bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2098 vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2100 // Checks the sum amount of all UTXO's.
2101 if (nMinimumSumAmount != MAX_MONEY) {
2102 nTotal += pcoin->tx->vout[i].nValue;
2104 if (nTotal >= nMinimumSumAmount) {
2105 return;
2109 // Checks the maximum number of UTXO's.
2110 if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2111 return;
2118 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2120 // TODO: Add AssertLockHeld(cs_wallet) here.
2122 // Because the return value from this function contains pointers to
2123 // CWalletTx objects, callers to this function really should acquire the
2124 // cs_wallet lock before calling it. However, the current caller doesn't
2125 // acquire this lock yet. There was an attempt to add the missing lock in
2126 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2127 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2128 // avoid adding some extra complexity to the Qt code.
2130 std::map<CTxDestination, std::vector<COutput>> result;
2132 std::vector<COutput> availableCoins;
2133 AvailableCoins(availableCoins);
2135 LOCK2(cs_main, cs_wallet);
2136 for (auto& coin : availableCoins) {
2137 CTxDestination address;
2138 if (coin.fSpendable &&
2139 ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2140 result[address].emplace_back(std::move(coin));
2144 std::vector<COutPoint> lockedCoins;
2145 ListLockedCoins(lockedCoins);
2146 for (const auto& output : lockedCoins) {
2147 auto it = mapWallet.find(output.hash);
2148 if (it != mapWallet.end()) {
2149 int depth = it->second.GetDepthInMainChain();
2150 if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2151 IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2152 CTxDestination address;
2153 if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2154 result[address].emplace_back(
2155 &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2161 return result;
2164 const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
2166 const CTransaction* ptx = &tx;
2167 int n = output;
2168 while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2169 const COutPoint& prevout = ptx->vin[0].prevout;
2170 auto it = mapWallet.find(prevout.hash);
2171 if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2172 !IsMine(it->second.tx->vout[prevout.n])) {
2173 break;
2175 ptx = it->second.tx.get();
2176 n = prevout.n;
2178 return ptx->vout[n];
2181 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2182 std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2184 std::vector<char> vfIncluded;
2186 vfBest.assign(vValue.size(), true);
2187 nBest = nTotalLower;
2189 FastRandomContext insecure_rand;
2191 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2193 vfIncluded.assign(vValue.size(), false);
2194 CAmount nTotal = 0;
2195 bool fReachedTarget = false;
2196 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2198 for (unsigned int i = 0; i < vValue.size(); i++)
2200 //The solver here uses a randomized algorithm,
2201 //the randomness serves no real security purpose but is just
2202 //needed to prevent degenerate behavior and it is important
2203 //that the rng is fast. We do not use a constant random sequence,
2204 //because there may be some privacy improvement by making
2205 //the selection random.
2206 if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2208 nTotal += vValue[i].txout.nValue;
2209 vfIncluded[i] = true;
2210 if (nTotal >= nTargetValue)
2212 fReachedTarget = true;
2213 if (nTotal < nBest)
2215 nBest = nTotal;
2216 vfBest = vfIncluded;
2218 nTotal -= vValue[i].txout.nValue;
2219 vfIncluded[i] = false;
2227 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2228 std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
2230 setCoinsRet.clear();
2231 nValueRet = 0;
2233 // List of values less than target
2234 boost::optional<CInputCoin> coinLowestLarger;
2235 std::vector<CInputCoin> vValue;
2236 CAmount nTotalLower = 0;
2238 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2240 BOOST_FOREACH(const COutput &output, vCoins)
2242 if (!output.fSpendable)
2243 continue;
2245 const CWalletTx *pcoin = output.tx;
2247 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2248 continue;
2250 if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2251 continue;
2253 int i = output.i;
2255 CInputCoin coin = CInputCoin(pcoin, i);
2257 if (coin.txout.nValue == nTargetValue)
2259 setCoinsRet.insert(coin);
2260 nValueRet += coin.txout.nValue;
2261 return true;
2263 else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
2265 vValue.push_back(coin);
2266 nTotalLower += coin.txout.nValue;
2268 else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
2270 coinLowestLarger = coin;
2274 if (nTotalLower == nTargetValue)
2276 for (const auto& input : vValue)
2278 setCoinsRet.insert(input);
2279 nValueRet += input.txout.nValue;
2281 return true;
2284 if (nTotalLower < nTargetValue)
2286 if (!coinLowestLarger)
2287 return false;
2288 setCoinsRet.insert(coinLowestLarger.get());
2289 nValueRet += coinLowestLarger->txout.nValue;
2290 return true;
2293 // Solve subset sum by stochastic approximation
2294 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2295 std::reverse(vValue.begin(), vValue.end());
2296 std::vector<char> vfBest;
2297 CAmount nBest;
2299 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2300 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2301 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2303 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2304 // or the next bigger coin is closer), return the bigger coin
2305 if (coinLowestLarger &&
2306 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
2308 setCoinsRet.insert(coinLowestLarger.get());
2309 nValueRet += coinLowestLarger->txout.nValue;
2311 else {
2312 for (unsigned int i = 0; i < vValue.size(); i++)
2313 if (vfBest[i])
2315 setCoinsRet.insert(vValue[i]);
2316 nValueRet += vValue[i].txout.nValue;
2319 if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2320 LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2321 for (unsigned int i = 0; i < vValue.size(); i++) {
2322 if (vfBest[i]) {
2323 LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
2326 LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2330 return true;
2333 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2335 std::vector<COutput> vCoins(vAvailableCoins);
2337 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2338 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2340 BOOST_FOREACH(const COutput& out, vCoins)
2342 if (!out.fSpendable)
2343 continue;
2344 nValueRet += out.tx->tx->vout[out.i].nValue;
2345 setCoinsRet.insert(CInputCoin(out.tx, out.i));
2347 return (nValueRet >= nTargetValue);
2350 // calculate value from preset inputs and store them
2351 std::set<CInputCoin> setPresetCoins;
2352 CAmount nValueFromPresetInputs = 0;
2354 std::vector<COutPoint> vPresetInputs;
2355 if (coinControl)
2356 coinControl->ListSelected(vPresetInputs);
2357 BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
2359 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2360 if (it != mapWallet.end())
2362 const CWalletTx* pcoin = &it->second;
2363 // Clearly invalid input, fail
2364 if (pcoin->tx->vout.size() <= outpoint.n)
2365 return false;
2366 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2367 setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
2368 } else
2369 return false; // TODO: Allow non-wallet inputs
2372 // remove preset inputs from vCoins
2373 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2375 if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
2376 it = vCoins.erase(it);
2377 else
2378 ++it;
2381 size_t nMaxChainLength = std::min(GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2382 bool fRejectLongChains = GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2384 bool res = nTargetValue <= nValueFromPresetInputs ||
2385 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2386 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2387 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2388 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2389 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2390 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2391 (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2393 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2394 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2396 // add preset inputs to the total value selected
2397 nValueRet += nValueFromPresetInputs;
2399 return res;
2402 bool CWallet::SignTransaction(CMutableTransaction &tx)
2404 AssertLockHeld(cs_wallet); // mapWallet
2406 // sign the new tx
2407 CTransaction txNewConst(tx);
2408 int nIn = 0;
2409 for (const auto& input : tx.vin) {
2410 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2411 if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2412 return false;
2414 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2415 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2416 SignatureData sigdata;
2417 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2418 return false;
2420 UpdateTransaction(tx, nIn, sigdata);
2421 nIn++;
2423 return true;
2426 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, std::string& strFailReason, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl coinControl, bool keepReserveKey)
2428 std::vector<CRecipient> vecSend;
2430 // Turn the txout set into a CRecipient vector
2431 for (size_t idx = 0; idx < tx.vout.size(); idx++)
2433 const CTxOut& txOut = tx.vout[idx];
2434 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2435 vecSend.push_back(recipient);
2438 coinControl.fAllowOtherInputs = true;
2440 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2441 coinControl.Select(txin.prevout);
2443 CReserveKey reservekey(this);
2444 CWalletTx wtx;
2445 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, &coinControl, false))
2446 return false;
2448 if (nChangePosInOut != -1)
2449 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2451 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2452 for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
2453 tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2455 // Add new txins (keeping original txin scriptSig/order)
2456 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
2458 if (!coinControl.IsSelected(txin.prevout))
2460 tx.vin.push_back(txin);
2462 if (lockUnspents)
2464 LOCK2(cs_main, cs_wallet);
2465 LockCoin(txin.prevout);
2470 // optionally keep the change output key
2471 if (keepReserveKey)
2472 reservekey.KeepKey();
2474 return true;
2477 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2478 int& nChangePosInOut, std::string& strFailReason, const CCoinControl* coinControl, bool sign)
2480 CAmount nValue = 0;
2481 int nChangePosRequest = nChangePosInOut;
2482 unsigned int nSubtractFeeFromAmount = 0;
2483 for (const auto& recipient : vecSend)
2485 if (nValue < 0 || recipient.nAmount < 0)
2487 strFailReason = _("Transaction amounts must not be negative");
2488 return false;
2490 nValue += recipient.nAmount;
2492 if (recipient.fSubtractFeeFromAmount)
2493 nSubtractFeeFromAmount++;
2495 if (vecSend.empty())
2497 strFailReason = _("Transaction must have at least one recipient");
2498 return false;
2501 wtxNew.fTimeReceivedIsTxTime = true;
2502 wtxNew.BindWallet(this);
2503 CMutableTransaction txNew;
2505 // Discourage fee sniping.
2507 // For a large miner the value of the transactions in the best block and
2508 // the mempool can exceed the cost of deliberately attempting to mine two
2509 // blocks to orphan the current best block. By setting nLockTime such that
2510 // only the next block can include the transaction, we discourage this
2511 // practice as the height restricted and limited blocksize gives miners
2512 // considering fee sniping fewer options for pulling off this attack.
2514 // A simple way to think about this is from the wallet's point of view we
2515 // always want the blockchain to move forward. By setting nLockTime this
2516 // way we're basically making the statement that we only want this
2517 // transaction to appear in the next block; we don't want to potentially
2518 // encourage reorgs by allowing transactions to appear at lower heights
2519 // than the next block in forks of the best chain.
2521 // Of course, the subsidy is high enough, and transaction volume low
2522 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2523 // now we ensure code won't be written that makes assumptions about
2524 // nLockTime that preclude a fix later.
2525 txNew.nLockTime = chainActive.Height();
2527 // Secondly occasionally randomly pick a nLockTime even further back, so
2528 // that transactions that are delayed after signing for whatever reason,
2529 // e.g. high-latency mix networks and some CoinJoin implementations, have
2530 // better privacy.
2531 if (GetRandInt(10) == 0)
2532 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2534 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2535 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2538 std::set<CInputCoin> setCoins;
2539 LOCK2(cs_main, cs_wallet);
2541 std::vector<COutput> vAvailableCoins;
2542 AvailableCoins(vAvailableCoins, true, coinControl);
2544 nFeeRet = 0;
2545 // Start with no fee and loop until there is enough fee
2546 while (true)
2548 nChangePosInOut = nChangePosRequest;
2549 txNew.vin.clear();
2550 txNew.vout.clear();
2551 wtxNew.fFromMe = true;
2552 bool fFirst = true;
2554 CAmount nValueToSelect = nValue;
2555 if (nSubtractFeeFromAmount == 0)
2556 nValueToSelect += nFeeRet;
2557 // vouts to the payees
2558 for (const auto& recipient : vecSend)
2560 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2562 if (recipient.fSubtractFeeFromAmount)
2564 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2566 if (fFirst) // first receiver pays the remainder not divisible by output count
2568 fFirst = false;
2569 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2573 if (IsDust(txout, ::dustRelayFee))
2575 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2577 if (txout.nValue < 0)
2578 strFailReason = _("The transaction amount is too small to pay the fee");
2579 else
2580 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2582 else
2583 strFailReason = _("Transaction amount too small");
2584 return false;
2586 txNew.vout.push_back(txout);
2589 // Choose coins to use
2590 CAmount nValueIn = 0;
2591 setCoins.clear();
2592 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, coinControl))
2594 strFailReason = _("Insufficient funds");
2595 return false;
2598 const CAmount nChange = nValueIn - nValueToSelect;
2599 if (nChange > 0)
2601 // Fill a vout to ourself
2602 // TODO: pass in scriptChange instead of reservekey so
2603 // change transaction isn't always pay-to-bitcoin-address
2604 CScript scriptChange;
2606 // coin control: send change to custom address
2607 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
2608 scriptChange = GetScriptForDestination(coinControl->destChange);
2610 // no coin control: send change to newly generated address
2611 else
2613 // Note: We use a new key here to keep it from being obvious which side is the change.
2614 // The drawback is that by not reusing a previous key, the change may be lost if a
2615 // backup is restored, if the backup doesn't have the new private key for the change.
2616 // If we reused the old key, it would be possible to add code to look for and
2617 // rediscover unknown transactions that were written with keys of ours to recover
2618 // post-backup change.
2620 // Reserve a new key pair from key pool
2621 CPubKey vchPubKey;
2622 bool ret;
2623 ret = reservekey.GetReservedKey(vchPubKey, true);
2624 if (!ret)
2626 strFailReason = _("Keypool ran out, please call keypoolrefill first");
2627 return false;
2630 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2633 CTxOut newTxOut(nChange, scriptChange);
2635 // We do not move dust-change to fees, because the sender would end up paying more than requested.
2636 // This would be against the purpose of the all-inclusive feature.
2637 // So instead we raise the change and deduct from the recipient.
2638 if (nSubtractFeeFromAmount > 0 && IsDust(newTxOut, ::dustRelayFee))
2640 CAmount nDust = GetDustThreshold(newTxOut, ::dustRelayFee) - newTxOut.nValue;
2641 newTxOut.nValue += nDust; // raise change until no more dust
2642 for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
2644 if (vecSend[i].fSubtractFeeFromAmount)
2646 txNew.vout[i].nValue -= nDust;
2647 if (IsDust(txNew.vout[i], ::dustRelayFee))
2649 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2650 return false;
2652 break;
2657 // Never create dust outputs; if we would, just
2658 // add the dust to the fee.
2659 if (IsDust(newTxOut, ::dustRelayFee))
2661 nChangePosInOut = -1;
2662 nFeeRet += nChange;
2663 reservekey.ReturnKey();
2665 else
2667 if (nChangePosInOut == -1)
2669 // Insert change txn at random position:
2670 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2672 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2674 strFailReason = _("Change index out of range");
2675 return false;
2678 std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2679 txNew.vout.insert(position, newTxOut);
2681 } else {
2682 reservekey.ReturnKey();
2683 nChangePosInOut = -1;
2686 // Fill vin
2688 // Note how the sequence number is set to non-maxint so that
2689 // the nLockTime set above actually works.
2691 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2692 // we use the highest possible value in that range (maxint-2)
2693 // to avoid conflicting with other possible uses of nSequence,
2694 // and in the spirit of "smallest possible change from prior
2695 // behavior."
2696 bool rbf = coinControl ? coinControl->signalRbf : fWalletRbf;
2697 const uint32_t nSequence = rbf ? MAX_BIP125_RBF_SEQUENCE : (std::numeric_limits<unsigned int>::max() - 1);
2698 for (const auto& coin : setCoins)
2699 txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
2700 nSequence));
2702 // Fill in dummy signatures for fee calculation.
2703 if (!DummySignTx(txNew, setCoins)) {
2704 strFailReason = _("Signing transaction failed");
2705 return false;
2708 unsigned int nBytes = GetVirtualTransactionSize(txNew);
2710 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2711 for (auto& vin : txNew.vin) {
2712 vin.scriptSig = CScript();
2713 vin.scriptWitness.SetNull();
2716 // Allow to override the default confirmation target over the CoinControl instance
2717 int currentConfirmationTarget = nTxConfirmTarget;
2718 if (coinControl && coinControl->nConfirmTarget > 0)
2719 currentConfirmationTarget = coinControl->nConfirmTarget;
2721 CAmount nFeeNeeded = GetMinimumFee(nBytes, currentConfirmationTarget, ::mempool, ::feeEstimator);
2722 if (coinControl && coinControl->fOverrideFeeRate)
2723 nFeeNeeded = coinControl->nFeeRate.GetFee(nBytes);
2725 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2726 // because we must be at the maximum allowed fee.
2727 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2729 strFailReason = _("Transaction too large for fee policy");
2730 return false;
2733 if (nFeeRet >= nFeeNeeded) {
2734 // Reduce fee to only the needed amount if we have change
2735 // output to increase. This prevents potential overpayment
2736 // in fees if the coins selected to meet nFeeNeeded result
2737 // in a transaction that requires less fee than the prior
2738 // iteration.
2739 // TODO: The case where nSubtractFeeFromAmount > 0 remains
2740 // to be addressed because it requires returning the fee to
2741 // the payees and not the change output.
2742 // TODO: The case where there is no change output remains
2743 // to be addressed so we avoid creating too small an output.
2744 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2745 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2746 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2747 change_position->nValue += extraFeePaid;
2748 nFeeRet -= extraFeePaid;
2750 break; // Done, enough fee included.
2753 // Try to reduce change to include necessary fee
2754 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2755 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2756 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2757 // Only reduce change if remaining amount is still a large enough output.
2758 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2759 change_position->nValue -= additionalFeeNeeded;
2760 nFeeRet += additionalFeeNeeded;
2761 break; // Done, able to increase fee from change
2765 // Include more fee and try again.
2766 nFeeRet = nFeeNeeded;
2767 continue;
2771 if (sign)
2773 CTransaction txNewConst(txNew);
2774 int nIn = 0;
2775 for (const auto& coin : setCoins)
2777 const CScript& scriptPubKey = coin.txout.scriptPubKey;
2778 SignatureData sigdata;
2780 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2782 strFailReason = _("Signing transaction failed");
2783 return false;
2784 } else {
2785 UpdateTransaction(txNew, nIn, sigdata);
2788 nIn++;
2792 // Embed the constructed transaction data in wtxNew.
2793 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2795 // Limit size
2796 if (GetTransactionWeight(wtxNew) >= MAX_STANDARD_TX_WEIGHT)
2798 strFailReason = _("Transaction too large");
2799 return false;
2803 if (GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2804 // Lastly, ensure this tx will pass the mempool's chain limits
2805 LockPoints lp;
2806 CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
2807 CTxMemPool::setEntries setAncestors;
2808 size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2809 size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2810 size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2811 size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2812 std::string errString;
2813 if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2814 strFailReason = _("Transaction has too long of a mempool chain");
2815 return false;
2818 return true;
2822 * Call after CreateTransaction unless you want to abort
2824 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
2827 LOCK2(cs_main, cs_wallet);
2828 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
2830 // Take key pair from key pool so it won't be used again
2831 reservekey.KeepKey();
2833 // Add tx to wallet, because if it has change it's also ours,
2834 // otherwise just for transaction history.
2835 AddToWallet(wtxNew);
2837 // Notify that old coins are spent
2838 BOOST_FOREACH(const CTxIn& txin, wtxNew.tx->vin)
2840 CWalletTx &coin = mapWallet[txin.prevout.hash];
2841 coin.BindWallet(this);
2842 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2846 // Track how many getdata requests our transaction gets
2847 mapRequestCount[wtxNew.GetHash()] = 0;
2849 if (fBroadcastTransactions)
2851 // Broadcast
2852 if (!wtxNew.AcceptToMemoryPool(maxTxFee, state)) {
2853 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
2854 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2855 } else {
2856 wtxNew.RelayWalletTransaction(connman);
2860 return true;
2863 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
2864 CWalletDB walletdb(*dbw);
2865 return walletdb.ListAccountCreditDebit(strAccount, entries);
2868 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
2870 CWalletDB walletdb(*dbw);
2872 return AddAccountingEntry(acentry, &walletdb);
2875 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
2877 if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry)) {
2878 return false;
2881 laccentries.push_back(acentry);
2882 CAccountingEntry & entry = laccentries.back();
2883 wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
2885 return true;
2888 CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
2890 return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
2893 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, bool ignoreGlobalPayTxFee)
2895 // payTxFee is the user-set global for desired feerate
2896 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
2897 // User didn't set: use -txconfirmtarget to estimate...
2898 if (nFeeNeeded == 0 || ignoreGlobalPayTxFee) {
2899 int estimateFoundTarget = nConfirmTarget;
2900 nFeeNeeded = estimator.estimateSmartFee(nConfirmTarget, &estimateFoundTarget, pool).GetFee(nTxBytes);
2901 // ... unless we don't have enough mempool data for estimatefee, then use fallbackFee
2902 if (nFeeNeeded == 0)
2903 nFeeNeeded = fallbackFee.GetFee(nTxBytes);
2905 // prevent user from paying a fee below minRelayTxFee or minTxFee
2906 nFeeNeeded = std::max(nFeeNeeded, GetRequiredFee(nTxBytes));
2907 // But always obey the maximum
2908 if (nFeeNeeded > maxTxFee)
2909 nFeeNeeded = maxTxFee;
2910 return nFeeNeeded;
2916 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2918 fFirstRunRet = false;
2919 DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
2920 if (nLoadWalletRet == DB_NEED_REWRITE)
2922 if (dbw->Rewrite("\x04pool"))
2924 LOCK(cs_wallet);
2925 setKeyPool.clear();
2926 // Note: can't top-up keypool here, because wallet is locked.
2927 // User will be prompted to unlock wallet the next operation
2928 // that requires a new key.
2932 if (nLoadWalletRet != DB_LOAD_OK)
2933 return nLoadWalletRet;
2934 fFirstRunRet = !vchDefaultKey.IsValid();
2936 uiInterface.LoadWallet(this);
2938 return DB_LOAD_OK;
2941 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
2943 AssertLockHeld(cs_wallet); // mapWallet
2944 vchDefaultKey = CPubKey();
2945 DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
2946 for (uint256 hash : vHashOut)
2947 mapWallet.erase(hash);
2949 if (nZapSelectTxRet == DB_NEED_REWRITE)
2951 if (dbw->Rewrite("\x04pool"))
2953 setKeyPool.clear();
2954 // Note: can't top-up keypool here, because wallet is locked.
2955 // User will be prompted to unlock wallet the next operation
2956 // that requires a new key.
2960 if (nZapSelectTxRet != DB_LOAD_OK)
2961 return nZapSelectTxRet;
2963 MarkDirty();
2965 return DB_LOAD_OK;
2969 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
2971 vchDefaultKey = CPubKey();
2972 DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
2973 if (nZapWalletTxRet == DB_NEED_REWRITE)
2975 if (dbw->Rewrite("\x04pool"))
2977 LOCK(cs_wallet);
2978 setKeyPool.clear();
2979 // Note: can't top-up keypool here, because wallet is locked.
2980 // User will be prompted to unlock wallet the next operation
2981 // that requires a new key.
2985 if (nZapWalletTxRet != DB_LOAD_OK)
2986 return nZapWalletTxRet;
2988 return DB_LOAD_OK;
2992 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
2994 bool fUpdated = false;
2996 LOCK(cs_wallet); // mapAddressBook
2997 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
2998 fUpdated = mi != mapAddressBook.end();
2999 mapAddressBook[address].name = strName;
3000 if (!strPurpose.empty()) /* update purpose only if requested */
3001 mapAddressBook[address].purpose = strPurpose;
3003 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3004 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3005 if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
3006 return false;
3007 return CWalletDB(*dbw).WriteName(CBitcoinAddress(address).ToString(), strName);
3010 bool CWallet::DelAddressBook(const CTxDestination& address)
3013 LOCK(cs_wallet); // mapAddressBook
3015 // Delete destdata tuples associated with address
3016 std::string strAddress = CBitcoinAddress(address).ToString();
3017 BOOST_FOREACH(const PAIRTYPE(std::string, std::string) &item, mapAddressBook[address].destdata)
3019 CWalletDB(*dbw).EraseDestData(strAddress, item.first);
3021 mapAddressBook.erase(address);
3024 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3026 CWalletDB(*dbw).ErasePurpose(CBitcoinAddress(address).ToString());
3027 return CWalletDB(*dbw).EraseName(CBitcoinAddress(address).ToString());
3030 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
3032 CTxDestination address;
3033 if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
3034 auto mi = mapAddressBook.find(address);
3035 if (mi != mapAddressBook.end()) {
3036 return mi->second.name;
3039 // A scriptPubKey that doesn't have an entry in the address book is
3040 // associated with the default account ("").
3041 const static std::string DEFAULT_ACCOUNT_NAME;
3042 return DEFAULT_ACCOUNT_NAME;
3045 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
3047 if (!CWalletDB(*dbw).WriteDefaultKey(vchPubKey))
3048 return false;
3049 vchDefaultKey = vchPubKey;
3050 return true;
3054 * Mark old keypool keys as used,
3055 * and generate all new keys
3057 bool CWallet::NewKeyPool()
3060 LOCK(cs_wallet);
3061 CWalletDB walletdb(*dbw);
3062 BOOST_FOREACH(int64_t nIndex, setKeyPool)
3063 walletdb.ErasePool(nIndex);
3064 setKeyPool.clear();
3066 if (!TopUpKeyPool()) {
3067 return false;
3069 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3071 return true;
3074 size_t CWallet::KeypoolCountExternalKeys()
3076 AssertLockHeld(cs_wallet); // setKeyPool
3078 // immediately return setKeyPool's size if HD or HD_SPLIT is disabled or not supported
3079 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3080 return setKeyPool.size();
3082 CWalletDB walletdb(*dbw);
3084 // count amount of external keys
3085 size_t amountE = 0;
3086 for(const int64_t& id : setKeyPool)
3088 CKeyPool tmpKeypool;
3089 if (!walletdb.ReadPool(id, tmpKeypool))
3090 throw std::runtime_error(std::string(__func__) + ": read failed");
3091 amountE += !tmpKeypool.fInternal;
3094 return amountE;
3097 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3100 LOCK(cs_wallet);
3102 if (IsLocked())
3103 return false;
3105 // Top up key pool
3106 unsigned int nTargetSize;
3107 if (kpSize > 0)
3108 nTargetSize = kpSize;
3109 else
3110 nTargetSize = std::max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3112 // count amount of available keys (internal, external)
3113 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3114 int64_t amountExternal = KeypoolCountExternalKeys();
3115 int64_t amountInternal = setKeyPool.size() - amountExternal;
3116 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - amountExternal, (int64_t) 0);
3117 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - amountInternal, (int64_t) 0);
3119 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3121 // don't create extra internal keys
3122 missingInternal = 0;
3124 bool internal = false;
3125 CWalletDB walletdb(*dbw);
3126 for (int64_t i = missingInternal + missingExternal; i--;)
3128 int64_t nEnd = 1;
3129 if (i < missingInternal)
3130 internal = true;
3131 if (!setKeyPool.empty())
3132 nEnd = *(--setKeyPool.end()) + 1;
3133 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey(internal), internal)))
3134 throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3135 setKeyPool.insert(nEnd);
3136 LogPrintf("keypool added key %d, size=%u, internal=%d\n", nEnd, setKeyPool.size(), internal);
3139 return true;
3142 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool internal)
3144 nIndex = -1;
3145 keypool.vchPubKey = CPubKey();
3147 LOCK(cs_wallet);
3149 if (!IsLocked())
3150 TopUpKeyPool();
3152 // Get the oldest key
3153 if(setKeyPool.empty())
3154 return;
3156 CWalletDB walletdb(*dbw);
3158 // try to find a key that matches the internal/external filter
3159 for(const int64_t& id : setKeyPool)
3161 CKeyPool tmpKeypool;
3162 if (!walletdb.ReadPool(id, tmpKeypool))
3163 throw std::runtime_error(std::string(__func__) + ": read failed");
3164 if (!HaveKey(tmpKeypool.vchPubKey.GetID()))
3165 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3166 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT) || tmpKeypool.fInternal == internal)
3168 nIndex = id;
3169 keypool = tmpKeypool;
3170 setKeyPool.erase(id);
3171 assert(keypool.vchPubKey.IsValid());
3172 LogPrintf("keypool reserve %d\n", nIndex);
3173 return;
3179 void CWallet::KeepKey(int64_t nIndex)
3181 // Remove from key pool
3182 CWalletDB walletdb(*dbw);
3183 walletdb.ErasePool(nIndex);
3184 LogPrintf("keypool keep %d\n", nIndex);
3187 void CWallet::ReturnKey(int64_t nIndex)
3189 // Return to key pool
3191 LOCK(cs_wallet);
3192 setKeyPool.insert(nIndex);
3194 LogPrintf("keypool return %d\n", nIndex);
3197 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3199 CKeyPool keypool;
3201 LOCK(cs_wallet);
3202 int64_t nIndex = 0;
3203 ReserveKeyFromKeyPool(nIndex, keypool, internal);
3204 if (nIndex == -1)
3206 if (IsLocked()) return false;
3207 result = GenerateNewKey(internal);
3208 return true;
3210 KeepKey(nIndex);
3211 result = keypool.vchPubKey;
3213 return true;
3216 int64_t CWallet::GetOldestKeyPoolTime()
3218 LOCK(cs_wallet);
3220 // if the keypool is empty, return <NOW>
3221 if (setKeyPool.empty())
3222 return GetTime();
3224 CKeyPool keypool;
3225 CWalletDB walletdb(*dbw);
3227 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT))
3229 // if HD & HD Chain Split is enabled, response max(oldest-internal-key, oldest-external-key)
3230 int64_t now = GetTime();
3231 int64_t oldest_external = now, oldest_internal = now;
3233 for(const int64_t& id : setKeyPool)
3235 if (!walletdb.ReadPool(id, keypool)) {
3236 throw std::runtime_error(std::string(__func__) + ": read failed");
3238 if (keypool.fInternal && keypool.nTime < oldest_internal) {
3239 oldest_internal = keypool.nTime;
3241 else if (!keypool.fInternal && keypool.nTime < oldest_external) {
3242 oldest_external = keypool.nTime;
3244 if (oldest_internal != now && oldest_external != now) {
3245 break;
3248 return std::max(oldest_internal, oldest_external);
3250 // load oldest key from keypool, get time and return
3251 int64_t nIndex = *(setKeyPool.begin());
3252 if (!walletdb.ReadPool(nIndex, keypool))
3253 throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3254 assert(keypool.vchPubKey.IsValid());
3255 return keypool.nTime;
3258 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3260 std::map<CTxDestination, CAmount> balances;
3263 LOCK(cs_wallet);
3264 for (const auto& walletEntry : mapWallet)
3266 const CWalletTx *pcoin = &walletEntry.second;
3268 if (!pcoin->IsTrusted())
3269 continue;
3271 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3272 continue;
3274 int nDepth = pcoin->GetDepthInMainChain();
3275 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3276 continue;
3278 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3280 CTxDestination addr;
3281 if (!IsMine(pcoin->tx->vout[i]))
3282 continue;
3283 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3284 continue;
3286 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3288 if (!balances.count(addr))
3289 balances[addr] = 0;
3290 balances[addr] += n;
3295 return balances;
3298 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3300 AssertLockHeld(cs_wallet); // mapWallet
3301 std::set< std::set<CTxDestination> > groupings;
3302 std::set<CTxDestination> grouping;
3304 for (const auto& walletEntry : mapWallet)
3306 const CWalletTx *pcoin = &walletEntry.second;
3308 if (pcoin->tx->vin.size() > 0)
3310 bool any_mine = false;
3311 // group all input addresses with each other
3312 BOOST_FOREACH(CTxIn txin, pcoin->tx->vin)
3314 CTxDestination address;
3315 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3316 continue;
3317 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3318 continue;
3319 grouping.insert(address);
3320 any_mine = true;
3323 // group change with input addresses
3324 if (any_mine)
3326 BOOST_FOREACH(CTxOut txout, pcoin->tx->vout)
3327 if (IsChange(txout))
3329 CTxDestination txoutAddr;
3330 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3331 continue;
3332 grouping.insert(txoutAddr);
3335 if (grouping.size() > 0)
3337 groupings.insert(grouping);
3338 grouping.clear();
3342 // group lone addrs by themselves
3343 for (const auto& txout : pcoin->tx->vout)
3344 if (IsMine(txout))
3346 CTxDestination address;
3347 if(!ExtractDestination(txout.scriptPubKey, address))
3348 continue;
3349 grouping.insert(address);
3350 groupings.insert(grouping);
3351 grouping.clear();
3355 std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3356 std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3357 BOOST_FOREACH(std::set<CTxDestination> _grouping, groupings)
3359 // make a set of all the groups hit by this new group
3360 std::set< std::set<CTxDestination>* > hits;
3361 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3362 BOOST_FOREACH(CTxDestination address, _grouping)
3363 if ((it = setmap.find(address)) != setmap.end())
3364 hits.insert((*it).second);
3366 // merge all hit groups into a new single group and delete old groups
3367 std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3368 BOOST_FOREACH(std::set<CTxDestination>* hit, hits)
3370 merged->insert(hit->begin(), hit->end());
3371 uniqueGroupings.erase(hit);
3372 delete hit;
3374 uniqueGroupings.insert(merged);
3376 // update setmap
3377 BOOST_FOREACH(CTxDestination element, *merged)
3378 setmap[element] = merged;
3381 std::set< std::set<CTxDestination> > ret;
3382 BOOST_FOREACH(std::set<CTxDestination>* uniqueGrouping, uniqueGroupings)
3384 ret.insert(*uniqueGrouping);
3385 delete uniqueGrouping;
3388 return ret;
3391 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3393 LOCK(cs_wallet);
3394 std::set<CTxDestination> result;
3395 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
3397 const CTxDestination& address = item.first;
3398 const std::string& strName = item.second.name;
3399 if (strName == strAccount)
3400 result.insert(address);
3402 return result;
3405 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3407 if (nIndex == -1)
3409 CKeyPool keypool;
3410 pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3411 if (nIndex != -1)
3412 vchPubKey = keypool.vchPubKey;
3413 else {
3414 return false;
3417 assert(vchPubKey.IsValid());
3418 pubkey = vchPubKey;
3419 return true;
3422 void CReserveKey::KeepKey()
3424 if (nIndex != -1)
3425 pwallet->KeepKey(nIndex);
3426 nIndex = -1;
3427 vchPubKey = CPubKey();
3430 void CReserveKey::ReturnKey()
3432 if (nIndex != -1)
3433 pwallet->ReturnKey(nIndex);
3434 nIndex = -1;
3435 vchPubKey = CPubKey();
3438 void CWallet::GetAllReserveKeys(std::set<CKeyID>& setAddress) const
3440 setAddress.clear();
3442 CWalletDB walletdb(*dbw);
3444 LOCK2(cs_main, cs_wallet);
3445 BOOST_FOREACH(const int64_t& id, setKeyPool)
3447 CKeyPool keypool;
3448 if (!walletdb.ReadPool(id, keypool))
3449 throw std::runtime_error(std::string(__func__) + ": read failed");
3450 assert(keypool.vchPubKey.IsValid());
3451 CKeyID keyID = keypool.vchPubKey.GetID();
3452 if (!HaveKey(keyID))
3453 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3454 setAddress.insert(keyID);
3458 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
3460 std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
3461 CPubKey pubkey;
3462 if (!rKey->GetReservedKey(pubkey))
3463 return;
3465 script = rKey;
3466 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3469 void CWallet::LockCoin(const COutPoint& output)
3471 AssertLockHeld(cs_wallet); // setLockedCoins
3472 setLockedCoins.insert(output);
3475 void CWallet::UnlockCoin(const COutPoint& output)
3477 AssertLockHeld(cs_wallet); // setLockedCoins
3478 setLockedCoins.erase(output);
3481 void CWallet::UnlockAllCoins()
3483 AssertLockHeld(cs_wallet); // setLockedCoins
3484 setLockedCoins.clear();
3487 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3489 AssertLockHeld(cs_wallet); // setLockedCoins
3490 COutPoint outpt(hash, n);
3492 return (setLockedCoins.count(outpt) > 0);
3495 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3497 AssertLockHeld(cs_wallet); // setLockedCoins
3498 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3499 it != setLockedCoins.end(); it++) {
3500 COutPoint outpt = (*it);
3501 vOutpts.push_back(outpt);
3505 /** @} */ // end of Actions
3507 class CAffectedKeysVisitor : public boost::static_visitor<void> {
3508 private:
3509 const CKeyStore &keystore;
3510 std::vector<CKeyID> &vKeys;
3512 public:
3513 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
3515 void Process(const CScript &script) {
3516 txnouttype type;
3517 std::vector<CTxDestination> vDest;
3518 int nRequired;
3519 if (ExtractDestinations(script, type, vDest, nRequired)) {
3520 BOOST_FOREACH(const CTxDestination &dest, vDest)
3521 boost::apply_visitor(*this, dest);
3525 void operator()(const CKeyID &keyId) {
3526 if (keystore.HaveKey(keyId))
3527 vKeys.push_back(keyId);
3530 void operator()(const CScriptID &scriptId) {
3531 CScript script;
3532 if (keystore.GetCScript(scriptId, script))
3533 Process(script);
3536 void operator()(const CNoDestination &none) {}
3539 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3540 AssertLockHeld(cs_wallet); // mapKeyMetadata
3541 mapKeyBirth.clear();
3543 // get birth times for keys with metadata
3544 for (const auto& entry : mapKeyMetadata) {
3545 if (entry.second.nCreateTime) {
3546 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3550 // map in which we'll infer heights of other keys
3551 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3552 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3553 std::set<CKeyID> setKeys;
3554 GetKeys(setKeys);
3555 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
3556 if (mapKeyBirth.count(keyid) == 0)
3557 mapKeyFirstBlock[keyid] = pindexMax;
3559 setKeys.clear();
3561 // if there are no such keys, we're done
3562 if (mapKeyFirstBlock.empty())
3563 return;
3565 // find first block that affects those keys, if there are any left
3566 std::vector<CKeyID> vAffected;
3567 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3568 // iterate over all wallet transactions...
3569 const CWalletTx &wtx = (*it).second;
3570 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3571 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3572 // ... which are already in a block
3573 int nHeight = blit->second->nHeight;
3574 BOOST_FOREACH(const CTxOut &txout, wtx.tx->vout) {
3575 // iterate over all their outputs
3576 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3577 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
3578 // ... and all their affected keys
3579 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3580 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3581 rit->second = blit->second;
3583 vAffected.clear();
3588 // Extract block timestamps for those keys
3589 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3590 mapKeyBirth[it->first] = it->second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3594 * Compute smart timestamp for a transaction being added to the wallet.
3596 * Logic:
3597 * - If sending a transaction, assign its timestamp to the current time.
3598 * - If receiving a transaction outside a block, assign its timestamp to the
3599 * current time.
3600 * - If receiving a block with a future timestamp, assign all its (not already
3601 * known) transactions' timestamps to the current time.
3602 * - If receiving a block with a past timestamp, before the most recent known
3603 * transaction (that we care about), assign all its (not already known)
3604 * transactions' timestamps to the same timestamp as that most-recent-known
3605 * transaction.
3606 * - If receiving a block with a past timestamp, but after the most recent known
3607 * transaction, assign all its (not already known) transactions' timestamps to
3608 * the block time.
3610 * For more information see CWalletTx::nTimeSmart,
3611 * https://bitcointalk.org/?topic=54527, or
3612 * https://github.com/bitcoin/bitcoin/pull/1393.
3614 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3616 unsigned int nTimeSmart = wtx.nTimeReceived;
3617 if (!wtx.hashUnset()) {
3618 if (mapBlockIndex.count(wtx.hashBlock)) {
3619 int64_t latestNow = wtx.nTimeReceived;
3620 int64_t latestEntry = 0;
3622 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3623 int64_t latestTolerated = latestNow + 300;
3624 const TxItems& txOrdered = wtxOrdered;
3625 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3626 CWalletTx* const pwtx = it->second.first;
3627 if (pwtx == &wtx) {
3628 continue;
3630 CAccountingEntry* const pacentry = it->second.second;
3631 int64_t nSmartTime;
3632 if (pwtx) {
3633 nSmartTime = pwtx->nTimeSmart;
3634 if (!nSmartTime) {
3635 nSmartTime = pwtx->nTimeReceived;
3637 } else {
3638 nSmartTime = pacentry->nTime;
3640 if (nSmartTime <= latestTolerated) {
3641 latestEntry = nSmartTime;
3642 if (nSmartTime > latestNow) {
3643 latestNow = nSmartTime;
3645 break;
3649 int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3650 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3651 } else {
3652 LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3655 return nTimeSmart;
3658 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3660 if (boost::get<CNoDestination>(&dest))
3661 return false;
3663 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3664 return CWalletDB(*dbw).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
3667 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3669 if (!mapAddressBook[dest].destdata.erase(key))
3670 return false;
3671 return CWalletDB(*dbw).EraseDestData(CBitcoinAddress(dest).ToString(), key);
3674 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3676 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3677 return true;
3680 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3682 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3683 if(i != mapAddressBook.end())
3685 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3686 if(j != i->second.destdata.end())
3688 if(value)
3689 *value = j->second;
3690 return true;
3693 return false;
3696 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3698 LOCK(cs_wallet);
3699 std::vector<std::string> values;
3700 for (const auto& address : mapAddressBook) {
3701 for (const auto& data : address.second.destdata) {
3702 if (!data.first.compare(0, prefix.size(), prefix)) {
3703 values.emplace_back(data.second);
3707 return values;
3710 std::string CWallet::GetWalletHelpString(bool showDebug)
3712 std::string strUsage = HelpMessageGroup(_("Wallet options:"));
3713 strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
3714 strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE));
3715 strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
3716 CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)));
3717 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
3718 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)));
3719 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
3720 CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
3721 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
3722 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup"));
3723 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE));
3724 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));
3725 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));
3726 strUsage += HelpMessageOpt("-walletrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (default: %u)"), DEFAULT_WALLET_RBF));
3727 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
3728 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT));
3729 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST));
3730 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
3731 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
3732 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
3734 if (showDebug)
3736 strUsage += HelpMessageGroup(_("Wallet debugging/testing options:"));
3738 strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE));
3739 strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET));
3740 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB));
3741 strUsage += HelpMessageOpt("-walletrejectlongchains", strprintf(_("Wallet will not create transactions that violate mempool chain limits (default: %u)"), DEFAULT_WALLET_REJECT_LONG_CHAINS));
3744 return strUsage;
3747 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
3749 // needed to restore wallet transaction meta data after -zapwallettxes
3750 std::vector<CWalletTx> vWtx;
3752 if (GetBoolArg("-zapwallettxes", false)) {
3753 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3755 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3756 CWallet *tempWallet = new CWallet(std::move(dbw));
3757 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3758 if (nZapWalletRet != DB_LOAD_OK) {
3759 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3760 return NULL;
3763 delete tempWallet;
3764 tempWallet = NULL;
3767 uiInterface.InitMessage(_("Loading wallet..."));
3769 int64_t nStart = GetTimeMillis();
3770 bool fFirstRun = true;
3771 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3772 CWallet *walletInstance = new CWallet(std::move(dbw));
3773 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3774 if (nLoadWalletRet != DB_LOAD_OK)
3776 if (nLoadWalletRet == DB_CORRUPT) {
3777 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3778 return NULL;
3780 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3782 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3783 " or address book entries might be missing or incorrect."),
3784 walletFile));
3786 else if (nLoadWalletRet == DB_TOO_NEW) {
3787 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
3788 return NULL;
3790 else if (nLoadWalletRet == DB_NEED_REWRITE)
3792 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3793 return NULL;
3795 else {
3796 InitError(strprintf(_("Error loading %s"), walletFile));
3797 return NULL;
3801 if (GetBoolArg("-upgradewallet", fFirstRun))
3803 int nMaxVersion = GetArg("-upgradewallet", 0);
3804 if (nMaxVersion == 0) // the -upgradewallet without argument case
3806 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3807 nMaxVersion = CLIENT_VERSION;
3808 walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3810 else
3811 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3812 if (nMaxVersion < walletInstance->GetVersion())
3814 InitError(_("Cannot downgrade wallet"));
3815 return NULL;
3817 walletInstance->SetMaxVersion(nMaxVersion);
3820 if (fFirstRun)
3822 // Create new keyUser and set as default key
3823 if (GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && !walletInstance->IsHDEnabled()) {
3825 // ensure this wallet.dat can only be opened by clients supporting HD with chain split
3826 walletInstance->SetMinVersion(FEATURE_HD_SPLIT);
3828 // generate a new master key
3829 CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
3830 if (!walletInstance->SetHDMasterKey(masterPubKey))
3831 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
3833 CPubKey newDefaultKey;
3834 if (walletInstance->GetKeyFromPool(newDefaultKey, false)) {
3835 walletInstance->SetDefaultKey(newDefaultKey);
3836 if (!walletInstance->SetAddressBook(walletInstance->vchDefaultKey.GetID(), "", "receive")) {
3837 InitError(_("Cannot write default address") += "\n");
3838 return NULL;
3842 walletInstance->SetBestChain(chainActive.GetLocator());
3844 else if (IsArgSet("-usehd")) {
3845 bool useHD = GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
3846 if (walletInstance->IsHDEnabled() && !useHD) {
3847 InitError(strprintf(_("Error loading %s: You can't disable HD on a already existing HD wallet"), walletFile));
3848 return NULL;
3850 if (!walletInstance->IsHDEnabled() && useHD) {
3851 InitError(strprintf(_("Error loading %s: You can't enable HD on a already existing non-HD wallet"), walletFile));
3852 return NULL;
3856 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
3858 RegisterValidationInterface(walletInstance);
3860 CBlockIndex *pindexRescan = chainActive.Genesis();
3861 if (!GetBoolArg("-rescan", false))
3863 CWalletDB walletdb(*walletInstance->dbw);
3864 CBlockLocator locator;
3865 if (walletdb.ReadBestBlock(locator))
3866 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
3868 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
3870 //We can't rescan beyond non-pruned blocks, stop and throw an error
3871 //this might happen if a user uses a old wallet within a pruned node
3872 // or if he ran -disablewallet for a longer time, then decided to re-enable
3873 if (fPruneMode)
3875 CBlockIndex *block = chainActive.Tip();
3876 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
3877 block = block->pprev;
3879 if (pindexRescan != block) {
3880 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3881 return NULL;
3885 uiInterface.InitMessage(_("Rescanning..."));
3886 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
3887 nStart = GetTimeMillis();
3888 walletInstance->ScanForWalletTransactions(pindexRescan, true);
3889 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
3890 walletInstance->SetBestChain(chainActive.GetLocator());
3891 walletInstance->dbw->IncrementUpdateCounter();
3893 // Restore wallet transaction metadata after -zapwallettxes=1
3894 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
3896 CWalletDB walletdb(*walletInstance->dbw);
3898 BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
3900 uint256 hash = wtxOld.GetHash();
3901 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
3902 if (mi != walletInstance->mapWallet.end())
3904 const CWalletTx* copyFrom = &wtxOld;
3905 CWalletTx* copyTo = &mi->second;
3906 copyTo->mapValue = copyFrom->mapValue;
3907 copyTo->vOrderForm = copyFrom->vOrderForm;
3908 copyTo->nTimeReceived = copyFrom->nTimeReceived;
3909 copyTo->nTimeSmart = copyFrom->nTimeSmart;
3910 copyTo->fFromMe = copyFrom->fFromMe;
3911 copyTo->strFromAccount = copyFrom->strFromAccount;
3912 copyTo->nOrderPos = copyFrom->nOrderPos;
3913 walletdb.WriteTx(*copyTo);
3918 walletInstance->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
3921 LOCK(walletInstance->cs_wallet);
3922 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
3923 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
3924 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
3927 return walletInstance;
3930 bool CWallet::InitLoadWallet()
3932 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
3933 LogPrintf("Wallet disabled!\n");
3934 return true;
3937 for (const std::string& walletFile : gArgs.GetArgs("-wallet")) {
3938 CWallet * const pwallet = CreateWalletFromFile(walletFile);
3939 if (!pwallet) {
3940 return false;
3942 vpwallets.push_back(pwallet);
3945 return true;
3948 std::atomic<bool> CWallet::fFlushScheduled(false);
3950 void CWallet::postInitProcess(CScheduler& scheduler)
3952 // Add wallet transactions that aren't already in a block to mempool
3953 // Do this here as mempool requires genesis block to be loaded
3954 ReacceptWalletTransactions();
3956 // Run a thread to flush wallet periodically
3957 if (!CWallet::fFlushScheduled.exchange(true)) {
3958 scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
3962 bool CWallet::ParameterInteraction()
3964 SoftSetArg("-wallet", DEFAULT_WALLET_DAT);
3965 const bool is_multiwallet = gArgs.GetArgs("-wallet").size() > 1;
3967 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
3968 return true;
3970 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && SoftSetBoolArg("-walletbroadcast", false)) {
3971 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
3974 if (GetBoolArg("-salvagewallet", false) && SoftSetBoolArg("-rescan", true)) {
3975 if (is_multiwallet) {
3976 return InitError(strprintf("%s is only allowed with a single wallet file", "-salvagewallet"));
3978 // Rewrite just private keys: rescan to find transactions
3979 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
3982 // -zapwallettx implies a rescan
3983 if (GetBoolArg("-zapwallettxes", false) && SoftSetBoolArg("-rescan", true)) {
3984 if (is_multiwallet) {
3985 return InitError(strprintf("%s is only allowed with a single wallet file", "-zapwallettxes"));
3987 LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
3990 if (is_multiwallet) {
3991 if (GetBoolArg("-upgradewallet", false)) {
3992 return InitError(strprintf("%s is only allowed with a single wallet file", "-upgradewallet"));
3996 if (GetBoolArg("-sysperms", false))
3997 return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
3998 if (GetArg("-prune", 0) && GetBoolArg("-rescan", false))
3999 return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
4001 if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB)
4002 InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
4003 _("The wallet will avoid paying less than the minimum relay fee."));
4005 if (IsArgSet("-mintxfee"))
4007 CAmount n = 0;
4008 if (!ParseMoney(GetArg("-mintxfee", ""), n) || 0 == n)
4009 return InitError(AmountErrMsg("mintxfee", GetArg("-mintxfee", "")));
4010 if (n > HIGH_TX_FEE_PER_KB)
4011 InitWarning(AmountHighWarn("-mintxfee") + " " +
4012 _("This is the minimum transaction fee you pay on every transaction."));
4013 CWallet::minTxFee = CFeeRate(n);
4015 if (IsArgSet("-fallbackfee"))
4017 CAmount nFeePerK = 0;
4018 if (!ParseMoney(GetArg("-fallbackfee", ""), nFeePerK))
4019 return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), GetArg("-fallbackfee", "")));
4020 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4021 InitWarning(AmountHighWarn("-fallbackfee") + " " +
4022 _("This is the transaction fee you may pay when fee estimates are not available."));
4023 CWallet::fallbackFee = CFeeRate(nFeePerK);
4025 if (IsArgSet("-paytxfee"))
4027 CAmount nFeePerK = 0;
4028 if (!ParseMoney(GetArg("-paytxfee", ""), nFeePerK))
4029 return InitError(AmountErrMsg("paytxfee", GetArg("-paytxfee", "")));
4030 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4031 InitWarning(AmountHighWarn("-paytxfee") + " " +
4032 _("This is the transaction fee you will pay if you send a transaction."));
4034 payTxFee = CFeeRate(nFeePerK, 1000);
4035 if (payTxFee < ::minRelayTxFee)
4037 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
4038 GetArg("-paytxfee", ""), ::minRelayTxFee.ToString()));
4041 if (IsArgSet("-maxtxfee"))
4043 CAmount nMaxFee = 0;
4044 if (!ParseMoney(GetArg("-maxtxfee", ""), nMaxFee))
4045 return InitError(AmountErrMsg("maxtxfee", GetArg("-maxtxfee", "")));
4046 if (nMaxFee > HIGH_MAX_TX_FEE)
4047 InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
4048 maxTxFee = nMaxFee;
4049 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
4051 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
4052 GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString()));
4055 nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
4056 bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
4057 fWalletRbf = GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
4059 return true;
4062 bool CWallet::BackupWallet(const std::string& strDest)
4064 return dbw->Backup(strDest);
4067 CKeyPool::CKeyPool()
4069 nTime = GetTime();
4070 fInternal = false;
4073 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
4075 nTime = GetTime();
4076 vchPubKey = vchPubKeyIn;
4077 fInternal = internalIn;
4080 CWalletKey::CWalletKey(int64_t nExpires)
4082 nTimeCreated = (nExpires ? GetTime() : 0);
4083 nTimeExpires = nExpires;
4086 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
4088 // Update the tx's hashBlock
4089 hashBlock = pindex->GetBlockHash();
4091 // set the position of the transaction in the block
4092 nIndex = posInBlock;
4095 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4097 if (hashUnset())
4098 return 0;
4100 AssertLockHeld(cs_main);
4102 // Find the block it claims to be in
4103 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4104 if (mi == mapBlockIndex.end())
4105 return 0;
4106 CBlockIndex* pindex = (*mi).second;
4107 if (!pindex || !chainActive.Contains(pindex))
4108 return 0;
4110 pindexRet = pindex;
4111 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4114 int CMerkleTx::GetBlocksToMaturity() const
4116 if (!IsCoinBase())
4117 return 0;
4118 return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4122 bool CMerkleTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
4124 return ::AcceptToMemoryPool(mempool, state, tx, true, NULL, NULL, false, nAbsurdFee);