Use range-based for loops (C++11) when looping over vector elements
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blob993776252b0dd0ed142c8587c6eaf0619f0b6464
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 CWallet* pwalletMain = NULL;
39 /** Transaction fee set by the user */
40 CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE);
41 unsigned int nTxConfirmTarget = DEFAULT_TX_CONFIRM_TARGET;
42 bool bSpendZeroConfChange = DEFAULT_SPEND_ZEROCONF_CHANGE;
43 bool fWalletRbf = DEFAULT_WALLET_RBF;
45 const char * DEFAULT_WALLET_DAT = "wallet.dat";
46 const uint32_t BIP32_HARDENED_KEY_LIMIT = 0x80000000;
48 /**
49 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
50 * Override with -mintxfee
52 CFeeRate CWallet::minTxFee = CFeeRate(DEFAULT_TRANSACTION_MINFEE);
53 /**
54 * If fee estimation does not have enough data to provide estimates, use this fee instead.
55 * Has no effect if not using fee estimation
56 * Override with -fallbackfee
58 CFeeRate CWallet::fallbackFee = CFeeRate(DEFAULT_FALLBACK_FEE);
60 const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
62 /** @defgroup mapWallet
64 * @{
67 struct CompareValueOnly
69 bool operator()(const CInputCoin& t1,
70 const CInputCoin& t2) const
72 return t1.txout.nValue < t2.txout.nValue;
76 std::string COutput::ToString() const
78 return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->tx->vout[i].nValue));
81 const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const
83 LOCK(cs_wallet);
84 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
85 if (it == mapWallet.end())
86 return NULL;
87 return &(it->second);
90 CPubKey CWallet::GenerateNewKey(bool internal)
92 AssertLockHeld(cs_wallet); // mapKeyMetadata
93 bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
95 CKey secret;
97 // Create new metadata
98 int64_t nCreationTime = GetTime();
99 CKeyMetadata metadata(nCreationTime);
101 // use HD key derivation if HD was enabled during wallet creation
102 if (IsHDEnabled()) {
103 DeriveNewChildKey(metadata, secret, (CanSupportFeature(FEATURE_HD_SPLIT) ? internal : false));
104 } else {
105 secret.MakeNewKey(fCompressed);
108 // Compressed public keys were introduced in version 0.6.0
109 if (fCompressed)
110 SetMinVersion(FEATURE_COMPRPUBKEY);
112 CPubKey pubkey = secret.GetPubKey();
113 assert(secret.VerifyPubKey(pubkey));
115 mapKeyMetadata[pubkey.GetID()] = metadata;
116 UpdateTimeFirstKey(nCreationTime);
118 if (!AddKeyPubKey(secret, pubkey))
119 throw std::runtime_error(std::string(__func__) + ": AddKey failed");
120 return pubkey;
123 void CWallet::DeriveNewChildKey(CKeyMetadata& metadata, CKey& secret, bool internal)
125 // for now we use a fixed keypath scheme of m/0'/0'/k
126 CKey key; //master key seed (256bit)
127 CExtKey masterKey; //hd master key
128 CExtKey accountKey; //key at m/0'
129 CExtKey chainChildKey; //key at m/0'/0' (external) or m/0'/1' (internal)
130 CExtKey childKey; //key at m/0'/0'/<n>'
132 // try to get the master key
133 if (!GetKey(hdChain.masterKeyID, key))
134 throw std::runtime_error(std::string(__func__) + ": Master key not found");
136 masterKey.SetMaster(key.begin(), key.size());
138 // derive m/0'
139 // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
140 masterKey.Derive(accountKey, BIP32_HARDENED_KEY_LIMIT);
142 // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
143 assert(internal ? CanSupportFeature(FEATURE_HD_SPLIT) : true);
144 accountKey.Derive(chainChildKey, BIP32_HARDENED_KEY_LIMIT+(internal ? 1 : 0));
146 // derive child key at next index, skip keys already known to the wallet
147 do {
148 // always derive hardened keys
149 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
150 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
151 if (internal) {
152 chainChildKey.Derive(childKey, hdChain.nInternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
153 metadata.hdKeypath = "m/0'/1'/" + std::to_string(hdChain.nInternalChainCounter) + "'";
154 hdChain.nInternalChainCounter++;
156 else {
157 chainChildKey.Derive(childKey, hdChain.nExternalChainCounter | BIP32_HARDENED_KEY_LIMIT);
158 metadata.hdKeypath = "m/0'/0'/" + std::to_string(hdChain.nExternalChainCounter) + "'";
159 hdChain.nExternalChainCounter++;
161 } while (HaveKey(childKey.key.GetPubKey().GetID()));
162 secret = childKey.key;
163 metadata.hdMasterKeyID = hdChain.masterKeyID;
164 // update the chain model in the database
165 if (!CWalletDB(*dbw).WriteHDChain(hdChain))
166 throw std::runtime_error(std::string(__func__) + ": Writing HD chain model failed");
169 bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey &pubkey)
171 AssertLockHeld(cs_wallet); // mapKeyMetadata
172 if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey))
173 return false;
175 // check if we need to remove from watch-only
176 CScript script;
177 script = GetScriptForDestination(pubkey.GetID());
178 if (HaveWatchOnly(script))
179 RemoveWatchOnly(script);
180 script = GetScriptForRawPubKey(pubkey);
181 if (HaveWatchOnly(script))
182 RemoveWatchOnly(script);
184 if (!IsCrypted()) {
185 return CWalletDB(*dbw).WriteKey(pubkey,
186 secret.GetPrivKey(),
187 mapKeyMetadata[pubkey.GetID()]);
189 return true;
192 bool CWallet::AddCryptedKey(const CPubKey &vchPubKey,
193 const std::vector<unsigned char> &vchCryptedSecret)
195 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret))
196 return false;
198 LOCK(cs_wallet);
199 if (pwalletdbEncryption)
200 return pwalletdbEncryption->WriteCryptedKey(vchPubKey,
201 vchCryptedSecret,
202 mapKeyMetadata[vchPubKey.GetID()]);
203 else
204 return CWalletDB(*dbw).WriteCryptedKey(vchPubKey,
205 vchCryptedSecret,
206 mapKeyMetadata[vchPubKey.GetID()]);
208 return false;
211 bool CWallet::LoadKeyMetadata(const CTxDestination& keyID, const CKeyMetadata &meta)
213 AssertLockHeld(cs_wallet); // mapKeyMetadata
214 UpdateTimeFirstKey(meta.nCreateTime);
215 mapKeyMetadata[keyID] = meta;
216 return true;
219 bool CWallet::LoadCryptedKey(const CPubKey &vchPubKey, const std::vector<unsigned char> &vchCryptedSecret)
221 return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret);
224 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime)
226 AssertLockHeld(cs_wallet);
227 if (nCreateTime <= 1) {
228 // Cannot determine birthday information, so set the wallet birthday to
229 // the beginning of time.
230 nTimeFirstKey = 1;
231 } else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
232 nTimeFirstKey = nCreateTime;
236 bool CWallet::AddCScript(const CScript& redeemScript)
238 if (!CCryptoKeyStore::AddCScript(redeemScript))
239 return false;
240 return CWalletDB(*dbw).WriteCScript(Hash160(redeemScript), redeemScript);
243 bool CWallet::LoadCScript(const CScript& redeemScript)
245 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
246 * that never can be redeemed. However, old wallets may still contain
247 * these. Do not add them to the wallet and warn. */
248 if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE)
250 std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString();
251 LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
252 __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
253 return true;
256 return CCryptoKeyStore::AddCScript(redeemScript);
259 bool CWallet::AddWatchOnly(const CScript& dest)
261 if (!CCryptoKeyStore::AddWatchOnly(dest))
262 return false;
263 const CKeyMetadata& meta = mapKeyMetadata[CScriptID(dest)];
264 UpdateTimeFirstKey(meta.nCreateTime);
265 NotifyWatchonlyChanged(true);
266 return CWalletDB(*dbw).WriteWatchOnly(dest, meta);
269 bool CWallet::AddWatchOnly(const CScript& dest, int64_t nCreateTime)
271 mapKeyMetadata[CScriptID(dest)].nCreateTime = nCreateTime;
272 return AddWatchOnly(dest);
275 bool CWallet::RemoveWatchOnly(const CScript &dest)
277 AssertLockHeld(cs_wallet);
278 if (!CCryptoKeyStore::RemoveWatchOnly(dest))
279 return false;
280 if (!HaveWatchOnly())
281 NotifyWatchonlyChanged(false);
282 if (!CWalletDB(*dbw).EraseWatchOnly(dest))
283 return false;
285 return true;
288 bool CWallet::LoadWatchOnly(const CScript &dest)
290 return CCryptoKeyStore::AddWatchOnly(dest);
293 bool CWallet::Unlock(const SecureString& strWalletPassphrase)
295 CCrypter crypter;
296 CKeyingMaterial _vMasterKey;
299 LOCK(cs_wallet);
300 BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
302 if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
303 return false;
304 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
305 continue; // try another master key
306 if (CCryptoKeyStore::Unlock(_vMasterKey))
307 return true;
310 return false;
313 bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase)
315 bool fWasLocked = IsLocked();
318 LOCK(cs_wallet);
319 Lock();
321 CCrypter crypter;
322 CKeyingMaterial _vMasterKey;
323 BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys)
325 if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
326 return false;
327 if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
328 return false;
329 if (CCryptoKeyStore::Unlock(_vMasterKey))
331 int64_t nStartTime = GetTimeMillis();
332 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
333 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime)));
335 nStartTime = GetTimeMillis();
336 crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
337 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
339 if (pMasterKey.second.nDeriveIterations < 25000)
340 pMasterKey.second.nDeriveIterations = 25000;
342 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
344 if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
345 return false;
346 if (!crypter.Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
347 return false;
348 CWalletDB(*dbw).WriteMasterKey(pMasterKey.first, pMasterKey.second);
349 if (fWasLocked)
350 Lock();
351 return true;
356 return false;
359 void CWallet::SetBestChain(const CBlockLocator& loc)
361 CWalletDB walletdb(*dbw);
362 walletdb.WriteBestBlock(loc);
365 bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit)
367 LOCK(cs_wallet); // nWalletVersion
368 if (nWalletVersion >= nVersion)
369 return true;
371 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
372 if (fExplicit && nVersion > nWalletMaxVersion)
373 nVersion = FEATURE_LATEST;
375 nWalletVersion = nVersion;
377 if (nVersion > nWalletMaxVersion)
378 nWalletMaxVersion = nVersion;
381 CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(*dbw);
382 if (nWalletVersion > 40000)
383 pwalletdb->WriteMinVersion(nWalletVersion);
384 if (!pwalletdbIn)
385 delete pwalletdb;
388 return true;
391 bool CWallet::SetMaxVersion(int nVersion)
393 LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion
394 // cannot downgrade below current version
395 if (nWalletVersion > nVersion)
396 return false;
398 nWalletMaxVersion = nVersion;
400 return true;
403 std::set<uint256> CWallet::GetConflicts(const uint256& txid) const
405 std::set<uint256> result;
406 AssertLockHeld(cs_wallet);
408 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
409 if (it == mapWallet.end())
410 return result;
411 const CWalletTx& wtx = it->second;
413 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
415 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
417 if (mapTxSpends.count(txin.prevout) <= 1)
418 continue; // No conflict if zero or one spends
419 range = mapTxSpends.equal_range(txin.prevout);
420 for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
421 result.insert(_it->second);
423 return result;
426 bool CWallet::HasWalletSpend(const uint256& txid) const
428 AssertLockHeld(cs_wallet);
429 auto iter = mapTxSpends.lower_bound(COutPoint(txid, 0));
430 return (iter != mapTxSpends.end() && iter->first.hash == txid);
433 void CWallet::Flush(bool shutdown)
435 dbw->Flush(shutdown);
438 bool CWallet::Verify()
440 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
441 return true;
443 uiInterface.InitMessage(_("Verifying wallet..."));
444 std::string walletFile = GetArg("-wallet", DEFAULT_WALLET_DAT);
446 std::string strError;
447 if (!CWalletDB::VerifyEnvironment(walletFile, GetDataDir().string(), strError))
448 return InitError(strError);
450 if (GetBoolArg("-salvagewallet", false))
452 // Recover readable keypairs:
453 CWallet dummyWallet;
454 if (!CWalletDB::Recover(walletFile, (void *)&dummyWallet, CWalletDB::RecoverKeysOnlyFilter))
455 return false;
458 std::string strWarning;
459 bool dbV = CWalletDB::VerifyDatabaseFile(walletFile, GetDataDir().string(), strWarning, strError);
460 if (!strWarning.empty())
461 InitWarning(strWarning);
462 if (!dbV)
464 InitError(strError);
465 return false;
467 return true;
470 void CWallet::SyncMetaData(std::pair<TxSpends::iterator, TxSpends::iterator> range)
472 // We want all the wallet transactions in range to have the same metadata as
473 // the oldest (smallest nOrderPos).
474 // So: find smallest nOrderPos:
476 int nMinOrderPos = std::numeric_limits<int>::max();
477 const CWalletTx* copyFrom = NULL;
478 for (TxSpends::iterator it = range.first; it != range.second; ++it)
480 const uint256& hash = it->second;
481 int n = mapWallet[hash].nOrderPos;
482 if (n < nMinOrderPos)
484 nMinOrderPos = n;
485 copyFrom = &mapWallet[hash];
488 // Now copy data from copyFrom to rest:
489 for (TxSpends::iterator it = range.first; it != range.second; ++it)
491 const uint256& hash = it->second;
492 CWalletTx* copyTo = &mapWallet[hash];
493 if (copyFrom == copyTo) continue;
494 if (!copyFrom->IsEquivalentTo(*copyTo)) continue;
495 copyTo->mapValue = copyFrom->mapValue;
496 copyTo->vOrderForm = copyFrom->vOrderForm;
497 // fTimeReceivedIsTxTime not copied on purpose
498 // nTimeReceived not copied on purpose
499 copyTo->nTimeSmart = copyFrom->nTimeSmart;
500 copyTo->fFromMe = copyFrom->fFromMe;
501 copyTo->strFromAccount = copyFrom->strFromAccount;
502 // nOrderPos not copied on purpose
503 // cached members not copied on purpose
508 * Outpoint is spent if any non-conflicted transaction
509 * spends it:
511 bool CWallet::IsSpent(const uint256& hash, unsigned int n) const
513 const COutPoint outpoint(hash, n);
514 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
515 range = mapTxSpends.equal_range(outpoint);
517 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
519 const uint256& wtxid = it->second;
520 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
521 if (mit != mapWallet.end()) {
522 int depth = mit->second.GetDepthInMainChain();
523 if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
524 return true; // Spent
527 return false;
530 void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid)
532 mapTxSpends.insert(std::make_pair(outpoint, wtxid));
534 std::pair<TxSpends::iterator, TxSpends::iterator> range;
535 range = mapTxSpends.equal_range(outpoint);
536 SyncMetaData(range);
540 void CWallet::AddToSpends(const uint256& wtxid)
542 assert(mapWallet.count(wtxid));
543 CWalletTx& thisTx = mapWallet[wtxid];
544 if (thisTx.IsCoinBase()) // Coinbases don't spend anything!
545 return;
547 BOOST_FOREACH(const CTxIn& txin, thisTx.tx->vin)
548 AddToSpends(txin.prevout, wtxid);
551 bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase)
553 if (IsCrypted())
554 return false;
556 CKeyingMaterial _vMasterKey;
558 _vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE);
559 GetStrongRandBytes(&_vMasterKey[0], WALLET_CRYPTO_KEY_SIZE);
561 CMasterKey kMasterKey;
563 kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE);
564 GetStrongRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE);
566 CCrypter crypter;
567 int64_t nStartTime = GetTimeMillis();
568 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod);
569 kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime));
571 nStartTime = GetTimeMillis();
572 crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod);
573 kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2;
575 if (kMasterKey.nDeriveIterations < 25000)
576 kMasterKey.nDeriveIterations = 25000;
578 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations);
580 if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod))
581 return false;
582 if (!crypter.Encrypt(_vMasterKey, kMasterKey.vchCryptedKey))
583 return false;
586 LOCK(cs_wallet);
587 mapMasterKeys[++nMasterKeyMaxID] = kMasterKey;
588 assert(!pwalletdbEncryption);
589 pwalletdbEncryption = new CWalletDB(*dbw);
590 if (!pwalletdbEncryption->TxnBegin()) {
591 delete pwalletdbEncryption;
592 pwalletdbEncryption = NULL;
593 return false;
595 pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey);
597 if (!EncryptKeys(_vMasterKey))
599 pwalletdbEncryption->TxnAbort();
600 delete pwalletdbEncryption;
601 // We now probably have half of our keys encrypted in memory, and half not...
602 // die and let the user reload the unencrypted wallet.
603 assert(false);
606 // Encryption was introduced in version 0.4.0
607 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true);
609 if (!pwalletdbEncryption->TxnCommit()) {
610 delete pwalletdbEncryption;
611 // We now have keys encrypted in memory, but not on disk...
612 // die to avoid confusion and let the user reload the unencrypted wallet.
613 assert(false);
616 delete pwalletdbEncryption;
617 pwalletdbEncryption = NULL;
619 Lock();
620 Unlock(strWalletPassphrase);
622 // if we are using HD, replace the HD master key (seed) with a new one
623 if (IsHDEnabled()) {
624 if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
625 return false;
629 NewKeyPool();
630 Lock();
632 // Need to completely rewrite the wallet file; if we don't, bdb might keep
633 // bits of the unencrypted private key in slack space in the database file.
634 dbw->Rewrite();
637 NotifyStatusChanged(this);
639 return true;
642 DBErrors CWallet::ReorderTransactions()
644 LOCK(cs_wallet);
645 CWalletDB walletdb(*dbw);
647 // Old wallets didn't have any defined order for transactions
648 // Probably a bad idea to change the output of this
650 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
651 typedef std::pair<CWalletTx*, CAccountingEntry*> TxPair;
652 typedef std::multimap<int64_t, TxPair > TxItems;
653 TxItems txByTime;
655 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
657 CWalletTx* wtx = &((*it).second);
658 txByTime.insert(std::make_pair(wtx->nTimeReceived, TxPair(wtx, (CAccountingEntry*)0)));
660 std::list<CAccountingEntry> acentries;
661 walletdb.ListAccountCreditDebit("", acentries);
662 BOOST_FOREACH(CAccountingEntry& entry, acentries)
664 txByTime.insert(std::make_pair(entry.nTime, TxPair((CWalletTx*)0, &entry)));
667 nOrderPosNext = 0;
668 std::vector<int64_t> nOrderPosOffsets;
669 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
671 CWalletTx *const pwtx = (*it).second.first;
672 CAccountingEntry *const pacentry = (*it).second.second;
673 int64_t& nOrderPos = (pwtx != 0) ? pwtx->nOrderPos : pacentry->nOrderPos;
675 if (nOrderPos == -1)
677 nOrderPos = nOrderPosNext++;
678 nOrderPosOffsets.push_back(nOrderPos);
680 if (pwtx)
682 if (!walletdb.WriteTx(*pwtx))
683 return DB_LOAD_FAIL;
685 else
686 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
687 return DB_LOAD_FAIL;
689 else
691 int64_t nOrderPosOff = 0;
692 BOOST_FOREACH(const int64_t& nOffsetStart, nOrderPosOffsets)
694 if (nOrderPos >= nOffsetStart)
695 ++nOrderPosOff;
697 nOrderPos += nOrderPosOff;
698 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
700 if (!nOrderPosOff)
701 continue;
703 // Since we're changing the order, write it back
704 if (pwtx)
706 if (!walletdb.WriteTx(*pwtx))
707 return DB_LOAD_FAIL;
709 else
710 if (!walletdb.WriteAccountingEntry(pacentry->nEntryNo, *pacentry))
711 return DB_LOAD_FAIL;
714 walletdb.WriteOrderPosNext(nOrderPosNext);
716 return DB_LOAD_OK;
719 int64_t CWallet::IncOrderPosNext(CWalletDB *pwalletdb)
721 AssertLockHeld(cs_wallet); // nOrderPosNext
722 int64_t nRet = nOrderPosNext++;
723 if (pwalletdb) {
724 pwalletdb->WriteOrderPosNext(nOrderPosNext);
725 } else {
726 CWalletDB(*dbw).WriteOrderPosNext(nOrderPosNext);
728 return nRet;
731 bool CWallet::AccountMove(std::string strFrom, std::string strTo, CAmount nAmount, std::string strComment)
733 CWalletDB walletdb(*dbw);
734 if (!walletdb.TxnBegin())
735 return false;
737 int64_t nNow = GetAdjustedTime();
739 // Debit
740 CAccountingEntry debit;
741 debit.nOrderPos = IncOrderPosNext(&walletdb);
742 debit.strAccount = strFrom;
743 debit.nCreditDebit = -nAmount;
744 debit.nTime = nNow;
745 debit.strOtherAccount = strTo;
746 debit.strComment = strComment;
747 AddAccountingEntry(debit, &walletdb);
749 // Credit
750 CAccountingEntry credit;
751 credit.nOrderPos = IncOrderPosNext(&walletdb);
752 credit.strAccount = strTo;
753 credit.nCreditDebit = nAmount;
754 credit.nTime = nNow;
755 credit.strOtherAccount = strFrom;
756 credit.strComment = strComment;
757 AddAccountingEntry(credit, &walletdb);
759 if (!walletdb.TxnCommit())
760 return false;
762 return true;
765 bool CWallet::GetAccountPubkey(CPubKey &pubKey, std::string strAccount, bool bForceNew)
767 CWalletDB walletdb(*dbw);
769 CAccount account;
770 walletdb.ReadAccount(strAccount, account);
772 if (!bForceNew) {
773 if (!account.vchPubKey.IsValid())
774 bForceNew = true;
775 else {
776 // Check if the current key has been used
777 CScript scriptPubKey = GetScriptForDestination(account.vchPubKey.GetID());
778 for (std::map<uint256, CWalletTx>::iterator it = mapWallet.begin();
779 it != mapWallet.end() && account.vchPubKey.IsValid();
780 ++it)
781 BOOST_FOREACH(const CTxOut& txout, (*it).second.tx->vout)
782 if (txout.scriptPubKey == scriptPubKey) {
783 bForceNew = true;
784 break;
789 // Generate a new key
790 if (bForceNew) {
791 if (!GetKeyFromPool(account.vchPubKey, false))
792 return false;
794 SetAddressBook(account.vchPubKey.GetID(), strAccount, "receive");
795 walletdb.WriteAccount(strAccount, account);
798 pubKey = account.vchPubKey;
800 return true;
803 void CWallet::MarkDirty()
806 LOCK(cs_wallet);
807 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
808 item.second.MarkDirty();
812 bool CWallet::MarkReplaced(const uint256& originalHash, const uint256& newHash)
814 LOCK(cs_wallet);
816 auto mi = mapWallet.find(originalHash);
818 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
819 assert(mi != mapWallet.end());
821 CWalletTx& wtx = (*mi).second;
823 // Ensure for now that we're not overwriting data
824 assert(wtx.mapValue.count("replaced_by_txid") == 0);
826 wtx.mapValue["replaced_by_txid"] = newHash.ToString();
828 CWalletDB walletdb(*dbw, "r+");
830 bool success = true;
831 if (!walletdb.WriteTx(wtx)) {
832 LogPrintf("%s: Updating walletdb tx %s failed", __func__, wtx.GetHash().ToString());
833 success = false;
836 NotifyTransactionChanged(this, originalHash, CT_UPDATED);
838 return success;
841 bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFlushOnClose)
843 LOCK(cs_wallet);
845 CWalletDB walletdb(*dbw, "r+", fFlushOnClose);
847 uint256 hash = wtxIn.GetHash();
849 // Inserts only if not already there, returns tx inserted or tx found
850 std::pair<std::map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(std::make_pair(hash, wtxIn));
851 CWalletTx& wtx = (*ret.first).second;
852 wtx.BindWallet(this);
853 bool fInsertedNew = ret.second;
854 if (fInsertedNew)
856 wtx.nTimeReceived = GetAdjustedTime();
857 wtx.nOrderPos = IncOrderPosNext(&walletdb);
858 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
859 wtx.nTimeSmart = ComputeTimeSmart(wtx);
860 AddToSpends(hash);
863 bool fUpdated = false;
864 if (!fInsertedNew)
866 // Merge
867 if (!wtxIn.hashUnset() && wtxIn.hashBlock != wtx.hashBlock)
869 wtx.hashBlock = wtxIn.hashBlock;
870 fUpdated = true;
872 // If no longer abandoned, update
873 if (wtxIn.hashBlock.IsNull() && wtx.isAbandoned())
875 wtx.hashBlock = wtxIn.hashBlock;
876 fUpdated = true;
878 if (wtxIn.nIndex != -1 && (wtxIn.nIndex != wtx.nIndex))
880 wtx.nIndex = wtxIn.nIndex;
881 fUpdated = true;
883 if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe)
885 wtx.fFromMe = wtxIn.fFromMe;
886 fUpdated = true;
890 //// debug print
891 LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : ""));
893 // Write to disk
894 if (fInsertedNew || fUpdated)
895 if (!walletdb.WriteTx(wtx))
896 return false;
898 // Break debit/credit balance caches:
899 wtx.MarkDirty();
901 // Notify UI of new or updated transaction
902 NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED);
904 // notify an external script when a wallet transaction comes in or is updated
905 std::string strCmd = GetArg("-walletnotify", "");
907 if ( !strCmd.empty())
909 boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex());
910 boost::thread t(runCommand, strCmd); // thread runs free
913 return true;
916 bool CWallet::LoadToWallet(const CWalletTx& wtxIn)
918 uint256 hash = wtxIn.GetHash();
920 mapWallet[hash] = wtxIn;
921 CWalletTx& wtx = mapWallet[hash];
922 wtx.BindWallet(this);
923 wtxOrdered.insert(std::make_pair(wtx.nOrderPos, TxPair(&wtx, (CAccountingEntry*)0)));
924 AddToSpends(hash);
925 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin) {
926 if (mapWallet.count(txin.prevout.hash)) {
927 CWalletTx& prevtx = mapWallet[txin.prevout.hash];
928 if (prevtx.nIndex == -1 && !prevtx.hashUnset()) {
929 MarkConflicted(prevtx.hashBlock, wtx.GetHash());
934 return true;
938 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
939 * be set when the transaction was known to be included in a block. When
940 * pIndex == NULL, then wallet state is not updated in AddToWallet, but
941 * notifications happen and cached balances are marked dirty.
943 * If fUpdate is true, existing transactions will be updated.
944 * TODO: One exception to this is that the abandoned state is cleared under the
945 * assumption that any further notification of a transaction that was considered
946 * abandoned is an indication that it is not safe to be considered abandoned.
947 * Abandoned state should probably be more carefully tracked via different
948 * posInBlock signals or by checking mempool presence when necessary.
950 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef& ptx, const CBlockIndex* pIndex, int posInBlock, bool fUpdate)
952 const CTransaction& tx = *ptx;
954 AssertLockHeld(cs_wallet);
956 if (pIndex != NULL) {
957 BOOST_FOREACH(const CTxIn& txin, tx.vin) {
958 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.prevout);
959 while (range.first != range.second) {
960 if (range.first->second != tx.GetHash()) {
961 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);
962 MarkConflicted(pIndex->GetBlockHash(), range.first->second);
964 range.first++;
969 bool fExisted = mapWallet.count(tx.GetHash()) != 0;
970 if (fExisted && !fUpdate) return false;
971 if (fExisted || IsMine(tx) || IsFromMe(tx))
973 CWalletTx wtx(this, ptx);
975 // Get merkle branch if transaction was found in a block
976 if (pIndex != NULL)
977 wtx.SetMerkleBranch(pIndex, posInBlock);
979 return AddToWallet(wtx, false);
982 return false;
985 bool CWallet::AbandonTransaction(const uint256& hashTx)
987 LOCK2(cs_main, cs_wallet);
989 CWalletDB walletdb(*dbw, "r+");
991 std::set<uint256> todo;
992 std::set<uint256> done;
994 // Can't mark abandoned if confirmed or in mempool
995 assert(mapWallet.count(hashTx));
996 CWalletTx& origtx = mapWallet[hashTx];
997 if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
998 return false;
1001 todo.insert(hashTx);
1003 while (!todo.empty()) {
1004 uint256 now = *todo.begin();
1005 todo.erase(now);
1006 done.insert(now);
1007 assert(mapWallet.count(now));
1008 CWalletTx& wtx = mapWallet[now];
1009 int currentconfirm = wtx.GetDepthInMainChain();
1010 // If the orig tx was not in block, none of its spends can be
1011 assert(currentconfirm <= 0);
1012 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1013 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1014 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1015 assert(!wtx.InMempool());
1016 wtx.nIndex = -1;
1017 wtx.setAbandoned();
1018 wtx.MarkDirty();
1019 walletdb.WriteTx(wtx);
1020 NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1021 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1022 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1023 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1024 if (!done.count(iter->second)) {
1025 todo.insert(iter->second);
1027 iter++;
1029 // If a transaction changes 'conflicted' state, that changes the balance
1030 // available of the outputs it spends. So force those to be recomputed
1031 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
1033 if (mapWallet.count(txin.prevout.hash))
1034 mapWallet[txin.prevout.hash].MarkDirty();
1039 return true;
1042 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1044 LOCK2(cs_main, cs_wallet);
1046 int conflictconfirms = 0;
1047 if (mapBlockIndex.count(hashBlock)) {
1048 CBlockIndex* pindex = mapBlockIndex[hashBlock];
1049 if (chainActive.Contains(pindex)) {
1050 conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1053 // If number of conflict confirms cannot be determined, this means
1054 // that the block is still unknown or not yet part of the main chain,
1055 // for example when loading the wallet during a reindex. Do nothing in that
1056 // case.
1057 if (conflictconfirms >= 0)
1058 return;
1060 // Do not flush the wallet here for performance reasons
1061 CWalletDB walletdb(*dbw, "r+", false);
1063 std::set<uint256> todo;
1064 std::set<uint256> done;
1066 todo.insert(hashTx);
1068 while (!todo.empty()) {
1069 uint256 now = *todo.begin();
1070 todo.erase(now);
1071 done.insert(now);
1072 assert(mapWallet.count(now));
1073 CWalletTx& wtx = mapWallet[now];
1074 int currentconfirm = wtx.GetDepthInMainChain();
1075 if (conflictconfirms < currentconfirm) {
1076 // Block is 'more conflicted' than current confirm; update.
1077 // Mark transaction as conflicted with this block.
1078 wtx.nIndex = -1;
1079 wtx.hashBlock = hashBlock;
1080 wtx.MarkDirty();
1081 walletdb.WriteTx(wtx);
1082 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1083 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1084 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1085 if (!done.count(iter->second)) {
1086 todo.insert(iter->second);
1088 iter++;
1090 // If a transaction changes 'conflicted' state, that changes the balance
1091 // available of the outputs it spends. So force those to be recomputed
1092 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
1094 if (mapWallet.count(txin.prevout.hash))
1095 mapWallet[txin.prevout.hash].MarkDirty();
1101 void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
1102 const CTransaction& tx = *ptx;
1104 if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
1105 return; // Not one of ours
1107 // If a transaction changes 'conflicted' state, that changes the balance
1108 // available of the outputs it spends. So force those to be
1109 // recomputed, also:
1110 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1112 if (mapWallet.count(txin.prevout.hash))
1113 mapWallet[txin.prevout.hash].MarkDirty();
1117 void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx) {
1118 LOCK2(cs_main, cs_wallet);
1119 SyncTransaction(ptx);
1122 void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
1123 LOCK2(cs_main, cs_wallet);
1124 // TODO: Temporarily ensure that mempool removals are notified before
1125 // connected transactions. This shouldn't matter, but the abandoned
1126 // state of transactions in our wallet is currently cleared when we
1127 // receive another notification and there is a race condition where
1128 // notification of a connected conflict might cause an outside process
1129 // to abandon a transaction and then have it inadvertently cleared by
1130 // the notification that the conflicted transaction was evicted.
1132 for (const CTransactionRef& ptx : vtxConflicted) {
1133 SyncTransaction(ptx);
1135 for (size_t i = 0; i < pblock->vtx.size(); i++) {
1136 SyncTransaction(pblock->vtx[i], pindex, i);
1140 void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
1141 LOCK2(cs_main, cs_wallet);
1143 for (const CTransactionRef& ptx : pblock->vtx) {
1144 SyncTransaction(ptx);
1150 isminetype CWallet::IsMine(const CTxIn &txin) const
1153 LOCK(cs_wallet);
1154 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1155 if (mi != mapWallet.end())
1157 const CWalletTx& prev = (*mi).second;
1158 if (txin.prevout.n < prev.tx->vout.size())
1159 return IsMine(prev.tx->vout[txin.prevout.n]);
1162 return ISMINE_NO;
1165 // Note that this function doesn't distinguish between a 0-valued input,
1166 // and a not-"is mine" (according to the filter) input.
1167 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1170 LOCK(cs_wallet);
1171 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1172 if (mi != mapWallet.end())
1174 const CWalletTx& prev = (*mi).second;
1175 if (txin.prevout.n < prev.tx->vout.size())
1176 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1177 return prev.tx->vout[txin.prevout.n].nValue;
1180 return 0;
1183 isminetype CWallet::IsMine(const CTxOut& txout) const
1185 return ::IsMine(*this, txout.scriptPubKey);
1188 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1190 if (!MoneyRange(txout.nValue))
1191 throw std::runtime_error(std::string(__func__) + ": value out of range");
1192 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1195 bool CWallet::IsChange(const CTxOut& txout) const
1197 // TODO: fix handling of 'change' outputs. The assumption is that any
1198 // payment to a script that is ours, but is not in the address book
1199 // is change. That assumption is likely to break when we implement multisignature
1200 // wallets that return change back into a multi-signature-protected address;
1201 // a better way of identifying which outputs are 'the send' and which are
1202 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1203 // which output, if any, was change).
1204 if (::IsMine(*this, txout.scriptPubKey))
1206 CTxDestination address;
1207 if (!ExtractDestination(txout.scriptPubKey, address))
1208 return true;
1210 LOCK(cs_wallet);
1211 if (!mapAddressBook.count(address))
1212 return true;
1214 return false;
1217 CAmount CWallet::GetChange(const CTxOut& txout) const
1219 if (!MoneyRange(txout.nValue))
1220 throw std::runtime_error(std::string(__func__) + ": value out of range");
1221 return (IsChange(txout) ? txout.nValue : 0);
1224 bool CWallet::IsMine(const CTransaction& tx) const
1226 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1227 if (IsMine(txout))
1228 return true;
1229 return false;
1232 bool CWallet::IsFromMe(const CTransaction& tx) const
1234 return (GetDebit(tx, ISMINE_ALL) > 0);
1237 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1239 CAmount nDebit = 0;
1240 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1242 nDebit += GetDebit(txin, filter);
1243 if (!MoneyRange(nDebit))
1244 throw std::runtime_error(std::string(__func__) + ": value out of range");
1246 return nDebit;
1249 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1251 LOCK(cs_wallet);
1253 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1255 auto mi = mapWallet.find(txin.prevout.hash);
1256 if (mi == mapWallet.end())
1257 return false; // any unknown inputs can't be from us
1259 const CWalletTx& prev = (*mi).second;
1261 if (txin.prevout.n >= prev.tx->vout.size())
1262 return false; // invalid input!
1264 if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1265 return false;
1267 return true;
1270 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1272 CAmount nCredit = 0;
1273 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1275 nCredit += GetCredit(txout, filter);
1276 if (!MoneyRange(nCredit))
1277 throw std::runtime_error(std::string(__func__) + ": value out of range");
1279 return nCredit;
1282 CAmount CWallet::GetChange(const CTransaction& tx) const
1284 CAmount nChange = 0;
1285 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1287 nChange += GetChange(txout);
1288 if (!MoneyRange(nChange))
1289 throw std::runtime_error(std::string(__func__) + ": value out of range");
1291 return nChange;
1294 CPubKey CWallet::GenerateNewHDMasterKey()
1296 CKey key;
1297 key.MakeNewKey(true);
1299 int64_t nCreationTime = GetTime();
1300 CKeyMetadata metadata(nCreationTime);
1302 // calculate the pubkey
1303 CPubKey pubkey = key.GetPubKey();
1304 assert(key.VerifyPubKey(pubkey));
1306 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1307 metadata.hdKeypath = "m";
1308 metadata.hdMasterKeyID = pubkey.GetID();
1311 LOCK(cs_wallet);
1313 // mem store the metadata
1314 mapKeyMetadata[pubkey.GetID()] = metadata;
1316 // write the key&metadata to the database
1317 if (!AddKeyPubKey(key, pubkey))
1318 throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1321 return pubkey;
1324 bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
1326 LOCK(cs_wallet);
1327 // store the keyid (hash160) together with
1328 // the child index counter in the database
1329 // as a hdchain object
1330 CHDChain newHdChain;
1331 newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1332 newHdChain.masterKeyID = pubkey.GetID();
1333 SetHDChain(newHdChain, false);
1335 return true;
1338 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1340 LOCK(cs_wallet);
1341 if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
1342 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1344 hdChain = chain;
1345 return true;
1348 bool CWallet::IsHDEnabled() const
1350 return !hdChain.masterKeyID.IsNull();
1353 int64_t CWalletTx::GetTxTime() const
1355 int64_t n = nTimeSmart;
1356 return n ? n : nTimeReceived;
1359 int CWalletTx::GetRequestCount() const
1361 // Returns -1 if it wasn't being tracked
1362 int nRequests = -1;
1364 LOCK(pwallet->cs_wallet);
1365 if (IsCoinBase())
1367 // Generated block
1368 if (!hashUnset())
1370 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1371 if (mi != pwallet->mapRequestCount.end())
1372 nRequests = (*mi).second;
1375 else
1377 // Did anyone request this transaction?
1378 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1379 if (mi != pwallet->mapRequestCount.end())
1381 nRequests = (*mi).second;
1383 // How about the block it's in?
1384 if (nRequests == 0 && !hashUnset())
1386 std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1387 if (_mi != pwallet->mapRequestCount.end())
1388 nRequests = (*_mi).second;
1389 else
1390 nRequests = 1; // If it's in someone else's block it must have got out
1395 return nRequests;
1398 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1399 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1401 nFee = 0;
1402 listReceived.clear();
1403 listSent.clear();
1404 strSentAccount = strFromAccount;
1406 // Compute fee:
1407 CAmount nDebit = GetDebit(filter);
1408 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1410 CAmount nValueOut = tx->GetValueOut();
1411 nFee = nDebit - nValueOut;
1414 // Sent/received.
1415 for (unsigned int i = 0; i < tx->vout.size(); ++i)
1417 const CTxOut& txout = tx->vout[i];
1418 isminetype fIsMine = pwallet->IsMine(txout);
1419 // Only need to handle txouts if AT LEAST one of these is true:
1420 // 1) they debit from us (sent)
1421 // 2) the output is to us (received)
1422 if (nDebit > 0)
1424 // Don't report 'change' txouts
1425 if (pwallet->IsChange(txout))
1426 continue;
1428 else if (!(fIsMine & filter))
1429 continue;
1431 // In either case, we need to get the destination address
1432 CTxDestination address;
1434 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1436 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1437 this->GetHash().ToString());
1438 address = CNoDestination();
1441 COutputEntry output = {address, txout.nValue, (int)i};
1443 // If we are debited by the transaction, add the output as a "sent" entry
1444 if (nDebit > 0)
1445 listSent.push_back(output);
1447 // If we are receiving the output, add it as a "received" entry
1448 if (fIsMine & filter)
1449 listReceived.push_back(output);
1455 * Scan the block chain (starting in pindexStart) for transactions
1456 * from or to us. If fUpdate is true, found transactions that already
1457 * exist in the wallet will be updated.
1459 * Returns pointer to the first block in the last contiguous range that was
1460 * successfully scanned or elided (elided if pIndexStart points at a block
1461 * before CWallet::nTimeFirstKey). Returns null if there is no such range, or
1462 * the range doesn't include chainActive.Tip().
1464 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1466 int64_t nNow = GetTime();
1467 const CChainParams& chainParams = Params();
1469 CBlockIndex* pindex = pindexStart;
1470 CBlockIndex* ret = pindexStart;
1472 LOCK2(cs_main, cs_wallet);
1473 fAbortRescan = false;
1474 fScanningWallet = true;
1476 // no need to read and scan block, if block was created before
1477 // our wallet birthday (as adjusted for block time variability)
1478 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - TIMESTAMP_WINDOW)))
1479 pindex = chainActive.Next(pindex);
1481 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1482 double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
1483 double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
1484 while (pindex && !fAbortRescan)
1486 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1487 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1488 if (GetTime() >= nNow + 60) {
1489 nNow = GetTime();
1490 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1493 CBlock block;
1494 if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
1495 for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1496 AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
1498 if (!ret) {
1499 ret = pindex;
1501 } else {
1502 ret = nullptr;
1504 pindex = chainActive.Next(pindex);
1506 if (pindex && fAbortRescan) {
1507 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1509 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1511 fScanningWallet = false;
1513 return ret;
1516 void CWallet::ReacceptWalletTransactions()
1518 // If transactions aren't being broadcasted, don't let them into local mempool either
1519 if (!fBroadcastTransactions)
1520 return;
1521 LOCK2(cs_main, cs_wallet);
1522 std::map<int64_t, CWalletTx*> mapSorted;
1524 // Sort pending wallet transactions based on their initial wallet insertion order
1525 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1527 const uint256& wtxid = item.first;
1528 CWalletTx& wtx = item.second;
1529 assert(wtx.GetHash() == wtxid);
1531 int nDepth = wtx.GetDepthInMainChain();
1533 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1534 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1538 // Try to add wallet transactions to memory pool
1539 BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
1541 CWalletTx& wtx = *(item.second);
1543 LOCK(mempool.cs);
1544 CValidationState state;
1545 wtx.AcceptToMemoryPool(maxTxFee, state);
1549 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1551 assert(pwallet->GetBroadcastTransactions());
1552 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1554 CValidationState state;
1555 /* GetDepthInMainChain already catches known conflicts. */
1556 if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1557 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1558 if (connman) {
1559 CInv inv(MSG_TX, GetHash());
1560 connman->ForEachNode([&inv](CNode* pnode)
1562 pnode->PushInventory(inv);
1564 return true;
1568 return false;
1571 std::set<uint256> CWalletTx::GetConflicts() const
1573 std::set<uint256> result;
1574 if (pwallet != NULL)
1576 uint256 myHash = GetHash();
1577 result = pwallet->GetConflicts(myHash);
1578 result.erase(myHash);
1580 return result;
1583 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1585 if (tx->vin.empty())
1586 return 0;
1588 CAmount debit = 0;
1589 if(filter & ISMINE_SPENDABLE)
1591 if (fDebitCached)
1592 debit += nDebitCached;
1593 else
1595 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1596 fDebitCached = true;
1597 debit += nDebitCached;
1600 if(filter & ISMINE_WATCH_ONLY)
1602 if(fWatchDebitCached)
1603 debit += nWatchDebitCached;
1604 else
1606 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1607 fWatchDebitCached = true;
1608 debit += nWatchDebitCached;
1611 return debit;
1614 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1616 // Must wait until coinbase is safely deep enough in the chain before valuing it
1617 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1618 return 0;
1620 CAmount credit = 0;
1621 if (filter & ISMINE_SPENDABLE)
1623 // GetBalance can assume transactions in mapWallet won't change
1624 if (fCreditCached)
1625 credit += nCreditCached;
1626 else
1628 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1629 fCreditCached = true;
1630 credit += nCreditCached;
1633 if (filter & ISMINE_WATCH_ONLY)
1635 if (fWatchCreditCached)
1636 credit += nWatchCreditCached;
1637 else
1639 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1640 fWatchCreditCached = true;
1641 credit += nWatchCreditCached;
1644 return credit;
1647 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1649 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1651 if (fUseCache && fImmatureCreditCached)
1652 return nImmatureCreditCached;
1653 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1654 fImmatureCreditCached = true;
1655 return nImmatureCreditCached;
1658 return 0;
1661 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1663 if (pwallet == 0)
1664 return 0;
1666 // Must wait until coinbase is safely deep enough in the chain before valuing it
1667 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1668 return 0;
1670 if (fUseCache && fAvailableCreditCached)
1671 return nAvailableCreditCached;
1673 CAmount nCredit = 0;
1674 uint256 hashTx = GetHash();
1675 for (unsigned int i = 0; i < tx->vout.size(); i++)
1677 if (!pwallet->IsSpent(hashTx, i))
1679 const CTxOut &txout = tx->vout[i];
1680 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1681 if (!MoneyRange(nCredit))
1682 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1686 nAvailableCreditCached = nCredit;
1687 fAvailableCreditCached = true;
1688 return nCredit;
1691 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1693 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1695 if (fUseCache && fImmatureWatchCreditCached)
1696 return nImmatureWatchCreditCached;
1697 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1698 fImmatureWatchCreditCached = true;
1699 return nImmatureWatchCreditCached;
1702 return 0;
1705 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1707 if (pwallet == 0)
1708 return 0;
1710 // Must wait until coinbase is safely deep enough in the chain before valuing it
1711 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1712 return 0;
1714 if (fUseCache && fAvailableWatchCreditCached)
1715 return nAvailableWatchCreditCached;
1717 CAmount nCredit = 0;
1718 for (unsigned int i = 0; i < tx->vout.size(); i++)
1720 if (!pwallet->IsSpent(GetHash(), i))
1722 const CTxOut &txout = tx->vout[i];
1723 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1724 if (!MoneyRange(nCredit))
1725 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1729 nAvailableWatchCreditCached = nCredit;
1730 fAvailableWatchCreditCached = true;
1731 return nCredit;
1734 CAmount CWalletTx::GetChange() const
1736 if (fChangeCached)
1737 return nChangeCached;
1738 nChangeCached = pwallet->GetChange(*this);
1739 fChangeCached = true;
1740 return nChangeCached;
1743 bool CWalletTx::InMempool() const
1745 LOCK(mempool.cs);
1746 return mempool.exists(GetHash());
1749 bool CWalletTx::IsTrusted() const
1751 // Quick answer in most cases
1752 if (!CheckFinalTx(*this))
1753 return false;
1754 int nDepth = GetDepthInMainChain();
1755 if (nDepth >= 1)
1756 return true;
1757 if (nDepth < 0)
1758 return false;
1759 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1760 return false;
1762 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1763 if (!InMempool())
1764 return false;
1766 // Trusted if all inputs are from us and are in the mempool:
1767 BOOST_FOREACH(const CTxIn& txin, tx->vin)
1769 // Transactions not sent by us: not trusted
1770 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1771 if (parent == NULL)
1772 return false;
1773 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1774 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1775 return false;
1777 return true;
1780 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1782 CMutableTransaction tx1 = *this->tx;
1783 CMutableTransaction tx2 = *_tx.tx;
1784 for (auto& txin : tx1.vin) txin.scriptSig = CScript();
1785 for (auto& txin : tx2.vin) txin.scriptSig = CScript();
1786 return CTransaction(tx1) == CTransaction(tx2);
1789 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1791 std::vector<uint256> result;
1793 LOCK(cs_wallet);
1794 // Sort them in chronological order
1795 std::multimap<unsigned int, CWalletTx*> mapSorted;
1796 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1798 CWalletTx& wtx = item.second;
1799 // Don't rebroadcast if newer than nTime:
1800 if (wtx.nTimeReceived > nTime)
1801 continue;
1802 mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1804 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1806 CWalletTx& wtx = *item.second;
1807 if (wtx.RelayWalletTransaction(connman))
1808 result.push_back(wtx.GetHash());
1810 return result;
1813 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1815 // Do this infrequently and randomly to avoid giving away
1816 // that these are our transactions.
1817 if (GetTime() < nNextResend || !fBroadcastTransactions)
1818 return;
1819 bool fFirst = (nNextResend == 0);
1820 nNextResend = GetTime() + GetRand(30 * 60);
1821 if (fFirst)
1822 return;
1824 // Only do it if there's been a new block since last time
1825 if (nBestBlockTime < nLastResend)
1826 return;
1827 nLastResend = GetTime();
1829 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1830 // block was found:
1831 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
1832 if (!relayed.empty())
1833 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
1836 /** @} */ // end of mapWallet
1841 /** @defgroup Actions
1843 * @{
1847 CAmount CWallet::GetBalance() const
1849 CAmount nTotal = 0;
1851 LOCK2(cs_main, cs_wallet);
1852 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1854 const CWalletTx* pcoin = &(*it).second;
1855 if (pcoin->IsTrusted())
1856 nTotal += pcoin->GetAvailableCredit();
1860 return nTotal;
1863 CAmount CWallet::GetUnconfirmedBalance() const
1865 CAmount nTotal = 0;
1867 LOCK2(cs_main, cs_wallet);
1868 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1870 const CWalletTx* pcoin = &(*it).second;
1871 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1872 nTotal += pcoin->GetAvailableCredit();
1875 return nTotal;
1878 CAmount CWallet::GetImmatureBalance() const
1880 CAmount nTotal = 0;
1882 LOCK2(cs_main, cs_wallet);
1883 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1885 const CWalletTx* pcoin = &(*it).second;
1886 nTotal += pcoin->GetImmatureCredit();
1889 return nTotal;
1892 CAmount CWallet::GetWatchOnlyBalance() const
1894 CAmount nTotal = 0;
1896 LOCK2(cs_main, cs_wallet);
1897 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1899 const CWalletTx* pcoin = &(*it).second;
1900 if (pcoin->IsTrusted())
1901 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1905 return nTotal;
1908 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
1910 CAmount nTotal = 0;
1912 LOCK2(cs_main, cs_wallet);
1913 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1915 const CWalletTx* pcoin = &(*it).second;
1916 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1917 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1920 return nTotal;
1923 CAmount CWallet::GetImmatureWatchOnlyBalance() const
1925 CAmount nTotal = 0;
1927 LOCK2(cs_main, cs_wallet);
1928 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1930 const CWalletTx* pcoin = &(*it).second;
1931 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1934 return nTotal;
1937 // Calculate total balance in a different way from GetBalance. The biggest
1938 // difference is that GetBalance sums up all unspent TxOuts paying to the
1939 // wallet, while this sums up both spent and unspent TxOuts paying to the
1940 // wallet, and then subtracts the values of TxIns spending from the wallet. This
1941 // also has fewer restrictions on which unconfirmed transactions are considered
1942 // trusted.
1943 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
1945 LOCK2(cs_main, cs_wallet);
1947 CAmount balance = 0;
1948 for (const auto& entry : mapWallet) {
1949 const CWalletTx& wtx = entry.second;
1950 const int depth = wtx.GetDepthInMainChain();
1951 if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
1952 continue;
1955 // Loop through tx outputs and add incoming payments. For outgoing txs,
1956 // treat change outputs specially, as part of the amount debited.
1957 CAmount debit = wtx.GetDebit(filter);
1958 const bool outgoing = debit > 0;
1959 for (const CTxOut& out : wtx.tx->vout) {
1960 if (outgoing && IsChange(out)) {
1961 debit -= out.nValue;
1962 } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
1963 balance += out.nValue;
1967 // For outgoing txs, subtract amount debited.
1968 if (outgoing && (!account || *account == wtx.strFromAccount)) {
1969 balance -= debit;
1973 if (account) {
1974 balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
1977 return balance;
1980 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
1982 vCoins.clear();
1985 LOCK2(cs_main, cs_wallet);
1987 CAmount nTotal = 0;
1989 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1991 const uint256& wtxid = it->first;
1992 const CWalletTx* pcoin = &(*it).second;
1994 if (!CheckFinalTx(*pcoin))
1995 continue;
1997 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
1998 continue;
2000 int nDepth = pcoin->GetDepthInMainChain();
2001 if (nDepth < 0)
2002 continue;
2004 // We should not consider coins which aren't at least in our mempool
2005 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2006 if (nDepth == 0 && !pcoin->InMempool())
2007 continue;
2009 bool safeTx = pcoin->IsTrusted();
2011 // We should not consider coins from transactions that are replacing
2012 // other transactions.
2014 // Example: There is a transaction A which is replaced by bumpfee
2015 // transaction B. In this case, we want to prevent creation of
2016 // a transaction B' which spends an output of B.
2018 // Reason: If transaction A were initially confirmed, transactions B
2019 // and B' would no longer be valid, so the user would have to create
2020 // a new transaction C to replace B'. However, in the case of a
2021 // one-block reorg, transactions B' and C might BOTH be accepted,
2022 // when the user only wanted one of them. Specifically, there could
2023 // be a 1-block reorg away from the chain where transactions A and C
2024 // were accepted to another chain where B, B', and C were all
2025 // accepted.
2026 if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2027 safeTx = false;
2030 // Similarly, we should not consider coins from transactions that
2031 // have been replaced. In the example above, we would want to prevent
2032 // creation of a transaction A' spending an output of A, because if
2033 // transaction B were initially confirmed, conflicting with A and
2034 // A', we wouldn't want to the user to create a transaction D
2035 // intending to replace A', but potentially resulting in a scenario
2036 // where A, A', and D could all be accepted (instead of just B and
2037 // D, or just A and A' like the user would want).
2038 if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2039 safeTx = false;
2042 if (fOnlySafe && !safeTx) {
2043 continue;
2046 if (nDepth < nMinDepth || nDepth > nMaxDepth)
2047 continue;
2049 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2050 if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2051 continue;
2053 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint((*it).first, i)))
2054 continue;
2056 if (IsLockedCoin((*it).first, i))
2057 continue;
2059 if (IsSpent(wtxid, i))
2060 continue;
2062 isminetype mine = IsMine(pcoin->tx->vout[i]);
2064 if (mine == ISMINE_NO) {
2065 continue;
2068 bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2069 bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2071 vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2073 // Checks the sum amount of all UTXO's.
2074 if (nMinimumSumAmount != MAX_MONEY) {
2075 nTotal += pcoin->tx->vout[i].nValue;
2077 if (nTotal >= nMinimumSumAmount) {
2078 return;
2082 // Checks the maximum number of UTXO's.
2083 if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2084 return;
2091 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2092 std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2094 std::vector<char> vfIncluded;
2096 vfBest.assign(vValue.size(), true);
2097 nBest = nTotalLower;
2099 FastRandomContext insecure_rand;
2101 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2103 vfIncluded.assign(vValue.size(), false);
2104 CAmount nTotal = 0;
2105 bool fReachedTarget = false;
2106 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2108 for (unsigned int i = 0; i < vValue.size(); i++)
2110 //The solver here uses a randomized algorithm,
2111 //the randomness serves no real security purpose but is just
2112 //needed to prevent degenerate behavior and it is important
2113 //that the rng is fast. We do not use a constant random sequence,
2114 //because there may be some privacy improvement by making
2115 //the selection random.
2116 if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2118 nTotal += vValue[i].txout.nValue;
2119 vfIncluded[i] = true;
2120 if (nTotal >= nTargetValue)
2122 fReachedTarget = true;
2123 if (nTotal < nBest)
2125 nBest = nTotal;
2126 vfBest = vfIncluded;
2128 nTotal -= vValue[i].txout.nValue;
2129 vfIncluded[i] = false;
2137 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2138 std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
2140 setCoinsRet.clear();
2141 nValueRet = 0;
2143 // List of values less than target
2144 boost::optional<CInputCoin> coinLowestLarger;
2145 std::vector<CInputCoin> vValue;
2146 CAmount nTotalLower = 0;
2148 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2150 BOOST_FOREACH(const COutput &output, vCoins)
2152 if (!output.fSpendable)
2153 continue;
2155 const CWalletTx *pcoin = output.tx;
2157 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2158 continue;
2160 if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2161 continue;
2163 int i = output.i;
2165 CInputCoin coin = CInputCoin(pcoin, i);
2167 if (coin.txout.nValue == nTargetValue)
2169 setCoinsRet.insert(coin);
2170 nValueRet += coin.txout.nValue;
2171 return true;
2173 else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
2175 vValue.push_back(coin);
2176 nTotalLower += coin.txout.nValue;
2178 else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
2180 coinLowestLarger = coin;
2184 if (nTotalLower == nTargetValue)
2186 for (const auto& input : vValue)
2188 setCoinsRet.insert(input);
2189 nValueRet += input.txout.nValue;
2191 return true;
2194 if (nTotalLower < nTargetValue)
2196 if (!coinLowestLarger)
2197 return false;
2198 setCoinsRet.insert(coinLowestLarger.get());
2199 nValueRet += coinLowestLarger->txout.nValue;
2200 return true;
2203 // Solve subset sum by stochastic approximation
2204 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2205 std::reverse(vValue.begin(), vValue.end());
2206 std::vector<char> vfBest;
2207 CAmount nBest;
2209 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2210 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2211 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2213 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2214 // or the next bigger coin is closer), return the bigger coin
2215 if (coinLowestLarger &&
2216 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
2218 setCoinsRet.insert(coinLowestLarger.get());
2219 nValueRet += coinLowestLarger->txout.nValue;
2221 else {
2222 for (unsigned int i = 0; i < vValue.size(); i++)
2223 if (vfBest[i])
2225 setCoinsRet.insert(vValue[i]);
2226 nValueRet += vValue[i].txout.nValue;
2229 if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2230 LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2231 for (unsigned int i = 0; i < vValue.size(); i++) {
2232 if (vfBest[i]) {
2233 LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
2236 LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2240 return true;
2243 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2245 std::vector<COutput> vCoins(vAvailableCoins);
2247 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2248 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2250 BOOST_FOREACH(const COutput& out, vCoins)
2252 if (!out.fSpendable)
2253 continue;
2254 nValueRet += out.tx->tx->vout[out.i].nValue;
2255 setCoinsRet.insert(CInputCoin(out.tx, out.i));
2257 return (nValueRet >= nTargetValue);
2260 // calculate value from preset inputs and store them
2261 std::set<CInputCoin> setPresetCoins;
2262 CAmount nValueFromPresetInputs = 0;
2264 std::vector<COutPoint> vPresetInputs;
2265 if (coinControl)
2266 coinControl->ListSelected(vPresetInputs);
2267 BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
2269 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2270 if (it != mapWallet.end())
2272 const CWalletTx* pcoin = &it->second;
2273 // Clearly invalid input, fail
2274 if (pcoin->tx->vout.size() <= outpoint.n)
2275 return false;
2276 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2277 setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
2278 } else
2279 return false; // TODO: Allow non-wallet inputs
2282 // remove preset inputs from vCoins
2283 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2285 if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
2286 it = vCoins.erase(it);
2287 else
2288 ++it;
2291 size_t nMaxChainLength = std::min(GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2292 bool fRejectLongChains = GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2294 bool res = nTargetValue <= nValueFromPresetInputs ||
2295 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2296 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2297 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2298 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2299 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2300 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2301 (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2303 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2304 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2306 // add preset inputs to the total value selected
2307 nValueRet += nValueFromPresetInputs;
2309 return res;
2312 bool CWallet::SignTransaction(CMutableTransaction &tx)
2314 AssertLockHeld(cs_wallet); // mapWallet
2316 // sign the new tx
2317 CTransaction txNewConst(tx);
2318 int nIn = 0;
2319 for (const auto& input : tx.vin) {
2320 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2321 if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2322 return false;
2324 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2325 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2326 SignatureData sigdata;
2327 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2328 return false;
2330 UpdateTransaction(tx, nIn, sigdata);
2331 nIn++;
2333 return true;
2336 bool CWallet::FundTransaction(CMutableTransaction& tx, CAmount& nFeeRet, bool overrideEstimatedFeeRate, const CFeeRate& specificFeeRate, int& nChangePosInOut, std::string& strFailReason, bool includeWatching, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, bool keepReserveKey, const CTxDestination& destChange)
2338 std::vector<CRecipient> vecSend;
2340 // Turn the txout set into a CRecipient vector
2341 for (size_t idx = 0; idx < tx.vout.size(); idx++)
2343 const CTxOut& txOut = tx.vout[idx];
2344 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2345 vecSend.push_back(recipient);
2348 CCoinControl coinControl;
2349 coinControl.destChange = destChange;
2350 coinControl.fAllowOtherInputs = true;
2351 coinControl.fAllowWatchOnly = includeWatching;
2352 coinControl.fOverrideFeeRate = overrideEstimatedFeeRate;
2353 coinControl.nFeeRate = specificFeeRate;
2355 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2356 coinControl.Select(txin.prevout);
2358 CReserveKey reservekey(this);
2359 CWalletTx wtx;
2360 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, &coinControl, false))
2361 return false;
2363 if (nChangePosInOut != -1)
2364 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2366 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2367 for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
2368 tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2370 // Add new txins (keeping original txin scriptSig/order)
2371 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
2373 if (!coinControl.IsSelected(txin.prevout))
2375 tx.vin.push_back(txin);
2377 if (lockUnspents)
2379 LOCK2(cs_main, cs_wallet);
2380 LockCoin(txin.prevout);
2385 // optionally keep the change output key
2386 if (keepReserveKey)
2387 reservekey.KeepKey();
2389 return true;
2392 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2393 int& nChangePosInOut, std::string& strFailReason, const CCoinControl* coinControl, bool sign)
2395 CAmount nValue = 0;
2396 int nChangePosRequest = nChangePosInOut;
2397 unsigned int nSubtractFeeFromAmount = 0;
2398 for (const auto& recipient : vecSend)
2400 if (nValue < 0 || recipient.nAmount < 0)
2402 strFailReason = _("Transaction amounts must not be negative");
2403 return false;
2405 nValue += recipient.nAmount;
2407 if (recipient.fSubtractFeeFromAmount)
2408 nSubtractFeeFromAmount++;
2410 if (vecSend.empty())
2412 strFailReason = _("Transaction must have at least one recipient");
2413 return false;
2416 wtxNew.fTimeReceivedIsTxTime = true;
2417 wtxNew.BindWallet(this);
2418 CMutableTransaction txNew;
2420 // Discourage fee sniping.
2422 // For a large miner the value of the transactions in the best block and
2423 // the mempool can exceed the cost of deliberately attempting to mine two
2424 // blocks to orphan the current best block. By setting nLockTime such that
2425 // only the next block can include the transaction, we discourage this
2426 // practice as the height restricted and limited blocksize gives miners
2427 // considering fee sniping fewer options for pulling off this attack.
2429 // A simple way to think about this is from the wallet's point of view we
2430 // always want the blockchain to move forward. By setting nLockTime this
2431 // way we're basically making the statement that we only want this
2432 // transaction to appear in the next block; we don't want to potentially
2433 // encourage reorgs by allowing transactions to appear at lower heights
2434 // than the next block in forks of the best chain.
2436 // Of course, the subsidy is high enough, and transaction volume low
2437 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2438 // now we ensure code won't be written that makes assumptions about
2439 // nLockTime that preclude a fix later.
2440 txNew.nLockTime = chainActive.Height();
2442 // Secondly occasionally randomly pick a nLockTime even further back, so
2443 // that transactions that are delayed after signing for whatever reason,
2444 // e.g. high-latency mix networks and some CoinJoin implementations, have
2445 // better privacy.
2446 if (GetRandInt(10) == 0)
2447 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2449 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2450 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2453 std::set<CInputCoin> setCoins;
2454 LOCK2(cs_main, cs_wallet);
2456 std::vector<COutput> vAvailableCoins;
2457 AvailableCoins(vAvailableCoins, true, coinControl);
2459 nFeeRet = 0;
2460 // Start with no fee and loop until there is enough fee
2461 while (true)
2463 nChangePosInOut = nChangePosRequest;
2464 txNew.vin.clear();
2465 txNew.vout.clear();
2466 wtxNew.fFromMe = true;
2467 bool fFirst = true;
2469 CAmount nValueToSelect = nValue;
2470 if (nSubtractFeeFromAmount == 0)
2471 nValueToSelect += nFeeRet;
2472 // vouts to the payees
2473 for (const auto& recipient : vecSend)
2475 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2477 if (recipient.fSubtractFeeFromAmount)
2479 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2481 if (fFirst) // first receiver pays the remainder not divisible by output count
2483 fFirst = false;
2484 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2488 if (IsDust(txout, ::dustRelayFee))
2490 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2492 if (txout.nValue < 0)
2493 strFailReason = _("The transaction amount is too small to pay the fee");
2494 else
2495 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2497 else
2498 strFailReason = _("Transaction amount too small");
2499 return false;
2501 txNew.vout.push_back(txout);
2504 // Choose coins to use
2505 CAmount nValueIn = 0;
2506 setCoins.clear();
2507 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, coinControl))
2509 strFailReason = _("Insufficient funds");
2510 return false;
2513 const CAmount nChange = nValueIn - nValueToSelect;
2514 if (nChange > 0)
2516 // Fill a vout to ourself
2517 // TODO: pass in scriptChange instead of reservekey so
2518 // change transaction isn't always pay-to-bitcoin-address
2519 CScript scriptChange;
2521 // coin control: send change to custom address
2522 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
2523 scriptChange = GetScriptForDestination(coinControl->destChange);
2525 // no coin control: send change to newly generated address
2526 else
2528 // Note: We use a new key here to keep it from being obvious which side is the change.
2529 // The drawback is that by not reusing a previous key, the change may be lost if a
2530 // backup is restored, if the backup doesn't have the new private key for the change.
2531 // If we reused the old key, it would be possible to add code to look for and
2532 // rediscover unknown transactions that were written with keys of ours to recover
2533 // post-backup change.
2535 // Reserve a new key pair from key pool
2536 CPubKey vchPubKey;
2537 bool ret;
2538 ret = reservekey.GetReservedKey(vchPubKey, true);
2539 if (!ret)
2541 strFailReason = _("Keypool ran out, please call keypoolrefill first");
2542 return false;
2545 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2548 CTxOut newTxOut(nChange, scriptChange);
2550 // We do not move dust-change to fees, because the sender would end up paying more than requested.
2551 // This would be against the purpose of the all-inclusive feature.
2552 // So instead we raise the change and deduct from the recipient.
2553 if (nSubtractFeeFromAmount > 0 && IsDust(newTxOut, ::dustRelayFee))
2555 CAmount nDust = GetDustThreshold(newTxOut, ::dustRelayFee) - newTxOut.nValue;
2556 newTxOut.nValue += nDust; // raise change until no more dust
2557 for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
2559 if (vecSend[i].fSubtractFeeFromAmount)
2561 txNew.vout[i].nValue -= nDust;
2562 if (IsDust(txNew.vout[i], ::dustRelayFee))
2564 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2565 return false;
2567 break;
2572 // Never create dust outputs; if we would, just
2573 // add the dust to the fee.
2574 if (IsDust(newTxOut, ::dustRelayFee))
2576 nChangePosInOut = -1;
2577 nFeeRet += nChange;
2578 reservekey.ReturnKey();
2580 else
2582 if (nChangePosInOut == -1)
2584 // Insert change txn at random position:
2585 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2587 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2589 strFailReason = _("Change index out of range");
2590 return false;
2593 std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2594 txNew.vout.insert(position, newTxOut);
2596 } else {
2597 reservekey.ReturnKey();
2598 nChangePosInOut = -1;
2601 // Fill vin
2603 // Note how the sequence number is set to non-maxint so that
2604 // the nLockTime set above actually works.
2606 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2607 // we use the highest possible value in that range (maxint-2)
2608 // to avoid conflicting with other possible uses of nSequence,
2609 // and in the spirit of "smallest possible change from prior
2610 // behavior."
2611 bool rbf = coinControl ? coinControl->signalRbf : fWalletRbf;
2612 for (const auto& coin : setCoins)
2613 txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
2614 std::numeric_limits<unsigned int>::max() - (rbf ? 2 : 1)));
2616 // Fill in dummy signatures for fee calculation.
2617 if (!DummySignTx(txNew, setCoins)) {
2618 strFailReason = _("Signing transaction failed");
2619 return false;
2622 unsigned int nBytes = GetVirtualTransactionSize(txNew);
2624 CTransaction txNewConst(txNew);
2626 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2627 for (auto& vin : txNew.vin) {
2628 vin.scriptSig = CScript();
2629 vin.scriptWitness.SetNull();
2632 // Allow to override the default confirmation target over the CoinControl instance
2633 int currentConfirmationTarget = nTxConfirmTarget;
2634 if (coinControl && coinControl->nConfirmTarget > 0)
2635 currentConfirmationTarget = coinControl->nConfirmTarget;
2637 CAmount nFeeNeeded = GetMinimumFee(nBytes, currentConfirmationTarget, ::mempool, ::feeEstimator);
2638 if (coinControl && nFeeNeeded > 0 && coinControl->nMinimumTotalFee > nFeeNeeded) {
2639 nFeeNeeded = coinControl->nMinimumTotalFee;
2641 if (coinControl && coinControl->fOverrideFeeRate)
2642 nFeeNeeded = coinControl->nFeeRate.GetFee(nBytes);
2644 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2645 // because we must be at the maximum allowed fee.
2646 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2648 strFailReason = _("Transaction too large for fee policy");
2649 return false;
2652 if (nFeeRet >= nFeeNeeded) {
2653 // Reduce fee to only the needed amount if we have change
2654 // output to increase. This prevents potential overpayment
2655 // in fees if the coins selected to meet nFeeNeeded result
2656 // in a transaction that requires less fee than the prior
2657 // iteration.
2658 // TODO: The case where nSubtractFeeFromAmount > 0 remains
2659 // to be addressed because it requires returning the fee to
2660 // the payees and not the change output.
2661 // TODO: The case where there is no change output remains
2662 // to be addressed so we avoid creating too small an output.
2663 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2664 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2665 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2666 change_position->nValue += extraFeePaid;
2667 nFeeRet -= extraFeePaid;
2669 break; // Done, enough fee included.
2672 // Try to reduce change to include necessary fee
2673 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2674 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2675 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2676 // Only reduce change if remaining amount is still a large enough output.
2677 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2678 change_position->nValue -= additionalFeeNeeded;
2679 nFeeRet += additionalFeeNeeded;
2680 break; // Done, able to increase fee from change
2684 // Include more fee and try again.
2685 nFeeRet = nFeeNeeded;
2686 continue;
2690 if (sign)
2692 CTransaction txNewConst(txNew);
2693 int nIn = 0;
2694 for (const auto& coin : setCoins)
2696 const CScript& scriptPubKey = coin.txout.scriptPubKey;
2697 SignatureData sigdata;
2699 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2701 strFailReason = _("Signing transaction failed");
2702 return false;
2703 } else {
2704 UpdateTransaction(txNew, nIn, sigdata);
2707 nIn++;
2711 // Embed the constructed transaction data in wtxNew.
2712 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2714 // Limit size
2715 if (GetTransactionWeight(wtxNew) >= MAX_STANDARD_TX_WEIGHT)
2717 strFailReason = _("Transaction too large");
2718 return false;
2722 if (GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2723 // Lastly, ensure this tx will pass the mempool's chain limits
2724 LockPoints lp;
2725 CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
2726 CTxMemPool::setEntries setAncestors;
2727 size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2728 size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2729 size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2730 size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2731 std::string errString;
2732 if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2733 strFailReason = _("Transaction has too long of a mempool chain");
2734 return false;
2737 return true;
2741 * Call after CreateTransaction unless you want to abort
2743 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
2746 LOCK2(cs_main, cs_wallet);
2747 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
2749 // Take key pair from key pool so it won't be used again
2750 reservekey.KeepKey();
2752 // Add tx to wallet, because if it has change it's also ours,
2753 // otherwise just for transaction history.
2754 AddToWallet(wtxNew);
2756 // Notify that old coins are spent
2757 BOOST_FOREACH(const CTxIn& txin, wtxNew.tx->vin)
2759 CWalletTx &coin = mapWallet[txin.prevout.hash];
2760 coin.BindWallet(this);
2761 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2765 // Track how many getdata requests our transaction gets
2766 mapRequestCount[wtxNew.GetHash()] = 0;
2768 if (fBroadcastTransactions)
2770 // Broadcast
2771 if (!wtxNew.AcceptToMemoryPool(maxTxFee, state)) {
2772 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
2773 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2774 } else {
2775 wtxNew.RelayWalletTransaction(connman);
2779 return true;
2782 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
2783 CWalletDB walletdb(*dbw);
2784 return walletdb.ListAccountCreditDebit(strAccount, entries);
2787 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
2789 CWalletDB walletdb(*dbw);
2791 return AddAccountingEntry(acentry, &walletdb);
2794 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
2796 if (!pwalletdb->WriteAccountingEntry_Backend(acentry))
2797 return false;
2799 laccentries.push_back(acentry);
2800 CAccountingEntry & entry = laccentries.back();
2801 wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
2803 return true;
2806 CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
2808 return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
2811 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, bool ignoreUserSetFee)
2813 // payTxFee is the user-set global for desired feerate
2814 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
2815 // User didn't set: use -txconfirmtarget to estimate...
2816 if (nFeeNeeded == 0 || ignoreUserSetFee) {
2817 int estimateFoundTarget = nConfirmTarget;
2818 nFeeNeeded = estimator.estimateSmartFee(nConfirmTarget, &estimateFoundTarget, pool).GetFee(nTxBytes);
2819 // ... unless we don't have enough mempool data for estimatefee, then use fallbackFee
2820 if (nFeeNeeded == 0)
2821 nFeeNeeded = fallbackFee.GetFee(nTxBytes);
2823 // prevent user from paying a fee below minRelayTxFee or minTxFee
2824 nFeeNeeded = std::max(nFeeNeeded, GetRequiredFee(nTxBytes));
2825 // But always obey the maximum
2826 if (nFeeNeeded > maxTxFee)
2827 nFeeNeeded = maxTxFee;
2828 return nFeeNeeded;
2834 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2836 fFirstRunRet = false;
2837 DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
2838 if (nLoadWalletRet == DB_NEED_REWRITE)
2840 if (dbw->Rewrite("\x04pool"))
2842 LOCK(cs_wallet);
2843 setKeyPool.clear();
2844 // Note: can't top-up keypool here, because wallet is locked.
2845 // User will be prompted to unlock wallet the next operation
2846 // that requires a new key.
2850 if (nLoadWalletRet != DB_LOAD_OK)
2851 return nLoadWalletRet;
2852 fFirstRunRet = !vchDefaultKey.IsValid();
2854 uiInterface.LoadWallet(this);
2856 return DB_LOAD_OK;
2859 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
2861 AssertLockHeld(cs_wallet); // mapWallet
2862 vchDefaultKey = CPubKey();
2863 DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
2864 for (uint256 hash : vHashOut)
2865 mapWallet.erase(hash);
2867 if (nZapSelectTxRet == DB_NEED_REWRITE)
2869 if (dbw->Rewrite("\x04pool"))
2871 setKeyPool.clear();
2872 // Note: can't top-up keypool here, because wallet is locked.
2873 // User will be prompted to unlock wallet the next operation
2874 // that requires a new key.
2878 if (nZapSelectTxRet != DB_LOAD_OK)
2879 return nZapSelectTxRet;
2881 MarkDirty();
2883 return DB_LOAD_OK;
2887 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
2889 vchDefaultKey = CPubKey();
2890 DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
2891 if (nZapWalletTxRet == DB_NEED_REWRITE)
2893 if (dbw->Rewrite("\x04pool"))
2895 LOCK(cs_wallet);
2896 setKeyPool.clear();
2897 // Note: can't top-up keypool here, because wallet is locked.
2898 // User will be prompted to unlock wallet the next operation
2899 // that requires a new key.
2903 if (nZapWalletTxRet != DB_LOAD_OK)
2904 return nZapWalletTxRet;
2906 return DB_LOAD_OK;
2910 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
2912 bool fUpdated = false;
2914 LOCK(cs_wallet); // mapAddressBook
2915 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
2916 fUpdated = mi != mapAddressBook.end();
2917 mapAddressBook[address].name = strName;
2918 if (!strPurpose.empty()) /* update purpose only if requested */
2919 mapAddressBook[address].purpose = strPurpose;
2921 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
2922 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
2923 if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
2924 return false;
2925 return CWalletDB(*dbw).WriteName(CBitcoinAddress(address).ToString(), strName);
2928 bool CWallet::DelAddressBook(const CTxDestination& address)
2931 LOCK(cs_wallet); // mapAddressBook
2933 // Delete destdata tuples associated with address
2934 std::string strAddress = CBitcoinAddress(address).ToString();
2935 BOOST_FOREACH(const PAIRTYPE(std::string, std::string) &item, mapAddressBook[address].destdata)
2937 CWalletDB(*dbw).EraseDestData(strAddress, item.first);
2939 mapAddressBook.erase(address);
2942 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
2944 CWalletDB(*dbw).ErasePurpose(CBitcoinAddress(address).ToString());
2945 return CWalletDB(*dbw).EraseName(CBitcoinAddress(address).ToString());
2948 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
2950 CTxDestination address;
2951 if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
2952 auto mi = mapAddressBook.find(address);
2953 if (mi != mapAddressBook.end()) {
2954 return mi->second.name;
2957 // A scriptPubKey that doesn't have an entry in the address book is
2958 // associated with the default account ("").
2959 const static std::string DEFAULT_ACCOUNT_NAME;
2960 return DEFAULT_ACCOUNT_NAME;
2963 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
2965 if (!CWalletDB(*dbw).WriteDefaultKey(vchPubKey))
2966 return false;
2967 vchDefaultKey = vchPubKey;
2968 return true;
2972 * Mark old keypool keys as used,
2973 * and generate all new keys
2975 bool CWallet::NewKeyPool()
2978 LOCK(cs_wallet);
2979 CWalletDB walletdb(*dbw);
2980 BOOST_FOREACH(int64_t nIndex, setKeyPool)
2981 walletdb.ErasePool(nIndex);
2982 setKeyPool.clear();
2984 if (!TopUpKeyPool()) {
2985 return false;
2987 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
2989 return true;
2992 size_t CWallet::KeypoolCountExternalKeys()
2994 AssertLockHeld(cs_wallet); // setKeyPool
2996 // immediately return setKeyPool's size if HD or HD_SPLIT is disabled or not supported
2997 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
2998 return setKeyPool.size();
3000 CWalletDB walletdb(*dbw);
3002 // count amount of external keys
3003 size_t amountE = 0;
3004 for(const int64_t& id : setKeyPool)
3006 CKeyPool tmpKeypool;
3007 if (!walletdb.ReadPool(id, tmpKeypool))
3008 throw std::runtime_error(std::string(__func__) + ": read failed");
3009 amountE += !tmpKeypool.fInternal;
3012 return amountE;
3015 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3018 LOCK(cs_wallet);
3020 if (IsLocked())
3021 return false;
3023 // Top up key pool
3024 unsigned int nTargetSize;
3025 if (kpSize > 0)
3026 nTargetSize = kpSize;
3027 else
3028 nTargetSize = std::max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3030 // count amount of available keys (internal, external)
3031 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3032 int64_t amountExternal = KeypoolCountExternalKeys();
3033 int64_t amountInternal = setKeyPool.size() - amountExternal;
3034 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - amountExternal, (int64_t) 0);
3035 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - amountInternal, (int64_t) 0);
3037 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3039 // don't create extra internal keys
3040 missingInternal = 0;
3042 bool internal = false;
3043 CWalletDB walletdb(*dbw);
3044 for (int64_t i = missingInternal + missingExternal; i--;)
3046 int64_t nEnd = 1;
3047 if (i < missingInternal)
3048 internal = true;
3049 if (!setKeyPool.empty())
3050 nEnd = *(--setKeyPool.end()) + 1;
3051 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey(internal), internal)))
3052 throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3053 setKeyPool.insert(nEnd);
3054 LogPrintf("keypool added key %d, size=%u, internal=%d\n", nEnd, setKeyPool.size(), internal);
3057 return true;
3060 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool internal)
3062 nIndex = -1;
3063 keypool.vchPubKey = CPubKey();
3065 LOCK(cs_wallet);
3067 if (!IsLocked())
3068 TopUpKeyPool();
3070 // Get the oldest key
3071 if(setKeyPool.empty())
3072 return;
3074 CWalletDB walletdb(*dbw);
3076 // try to find a key that matches the internal/external filter
3077 for(const int64_t& id : setKeyPool)
3079 CKeyPool tmpKeypool;
3080 if (!walletdb.ReadPool(id, tmpKeypool))
3081 throw std::runtime_error(std::string(__func__) + ": read failed");
3082 if (!HaveKey(tmpKeypool.vchPubKey.GetID()))
3083 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3084 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT) || tmpKeypool.fInternal == internal)
3086 nIndex = id;
3087 keypool = tmpKeypool;
3088 setKeyPool.erase(id);
3089 assert(keypool.vchPubKey.IsValid());
3090 LogPrintf("keypool reserve %d\n", nIndex);
3091 return;
3097 void CWallet::KeepKey(int64_t nIndex)
3099 // Remove from key pool
3100 CWalletDB walletdb(*dbw);
3101 walletdb.ErasePool(nIndex);
3102 LogPrintf("keypool keep %d\n", nIndex);
3105 void CWallet::ReturnKey(int64_t nIndex)
3107 // Return to key pool
3109 LOCK(cs_wallet);
3110 setKeyPool.insert(nIndex);
3112 LogPrintf("keypool return %d\n", nIndex);
3115 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3117 int64_t nIndex = 0;
3118 CKeyPool keypool;
3120 LOCK(cs_wallet);
3121 ReserveKeyFromKeyPool(nIndex, keypool, internal);
3122 if (nIndex == -1)
3124 if (IsLocked()) return false;
3125 result = GenerateNewKey(internal);
3126 return true;
3128 KeepKey(nIndex);
3129 result = keypool.vchPubKey;
3131 return true;
3134 int64_t CWallet::GetOldestKeyPoolTime()
3136 LOCK(cs_wallet);
3138 // if the keypool is empty, return <NOW>
3139 if (setKeyPool.empty())
3140 return GetTime();
3142 CKeyPool keypool;
3143 CWalletDB walletdb(*dbw);
3145 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT))
3147 // if HD & HD Chain Split is enabled, response max(oldest-internal-key, oldest-external-key)
3148 int64_t now = GetTime();
3149 int64_t oldest_external = now, oldest_internal = now;
3151 for(const int64_t& id : setKeyPool)
3153 if (!walletdb.ReadPool(id, keypool)) {
3154 throw std::runtime_error(std::string(__func__) + ": read failed");
3156 if (keypool.fInternal && keypool.nTime < oldest_internal) {
3157 oldest_internal = keypool.nTime;
3159 else if (!keypool.fInternal && keypool.nTime < oldest_external) {
3160 oldest_external = keypool.nTime;
3162 if (oldest_internal != now && oldest_external != now) {
3163 break;
3166 return std::max(oldest_internal, oldest_external);
3168 // load oldest key from keypool, get time and return
3169 int64_t nIndex = *(setKeyPool.begin());
3170 if (!walletdb.ReadPool(nIndex, keypool))
3171 throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3172 assert(keypool.vchPubKey.IsValid());
3173 return keypool.nTime;
3176 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3178 std::map<CTxDestination, CAmount> balances;
3181 LOCK(cs_wallet);
3182 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3184 CWalletTx *pcoin = &walletEntry.second;
3186 if (!pcoin->IsTrusted())
3187 continue;
3189 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3190 continue;
3192 int nDepth = pcoin->GetDepthInMainChain();
3193 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3194 continue;
3196 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3198 CTxDestination addr;
3199 if (!IsMine(pcoin->tx->vout[i]))
3200 continue;
3201 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3202 continue;
3204 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3206 if (!balances.count(addr))
3207 balances[addr] = 0;
3208 balances[addr] += n;
3213 return balances;
3216 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3218 AssertLockHeld(cs_wallet); // mapWallet
3219 std::set< std::set<CTxDestination> > groupings;
3220 std::set<CTxDestination> grouping;
3222 BOOST_FOREACH(PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet)
3224 CWalletTx *pcoin = &walletEntry.second;
3226 if (pcoin->tx->vin.size() > 0)
3228 bool any_mine = false;
3229 // group all input addresses with each other
3230 BOOST_FOREACH(CTxIn txin, pcoin->tx->vin)
3232 CTxDestination address;
3233 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3234 continue;
3235 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3236 continue;
3237 grouping.insert(address);
3238 any_mine = true;
3241 // group change with input addresses
3242 if (any_mine)
3244 BOOST_FOREACH(CTxOut txout, pcoin->tx->vout)
3245 if (IsChange(txout))
3247 CTxDestination txoutAddr;
3248 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3249 continue;
3250 grouping.insert(txoutAddr);
3253 if (grouping.size() > 0)
3255 groupings.insert(grouping);
3256 grouping.clear();
3260 // group lone addrs by themselves
3261 for (const auto& txout : pcoin->tx->vout)
3262 if (IsMine(txout))
3264 CTxDestination address;
3265 if(!ExtractDestination(txout.scriptPubKey, address))
3266 continue;
3267 grouping.insert(address);
3268 groupings.insert(grouping);
3269 grouping.clear();
3273 std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3274 std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3275 BOOST_FOREACH(std::set<CTxDestination> _grouping, groupings)
3277 // make a set of all the groups hit by this new group
3278 std::set< std::set<CTxDestination>* > hits;
3279 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3280 BOOST_FOREACH(CTxDestination address, _grouping)
3281 if ((it = setmap.find(address)) != setmap.end())
3282 hits.insert((*it).second);
3284 // merge all hit groups into a new single group and delete old groups
3285 std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3286 BOOST_FOREACH(std::set<CTxDestination>* hit, hits)
3288 merged->insert(hit->begin(), hit->end());
3289 uniqueGroupings.erase(hit);
3290 delete hit;
3292 uniqueGroupings.insert(merged);
3294 // update setmap
3295 BOOST_FOREACH(CTxDestination element, *merged)
3296 setmap[element] = merged;
3299 std::set< std::set<CTxDestination> > ret;
3300 BOOST_FOREACH(std::set<CTxDestination>* uniqueGrouping, uniqueGroupings)
3302 ret.insert(*uniqueGrouping);
3303 delete uniqueGrouping;
3306 return ret;
3309 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3311 LOCK(cs_wallet);
3312 std::set<CTxDestination> result;
3313 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
3315 const CTxDestination& address = item.first;
3316 const std::string& strName = item.second.name;
3317 if (strName == strAccount)
3318 result.insert(address);
3320 return result;
3323 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3325 if (nIndex == -1)
3327 CKeyPool keypool;
3328 pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3329 if (nIndex != -1)
3330 vchPubKey = keypool.vchPubKey;
3331 else {
3332 return false;
3335 assert(vchPubKey.IsValid());
3336 pubkey = vchPubKey;
3337 return true;
3340 void CReserveKey::KeepKey()
3342 if (nIndex != -1)
3343 pwallet->KeepKey(nIndex);
3344 nIndex = -1;
3345 vchPubKey = CPubKey();
3348 void CReserveKey::ReturnKey()
3350 if (nIndex != -1)
3351 pwallet->ReturnKey(nIndex);
3352 nIndex = -1;
3353 vchPubKey = CPubKey();
3356 void CWallet::GetAllReserveKeys(std::set<CKeyID>& setAddress) const
3358 setAddress.clear();
3360 CWalletDB walletdb(*dbw);
3362 LOCK2(cs_main, cs_wallet);
3363 BOOST_FOREACH(const int64_t& id, setKeyPool)
3365 CKeyPool keypool;
3366 if (!walletdb.ReadPool(id, keypool))
3367 throw std::runtime_error(std::string(__func__) + ": read failed");
3368 assert(keypool.vchPubKey.IsValid());
3369 CKeyID keyID = keypool.vchPubKey.GetID();
3370 if (!HaveKey(keyID))
3371 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3372 setAddress.insert(keyID);
3376 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
3378 std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
3379 CPubKey pubkey;
3380 if (!rKey->GetReservedKey(pubkey))
3381 return;
3383 script = rKey;
3384 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3387 void CWallet::LockCoin(const COutPoint& output)
3389 AssertLockHeld(cs_wallet); // setLockedCoins
3390 setLockedCoins.insert(output);
3393 void CWallet::UnlockCoin(const COutPoint& output)
3395 AssertLockHeld(cs_wallet); // setLockedCoins
3396 setLockedCoins.erase(output);
3399 void CWallet::UnlockAllCoins()
3401 AssertLockHeld(cs_wallet); // setLockedCoins
3402 setLockedCoins.clear();
3405 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3407 AssertLockHeld(cs_wallet); // setLockedCoins
3408 COutPoint outpt(hash, n);
3410 return (setLockedCoins.count(outpt) > 0);
3413 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts)
3415 AssertLockHeld(cs_wallet); // setLockedCoins
3416 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3417 it != setLockedCoins.end(); it++) {
3418 COutPoint outpt = (*it);
3419 vOutpts.push_back(outpt);
3423 /** @} */ // end of Actions
3425 class CAffectedKeysVisitor : public boost::static_visitor<void> {
3426 private:
3427 const CKeyStore &keystore;
3428 std::vector<CKeyID> &vKeys;
3430 public:
3431 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
3433 void Process(const CScript &script) {
3434 txnouttype type;
3435 std::vector<CTxDestination> vDest;
3436 int nRequired;
3437 if (ExtractDestinations(script, type, vDest, nRequired)) {
3438 BOOST_FOREACH(const CTxDestination &dest, vDest)
3439 boost::apply_visitor(*this, dest);
3443 void operator()(const CKeyID &keyId) {
3444 if (keystore.HaveKey(keyId))
3445 vKeys.push_back(keyId);
3448 void operator()(const CScriptID &scriptId) {
3449 CScript script;
3450 if (keystore.GetCScript(scriptId, script))
3451 Process(script);
3454 void operator()(const CNoDestination &none) {}
3457 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3458 AssertLockHeld(cs_wallet); // mapKeyMetadata
3459 mapKeyBirth.clear();
3461 // get birth times for keys with metadata
3462 for (const auto& entry : mapKeyMetadata) {
3463 if (entry.second.nCreateTime) {
3464 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3468 // map in which we'll infer heights of other keys
3469 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3470 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3471 std::set<CKeyID> setKeys;
3472 GetKeys(setKeys);
3473 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
3474 if (mapKeyBirth.count(keyid) == 0)
3475 mapKeyFirstBlock[keyid] = pindexMax;
3477 setKeys.clear();
3479 // if there are no such keys, we're done
3480 if (mapKeyFirstBlock.empty())
3481 return;
3483 // find first block that affects those keys, if there are any left
3484 std::vector<CKeyID> vAffected;
3485 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3486 // iterate over all wallet transactions...
3487 const CWalletTx &wtx = (*it).second;
3488 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3489 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3490 // ... which are already in a block
3491 int nHeight = blit->second->nHeight;
3492 BOOST_FOREACH(const CTxOut &txout, wtx.tx->vout) {
3493 // iterate over all their outputs
3494 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3495 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
3496 // ... and all their affected keys
3497 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3498 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3499 rit->second = blit->second;
3501 vAffected.clear();
3506 // Extract block timestamps for those keys
3507 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3508 mapKeyBirth[it->first] = it->second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3512 * Compute smart timestamp for a transaction being added to the wallet.
3514 * Logic:
3515 * - If sending a transaction, assign its timestamp to the current time.
3516 * - If receiving a transaction outside a block, assign its timestamp to the
3517 * current time.
3518 * - If receiving a block with a future timestamp, assign all its (not already
3519 * known) transactions' timestamps to the current time.
3520 * - If receiving a block with a past timestamp, before the most recent known
3521 * transaction (that we care about), assign all its (not already known)
3522 * transactions' timestamps to the same timestamp as that most-recent-known
3523 * transaction.
3524 * - If receiving a block with a past timestamp, but after the most recent known
3525 * transaction, assign all its (not already known) transactions' timestamps to
3526 * the block time.
3528 * For more information see CWalletTx::nTimeSmart,
3529 * https://bitcointalk.org/?topic=54527, or
3530 * https://github.com/bitcoin/bitcoin/pull/1393.
3532 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3534 unsigned int nTimeSmart = wtx.nTimeReceived;
3535 if (!wtx.hashUnset()) {
3536 if (mapBlockIndex.count(wtx.hashBlock)) {
3537 int64_t latestNow = wtx.nTimeReceived;
3538 int64_t latestEntry = 0;
3540 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3541 int64_t latestTolerated = latestNow + 300;
3542 const TxItems& txOrdered = wtxOrdered;
3543 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3544 CWalletTx* const pwtx = it->second.first;
3545 if (pwtx == &wtx) {
3546 continue;
3548 CAccountingEntry* const pacentry = it->second.second;
3549 int64_t nSmartTime;
3550 if (pwtx) {
3551 nSmartTime = pwtx->nTimeSmart;
3552 if (!nSmartTime) {
3553 nSmartTime = pwtx->nTimeReceived;
3555 } else {
3556 nSmartTime = pacentry->nTime;
3558 if (nSmartTime <= latestTolerated) {
3559 latestEntry = nSmartTime;
3560 if (nSmartTime > latestNow) {
3561 latestNow = nSmartTime;
3563 break;
3567 int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3568 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3569 } else {
3570 LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3573 return nTimeSmart;
3576 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3578 if (boost::get<CNoDestination>(&dest))
3579 return false;
3581 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3582 return CWalletDB(*dbw).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
3585 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3587 if (!mapAddressBook[dest].destdata.erase(key))
3588 return false;
3589 return CWalletDB(*dbw).EraseDestData(CBitcoinAddress(dest).ToString(), key);
3592 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3594 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3595 return true;
3598 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3600 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3601 if(i != mapAddressBook.end())
3603 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3604 if(j != i->second.destdata.end())
3606 if(value)
3607 *value = j->second;
3608 return true;
3611 return false;
3614 std::string CWallet::GetWalletHelpString(bool showDebug)
3616 std::string strUsage = HelpMessageGroup(_("Wallet options:"));
3617 strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
3618 strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE));
3619 strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
3620 CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)));
3621 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
3622 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)));
3623 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
3624 CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
3625 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
3626 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup"));
3627 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE));
3628 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));
3629 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));
3630 strUsage += HelpMessageOpt("-walletrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (default: %u)"), DEFAULT_WALLET_RBF));
3631 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
3632 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT));
3633 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST));
3634 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
3635 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
3636 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
3638 if (showDebug)
3640 strUsage += HelpMessageGroup(_("Wallet debugging/testing options:"));
3642 strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE));
3643 strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET));
3644 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB));
3645 strUsage += HelpMessageOpt("-walletrejectlongchains", strprintf(_("Wallet will not create transactions that violate mempool chain limits (default: %u)"), DEFAULT_WALLET_REJECT_LONG_CHAINS));
3648 return strUsage;
3651 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
3653 // needed to restore wallet transaction meta data after -zapwallettxes
3654 std::vector<CWalletTx> vWtx;
3656 if (GetBoolArg("-zapwallettxes", false)) {
3657 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3659 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3660 CWallet *tempWallet = new CWallet(std::move(dbw));
3661 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3662 if (nZapWalletRet != DB_LOAD_OK) {
3663 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3664 return NULL;
3667 delete tempWallet;
3668 tempWallet = NULL;
3671 uiInterface.InitMessage(_("Loading wallet..."));
3673 int64_t nStart = GetTimeMillis();
3674 bool fFirstRun = true;
3675 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3676 CWallet *walletInstance = new CWallet(std::move(dbw));
3677 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3678 if (nLoadWalletRet != DB_LOAD_OK)
3680 if (nLoadWalletRet == DB_CORRUPT) {
3681 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3682 return NULL;
3684 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3686 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3687 " or address book entries might be missing or incorrect."),
3688 walletFile));
3690 else if (nLoadWalletRet == DB_TOO_NEW) {
3691 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
3692 return NULL;
3694 else if (nLoadWalletRet == DB_NEED_REWRITE)
3696 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3697 return NULL;
3699 else {
3700 InitError(strprintf(_("Error loading %s"), walletFile));
3701 return NULL;
3705 if (GetBoolArg("-upgradewallet", fFirstRun))
3707 int nMaxVersion = GetArg("-upgradewallet", 0);
3708 if (nMaxVersion == 0) // the -upgradewallet without argument case
3710 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3711 nMaxVersion = CLIENT_VERSION;
3712 walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3714 else
3715 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3716 if (nMaxVersion < walletInstance->GetVersion())
3718 InitError(_("Cannot downgrade wallet"));
3719 return NULL;
3721 walletInstance->SetMaxVersion(nMaxVersion);
3724 if (fFirstRun)
3726 // Create new keyUser and set as default key
3727 if (GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && !walletInstance->IsHDEnabled()) {
3729 // ensure this wallet.dat can only be opened by clients supporting HD with chain split
3730 walletInstance->SetMinVersion(FEATURE_HD_SPLIT);
3732 // generate a new master key
3733 CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
3734 if (!walletInstance->SetHDMasterKey(masterPubKey))
3735 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
3737 CPubKey newDefaultKey;
3738 if (walletInstance->GetKeyFromPool(newDefaultKey, false)) {
3739 walletInstance->SetDefaultKey(newDefaultKey);
3740 if (!walletInstance->SetAddressBook(walletInstance->vchDefaultKey.GetID(), "", "receive")) {
3741 InitError(_("Cannot write default address") += "\n");
3742 return NULL;
3746 walletInstance->SetBestChain(chainActive.GetLocator());
3748 else if (IsArgSet("-usehd")) {
3749 bool useHD = GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
3750 if (walletInstance->IsHDEnabled() && !useHD) {
3751 InitError(strprintf(_("Error loading %s: You can't disable HD on a already existing HD wallet"), walletFile));
3752 return NULL;
3754 if (!walletInstance->IsHDEnabled() && useHD) {
3755 InitError(strprintf(_("Error loading %s: You can't enable HD on a already existing non-HD wallet"), walletFile));
3756 return NULL;
3760 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
3762 RegisterValidationInterface(walletInstance);
3764 CBlockIndex *pindexRescan = chainActive.Genesis();
3765 if (!GetBoolArg("-rescan", false))
3767 CWalletDB walletdb(*walletInstance->dbw);
3768 CBlockLocator locator;
3769 if (walletdb.ReadBestBlock(locator))
3770 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
3772 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
3774 //We can't rescan beyond non-pruned blocks, stop and throw an error
3775 //this might happen if a user uses a old wallet within a pruned node
3776 // or if he ran -disablewallet for a longer time, then decided to re-enable
3777 if (fPruneMode)
3779 CBlockIndex *block = chainActive.Tip();
3780 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
3781 block = block->pprev;
3783 if (pindexRescan != block) {
3784 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3785 return NULL;
3789 uiInterface.InitMessage(_("Rescanning..."));
3790 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
3791 nStart = GetTimeMillis();
3792 walletInstance->ScanForWalletTransactions(pindexRescan, true);
3793 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
3794 walletInstance->SetBestChain(chainActive.GetLocator());
3795 CWalletDB::IncrementUpdateCounter();
3797 // Restore wallet transaction metadata after -zapwallettxes=1
3798 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
3800 CWalletDB walletdb(*walletInstance->dbw);
3802 BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
3804 uint256 hash = wtxOld.GetHash();
3805 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
3806 if (mi != walletInstance->mapWallet.end())
3808 const CWalletTx* copyFrom = &wtxOld;
3809 CWalletTx* copyTo = &mi->second;
3810 copyTo->mapValue = copyFrom->mapValue;
3811 copyTo->vOrderForm = copyFrom->vOrderForm;
3812 copyTo->nTimeReceived = copyFrom->nTimeReceived;
3813 copyTo->nTimeSmart = copyFrom->nTimeSmart;
3814 copyTo->fFromMe = copyFrom->fFromMe;
3815 copyTo->strFromAccount = copyFrom->strFromAccount;
3816 copyTo->nOrderPos = copyFrom->nOrderPos;
3817 walletdb.WriteTx(*copyTo);
3822 walletInstance->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
3825 LOCK(walletInstance->cs_wallet);
3826 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
3827 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
3828 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
3831 return walletInstance;
3834 bool CWallet::InitLoadWallet()
3836 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
3837 pwalletMain = NULL;
3838 LogPrintf("Wallet disabled!\n");
3839 return true;
3842 std::string walletFile = GetArg("-wallet", DEFAULT_WALLET_DAT);
3844 if (boost::filesystem::path(walletFile).filename() != walletFile) {
3845 return InitError(_("-wallet parameter must only specify a filename (not a path)"));
3846 } else if (SanitizeString(walletFile, SAFE_CHARS_FILENAME) != walletFile) {
3847 return InitError(_("Invalid characters in -wallet filename"));
3850 CWallet * const pwallet = CreateWalletFromFile(walletFile);
3851 if (!pwallet) {
3852 return false;
3854 pwalletMain = pwallet;
3856 return true;
3859 std::atomic<bool> CWallet::fFlushScheduled(false);
3861 void CWallet::postInitProcess(CScheduler& scheduler)
3863 // Add wallet transactions that aren't already in a block to mempool
3864 // Do this here as mempool requires genesis block to be loaded
3865 ReacceptWalletTransactions();
3867 // Run a thread to flush wallet periodically
3868 if (!CWallet::fFlushScheduled.exchange(true)) {
3869 scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
3873 bool CWallet::ParameterInteraction()
3875 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
3876 return true;
3878 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && SoftSetBoolArg("-walletbroadcast", false)) {
3879 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
3882 if (GetBoolArg("-salvagewallet", false) && SoftSetBoolArg("-rescan", true)) {
3883 // Rewrite just private keys: rescan to find transactions
3884 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
3887 // -zapwallettx implies a rescan
3888 if (GetBoolArg("-zapwallettxes", false) && SoftSetBoolArg("-rescan", true)) {
3889 LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
3892 if (GetBoolArg("-sysperms", false))
3893 return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
3894 if (GetArg("-prune", 0) && GetBoolArg("-rescan", false))
3895 return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
3897 if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB)
3898 InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
3899 _("The wallet will avoid paying less than the minimum relay fee."));
3901 if (IsArgSet("-mintxfee"))
3903 CAmount n = 0;
3904 if (!ParseMoney(GetArg("-mintxfee", ""), n) || 0 == n)
3905 return InitError(AmountErrMsg("mintxfee", GetArg("-mintxfee", "")));
3906 if (n > HIGH_TX_FEE_PER_KB)
3907 InitWarning(AmountHighWarn("-mintxfee") + " " +
3908 _("This is the minimum transaction fee you pay on every transaction."));
3909 CWallet::minTxFee = CFeeRate(n);
3911 if (IsArgSet("-fallbackfee"))
3913 CAmount nFeePerK = 0;
3914 if (!ParseMoney(GetArg("-fallbackfee", ""), nFeePerK))
3915 return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), GetArg("-fallbackfee", "")));
3916 if (nFeePerK > HIGH_TX_FEE_PER_KB)
3917 InitWarning(AmountHighWarn("-fallbackfee") + " " +
3918 _("This is the transaction fee you may pay when fee estimates are not available."));
3919 CWallet::fallbackFee = CFeeRate(nFeePerK);
3921 if (IsArgSet("-paytxfee"))
3923 CAmount nFeePerK = 0;
3924 if (!ParseMoney(GetArg("-paytxfee", ""), nFeePerK))
3925 return InitError(AmountErrMsg("paytxfee", GetArg("-paytxfee", "")));
3926 if (nFeePerK > HIGH_TX_FEE_PER_KB)
3927 InitWarning(AmountHighWarn("-paytxfee") + " " +
3928 _("This is the transaction fee you will pay if you send a transaction."));
3930 payTxFee = CFeeRate(nFeePerK, 1000);
3931 if (payTxFee < ::minRelayTxFee)
3933 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
3934 GetArg("-paytxfee", ""), ::minRelayTxFee.ToString()));
3937 if (IsArgSet("-maxtxfee"))
3939 CAmount nMaxFee = 0;
3940 if (!ParseMoney(GetArg("-maxtxfee", ""), nMaxFee))
3941 return InitError(AmountErrMsg("maxtxfee", GetArg("-maxtxfee", "")));
3942 if (nMaxFee > HIGH_MAX_TX_FEE)
3943 InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
3944 maxTxFee = nMaxFee;
3945 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
3947 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
3948 GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString()));
3951 nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
3952 bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
3953 fWalletRbf = GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
3955 return true;
3958 bool CWallet::BackupWallet(const std::string& strDest)
3960 return dbw->Backup(strDest);
3963 CKeyPool::CKeyPool()
3965 nTime = GetTime();
3966 fInternal = false;
3969 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
3971 nTime = GetTime();
3972 vchPubKey = vchPubKeyIn;
3973 fInternal = internalIn;
3976 CWalletKey::CWalletKey(int64_t nExpires)
3978 nTimeCreated = (nExpires ? GetTime() : 0);
3979 nTimeExpires = nExpires;
3982 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
3984 // Update the tx's hashBlock
3985 hashBlock = pindex->GetBlockHash();
3987 // set the position of the transaction in the block
3988 nIndex = posInBlock;
3991 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
3993 if (hashUnset())
3994 return 0;
3996 AssertLockHeld(cs_main);
3998 // Find the block it claims to be in
3999 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4000 if (mi == mapBlockIndex.end())
4001 return 0;
4002 CBlockIndex* pindex = (*mi).second;
4003 if (!pindex || !chainActive.Contains(pindex))
4004 return 0;
4006 pindexRet = pindex;
4007 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4010 int CMerkleTx::GetBlocksToMaturity() const
4012 if (!IsCoinBase())
4013 return 0;
4014 return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4018 bool CMerkleTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
4020 return ::AcceptToMemoryPool(mempool, state, tx, true, NULL, NULL, false, nAbsurdFee);