CWalletDB: Store the update counter per wallet
[bitcoinplatinum.git] / src / wallet / wallet.cpp
blob9d49b72308dd5aa00f648ba9161b86a3e044c6ab
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::TransactionCanBeAbandoned(const uint256& hashTx) const
987 LOCK2(cs_main, cs_wallet);
988 const CWalletTx* wtx = GetWalletTx(hashTx);
989 return wtx && !wtx->isAbandoned() && wtx->GetDepthInMainChain() <= 0 && !wtx->InMempool();
992 bool CWallet::AbandonTransaction(const uint256& hashTx)
994 LOCK2(cs_main, cs_wallet);
996 CWalletDB walletdb(*dbw, "r+");
998 std::set<uint256> todo;
999 std::set<uint256> done;
1001 // Can't mark abandoned if confirmed or in mempool
1002 assert(mapWallet.count(hashTx));
1003 CWalletTx& origtx = mapWallet[hashTx];
1004 if (origtx.GetDepthInMainChain() > 0 || origtx.InMempool()) {
1005 return false;
1008 todo.insert(hashTx);
1010 while (!todo.empty()) {
1011 uint256 now = *todo.begin();
1012 todo.erase(now);
1013 done.insert(now);
1014 assert(mapWallet.count(now));
1015 CWalletTx& wtx = mapWallet[now];
1016 int currentconfirm = wtx.GetDepthInMainChain();
1017 // If the orig tx was not in block, none of its spends can be
1018 assert(currentconfirm <= 0);
1019 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1020 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1021 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1022 assert(!wtx.InMempool());
1023 wtx.nIndex = -1;
1024 wtx.setAbandoned();
1025 wtx.MarkDirty();
1026 walletdb.WriteTx(wtx);
1027 NotifyTransactionChanged(this, wtx.GetHash(), CT_UPDATED);
1028 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1029 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(hashTx, 0));
1030 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1031 if (!done.count(iter->second)) {
1032 todo.insert(iter->second);
1034 iter++;
1036 // If a transaction changes 'conflicted' state, that changes the balance
1037 // available of the outputs it spends. So force those to be recomputed
1038 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
1040 if (mapWallet.count(txin.prevout.hash))
1041 mapWallet[txin.prevout.hash].MarkDirty();
1046 return true;
1049 void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx)
1051 LOCK2(cs_main, cs_wallet);
1053 int conflictconfirms = 0;
1054 if (mapBlockIndex.count(hashBlock)) {
1055 CBlockIndex* pindex = mapBlockIndex[hashBlock];
1056 if (chainActive.Contains(pindex)) {
1057 conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1);
1060 // If number of conflict confirms cannot be determined, this means
1061 // that the block is still unknown or not yet part of the main chain,
1062 // for example when loading the wallet during a reindex. Do nothing in that
1063 // case.
1064 if (conflictconfirms >= 0)
1065 return;
1067 // Do not flush the wallet here for performance reasons
1068 CWalletDB walletdb(*dbw, "r+", false);
1070 std::set<uint256> todo;
1071 std::set<uint256> done;
1073 todo.insert(hashTx);
1075 while (!todo.empty()) {
1076 uint256 now = *todo.begin();
1077 todo.erase(now);
1078 done.insert(now);
1079 assert(mapWallet.count(now));
1080 CWalletTx& wtx = mapWallet[now];
1081 int currentconfirm = wtx.GetDepthInMainChain();
1082 if (conflictconfirms < currentconfirm) {
1083 // Block is 'more conflicted' than current confirm; update.
1084 // Mark transaction as conflicted with this block.
1085 wtx.nIndex = -1;
1086 wtx.hashBlock = hashBlock;
1087 wtx.MarkDirty();
1088 walletdb.WriteTx(wtx);
1089 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1090 TxSpends::const_iterator iter = mapTxSpends.lower_bound(COutPoint(now, 0));
1091 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1092 if (!done.count(iter->second)) {
1093 todo.insert(iter->second);
1095 iter++;
1097 // If a transaction changes 'conflicted' state, that changes the balance
1098 // available of the outputs it spends. So force those to be recomputed
1099 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
1101 if (mapWallet.count(txin.prevout.hash))
1102 mapWallet[txin.prevout.hash].MarkDirty();
1108 void CWallet::SyncTransaction(const CTransactionRef& ptx, const CBlockIndex *pindex, int posInBlock) {
1109 const CTransaction& tx = *ptx;
1111 if (!AddToWalletIfInvolvingMe(ptx, pindex, posInBlock, true))
1112 return; // Not one of ours
1114 // If a transaction changes 'conflicted' state, that changes the balance
1115 // available of the outputs it spends. So force those to be
1116 // recomputed, also:
1117 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1119 if (mapWallet.count(txin.prevout.hash))
1120 mapWallet[txin.prevout.hash].MarkDirty();
1124 void CWallet::TransactionAddedToMempool(const CTransactionRef& ptx) {
1125 LOCK2(cs_main, cs_wallet);
1126 SyncTransaction(ptx);
1129 void CWallet::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex *pindex, const std::vector<CTransactionRef>& vtxConflicted) {
1130 LOCK2(cs_main, cs_wallet);
1131 // TODO: Temporarily ensure that mempool removals are notified before
1132 // connected transactions. This shouldn't matter, but the abandoned
1133 // state of transactions in our wallet is currently cleared when we
1134 // receive another notification and there is a race condition where
1135 // notification of a connected conflict might cause an outside process
1136 // to abandon a transaction and then have it inadvertently cleared by
1137 // the notification that the conflicted transaction was evicted.
1139 for (const CTransactionRef& ptx : vtxConflicted) {
1140 SyncTransaction(ptx);
1142 for (size_t i = 0; i < pblock->vtx.size(); i++) {
1143 SyncTransaction(pblock->vtx[i], pindex, i);
1147 void CWallet::BlockDisconnected(const std::shared_ptr<const CBlock>& pblock) {
1148 LOCK2(cs_main, cs_wallet);
1150 for (const CTransactionRef& ptx : pblock->vtx) {
1151 SyncTransaction(ptx);
1157 isminetype CWallet::IsMine(const CTxIn &txin) const
1160 LOCK(cs_wallet);
1161 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1162 if (mi != mapWallet.end())
1164 const CWalletTx& prev = (*mi).second;
1165 if (txin.prevout.n < prev.tx->vout.size())
1166 return IsMine(prev.tx->vout[txin.prevout.n]);
1169 return ISMINE_NO;
1172 // Note that this function doesn't distinguish between a 0-valued input,
1173 // and a not-"is mine" (according to the filter) input.
1174 CAmount CWallet::GetDebit(const CTxIn &txin, const isminefilter& filter) const
1177 LOCK(cs_wallet);
1178 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash);
1179 if (mi != mapWallet.end())
1181 const CWalletTx& prev = (*mi).second;
1182 if (txin.prevout.n < prev.tx->vout.size())
1183 if (IsMine(prev.tx->vout[txin.prevout.n]) & filter)
1184 return prev.tx->vout[txin.prevout.n].nValue;
1187 return 0;
1190 isminetype CWallet::IsMine(const CTxOut& txout) const
1192 return ::IsMine(*this, txout.scriptPubKey);
1195 CAmount CWallet::GetCredit(const CTxOut& txout, const isminefilter& filter) const
1197 if (!MoneyRange(txout.nValue))
1198 throw std::runtime_error(std::string(__func__) + ": value out of range");
1199 return ((IsMine(txout) & filter) ? txout.nValue : 0);
1202 bool CWallet::IsChange(const CTxOut& txout) const
1204 // TODO: fix handling of 'change' outputs. The assumption is that any
1205 // payment to a script that is ours, but is not in the address book
1206 // is change. That assumption is likely to break when we implement multisignature
1207 // wallets that return change back into a multi-signature-protected address;
1208 // a better way of identifying which outputs are 'the send' and which are
1209 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1210 // which output, if any, was change).
1211 if (::IsMine(*this, txout.scriptPubKey))
1213 CTxDestination address;
1214 if (!ExtractDestination(txout.scriptPubKey, address))
1215 return true;
1217 LOCK(cs_wallet);
1218 if (!mapAddressBook.count(address))
1219 return true;
1221 return false;
1224 CAmount CWallet::GetChange(const CTxOut& txout) const
1226 if (!MoneyRange(txout.nValue))
1227 throw std::runtime_error(std::string(__func__) + ": value out of range");
1228 return (IsChange(txout) ? txout.nValue : 0);
1231 bool CWallet::IsMine(const CTransaction& tx) const
1233 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1234 if (IsMine(txout))
1235 return true;
1236 return false;
1239 bool CWallet::IsFromMe(const CTransaction& tx) const
1241 return (GetDebit(tx, ISMINE_ALL) > 0);
1244 CAmount CWallet::GetDebit(const CTransaction& tx, const isminefilter& filter) const
1246 CAmount nDebit = 0;
1247 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1249 nDebit += GetDebit(txin, filter);
1250 if (!MoneyRange(nDebit))
1251 throw std::runtime_error(std::string(__func__) + ": value out of range");
1253 return nDebit;
1256 bool CWallet::IsAllFromMe(const CTransaction& tx, const isminefilter& filter) const
1258 LOCK(cs_wallet);
1260 BOOST_FOREACH(const CTxIn& txin, tx.vin)
1262 auto mi = mapWallet.find(txin.prevout.hash);
1263 if (mi == mapWallet.end())
1264 return false; // any unknown inputs can't be from us
1266 const CWalletTx& prev = (*mi).second;
1268 if (txin.prevout.n >= prev.tx->vout.size())
1269 return false; // invalid input!
1271 if (!(IsMine(prev.tx->vout[txin.prevout.n]) & filter))
1272 return false;
1274 return true;
1277 CAmount CWallet::GetCredit(const CTransaction& tx, const isminefilter& filter) const
1279 CAmount nCredit = 0;
1280 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1282 nCredit += GetCredit(txout, filter);
1283 if (!MoneyRange(nCredit))
1284 throw std::runtime_error(std::string(__func__) + ": value out of range");
1286 return nCredit;
1289 CAmount CWallet::GetChange(const CTransaction& tx) const
1291 CAmount nChange = 0;
1292 BOOST_FOREACH(const CTxOut& txout, tx.vout)
1294 nChange += GetChange(txout);
1295 if (!MoneyRange(nChange))
1296 throw std::runtime_error(std::string(__func__) + ": value out of range");
1298 return nChange;
1301 CPubKey CWallet::GenerateNewHDMasterKey()
1303 CKey key;
1304 key.MakeNewKey(true);
1306 int64_t nCreationTime = GetTime();
1307 CKeyMetadata metadata(nCreationTime);
1309 // calculate the pubkey
1310 CPubKey pubkey = key.GetPubKey();
1311 assert(key.VerifyPubKey(pubkey));
1313 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1314 metadata.hdKeypath = "m";
1315 metadata.hdMasterKeyID = pubkey.GetID();
1318 LOCK(cs_wallet);
1320 // mem store the metadata
1321 mapKeyMetadata[pubkey.GetID()] = metadata;
1323 // write the key&metadata to the database
1324 if (!AddKeyPubKey(key, pubkey))
1325 throw std::runtime_error(std::string(__func__) + ": AddKeyPubKey failed");
1328 return pubkey;
1331 bool CWallet::SetHDMasterKey(const CPubKey& pubkey)
1333 LOCK(cs_wallet);
1334 // store the keyid (hash160) together with
1335 // the child index counter in the database
1336 // as a hdchain object
1337 CHDChain newHdChain;
1338 newHdChain.nVersion = CanSupportFeature(FEATURE_HD_SPLIT) ? CHDChain::VERSION_HD_CHAIN_SPLIT : CHDChain::VERSION_HD_BASE;
1339 newHdChain.masterKeyID = pubkey.GetID();
1340 SetHDChain(newHdChain, false);
1342 return true;
1345 bool CWallet::SetHDChain(const CHDChain& chain, bool memonly)
1347 LOCK(cs_wallet);
1348 if (!memonly && !CWalletDB(*dbw).WriteHDChain(chain))
1349 throw std::runtime_error(std::string(__func__) + ": writing chain failed");
1351 hdChain = chain;
1352 return true;
1355 bool CWallet::IsHDEnabled() const
1357 return !hdChain.masterKeyID.IsNull();
1360 int64_t CWalletTx::GetTxTime() const
1362 int64_t n = nTimeSmart;
1363 return n ? n : nTimeReceived;
1366 int CWalletTx::GetRequestCount() const
1368 // Returns -1 if it wasn't being tracked
1369 int nRequests = -1;
1371 LOCK(pwallet->cs_wallet);
1372 if (IsCoinBase())
1374 // Generated block
1375 if (!hashUnset())
1377 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock);
1378 if (mi != pwallet->mapRequestCount.end())
1379 nRequests = (*mi).second;
1382 else
1384 // Did anyone request this transaction?
1385 std::map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash());
1386 if (mi != pwallet->mapRequestCount.end())
1388 nRequests = (*mi).second;
1390 // How about the block it's in?
1391 if (nRequests == 0 && !hashUnset())
1393 std::map<uint256, int>::const_iterator _mi = pwallet->mapRequestCount.find(hashBlock);
1394 if (_mi != pwallet->mapRequestCount.end())
1395 nRequests = (*_mi).second;
1396 else
1397 nRequests = 1; // If it's in someone else's block it must have got out
1402 return nRequests;
1405 void CWalletTx::GetAmounts(std::list<COutputEntry>& listReceived,
1406 std::list<COutputEntry>& listSent, CAmount& nFee, std::string& strSentAccount, const isminefilter& filter) const
1408 nFee = 0;
1409 listReceived.clear();
1410 listSent.clear();
1411 strSentAccount = strFromAccount;
1413 // Compute fee:
1414 CAmount nDebit = GetDebit(filter);
1415 if (nDebit > 0) // debit>0 means we signed/sent this transaction
1417 CAmount nValueOut = tx->GetValueOut();
1418 nFee = nDebit - nValueOut;
1421 // Sent/received.
1422 for (unsigned int i = 0; i < tx->vout.size(); ++i)
1424 const CTxOut& txout = tx->vout[i];
1425 isminetype fIsMine = pwallet->IsMine(txout);
1426 // Only need to handle txouts if AT LEAST one of these is true:
1427 // 1) they debit from us (sent)
1428 // 2) the output is to us (received)
1429 if (nDebit > 0)
1431 // Don't report 'change' txouts
1432 if (pwallet->IsChange(txout))
1433 continue;
1435 else if (!(fIsMine & filter))
1436 continue;
1438 // In either case, we need to get the destination address
1439 CTxDestination address;
1441 if (!ExtractDestination(txout.scriptPubKey, address) && !txout.scriptPubKey.IsUnspendable())
1443 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1444 this->GetHash().ToString());
1445 address = CNoDestination();
1448 COutputEntry output = {address, txout.nValue, (int)i};
1450 // If we are debited by the transaction, add the output as a "sent" entry
1451 if (nDebit > 0)
1452 listSent.push_back(output);
1454 // If we are receiving the output, add it as a "received" entry
1455 if (fIsMine & filter)
1456 listReceived.push_back(output);
1462 * Scan the block chain (starting in pindexStart) for transactions
1463 * from or to us. If fUpdate is true, found transactions that already
1464 * exist in the wallet will be updated.
1466 * Returns null if scan was successful. Otherwise, if a complete rescan was not
1467 * possible (due to pruning or corruption), returns pointer to the most recent
1468 * block that could not be scanned.
1470 CBlockIndex* CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate)
1472 int64_t nNow = GetTime();
1473 const CChainParams& chainParams = Params();
1475 CBlockIndex* pindex = pindexStart;
1476 CBlockIndex* ret = nullptr;
1478 LOCK2(cs_main, cs_wallet);
1479 fAbortRescan = false;
1480 fScanningWallet = true;
1482 // no need to read and scan block, if block was created before
1483 // our wallet birthday (as adjusted for block time variability)
1484 while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - TIMESTAMP_WINDOW)))
1485 pindex = chainActive.Next(pindex);
1487 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1488 double dProgressStart = GuessVerificationProgress(chainParams.TxData(), pindex);
1489 double dProgressTip = GuessVerificationProgress(chainParams.TxData(), chainActive.Tip());
1490 while (pindex && !fAbortRescan)
1492 if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0)
1493 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams.TxData(), pindex) - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1494 if (GetTime() >= nNow + 60) {
1495 nNow = GetTime();
1496 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1499 CBlock block;
1500 if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) {
1501 for (size_t posInBlock = 0; posInBlock < block.vtx.size(); ++posInBlock) {
1502 AddToWalletIfInvolvingMe(block.vtx[posInBlock], pindex, posInBlock, fUpdate);
1504 } else {
1505 ret = pindex;
1507 pindex = chainActive.Next(pindex);
1509 if (pindex && fAbortRescan) {
1510 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex->nHeight, GuessVerificationProgress(chainParams.TxData(), pindex));
1512 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1514 fScanningWallet = false;
1516 return ret;
1519 void CWallet::ReacceptWalletTransactions()
1521 // If transactions aren't being broadcasted, don't let them into local mempool either
1522 if (!fBroadcastTransactions)
1523 return;
1524 LOCK2(cs_main, cs_wallet);
1525 std::map<int64_t, CWalletTx*> mapSorted;
1527 // Sort pending wallet transactions based on their initial wallet insertion order
1528 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1530 const uint256& wtxid = item.first;
1531 CWalletTx& wtx = item.second;
1532 assert(wtx.GetHash() == wtxid);
1534 int nDepth = wtx.GetDepthInMainChain();
1536 if (!wtx.IsCoinBase() && (nDepth == 0 && !wtx.isAbandoned())) {
1537 mapSorted.insert(std::make_pair(wtx.nOrderPos, &wtx));
1541 // Try to add wallet transactions to memory pool
1542 BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx*)& item, mapSorted)
1544 CWalletTx& wtx = *(item.second);
1546 LOCK(mempool.cs);
1547 CValidationState state;
1548 wtx.AcceptToMemoryPool(maxTxFee, state);
1552 bool CWalletTx::RelayWalletTransaction(CConnman* connman)
1554 assert(pwallet->GetBroadcastTransactions());
1555 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1557 CValidationState state;
1558 /* GetDepthInMainChain already catches known conflicts. */
1559 if (InMempool() || AcceptToMemoryPool(maxTxFee, state)) {
1560 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1561 if (connman) {
1562 CInv inv(MSG_TX, GetHash());
1563 connman->ForEachNode([&inv](CNode* pnode)
1565 pnode->PushInventory(inv);
1567 return true;
1571 return false;
1574 std::set<uint256> CWalletTx::GetConflicts() const
1576 std::set<uint256> result;
1577 if (pwallet != NULL)
1579 uint256 myHash = GetHash();
1580 result = pwallet->GetConflicts(myHash);
1581 result.erase(myHash);
1583 return result;
1586 CAmount CWalletTx::GetDebit(const isminefilter& filter) const
1588 if (tx->vin.empty())
1589 return 0;
1591 CAmount debit = 0;
1592 if(filter & ISMINE_SPENDABLE)
1594 if (fDebitCached)
1595 debit += nDebitCached;
1596 else
1598 nDebitCached = pwallet->GetDebit(*this, ISMINE_SPENDABLE);
1599 fDebitCached = true;
1600 debit += nDebitCached;
1603 if(filter & ISMINE_WATCH_ONLY)
1605 if(fWatchDebitCached)
1606 debit += nWatchDebitCached;
1607 else
1609 nWatchDebitCached = pwallet->GetDebit(*this, ISMINE_WATCH_ONLY);
1610 fWatchDebitCached = true;
1611 debit += nWatchDebitCached;
1614 return debit;
1617 CAmount CWalletTx::GetCredit(const isminefilter& filter) const
1619 // Must wait until coinbase is safely deep enough in the chain before valuing it
1620 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1621 return 0;
1623 CAmount credit = 0;
1624 if (filter & ISMINE_SPENDABLE)
1626 // GetBalance can assume transactions in mapWallet won't change
1627 if (fCreditCached)
1628 credit += nCreditCached;
1629 else
1631 nCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1632 fCreditCached = true;
1633 credit += nCreditCached;
1636 if (filter & ISMINE_WATCH_ONLY)
1638 if (fWatchCreditCached)
1639 credit += nWatchCreditCached;
1640 else
1642 nWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1643 fWatchCreditCached = true;
1644 credit += nWatchCreditCached;
1647 return credit;
1650 CAmount CWalletTx::GetImmatureCredit(bool fUseCache) const
1652 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1654 if (fUseCache && fImmatureCreditCached)
1655 return nImmatureCreditCached;
1656 nImmatureCreditCached = pwallet->GetCredit(*this, ISMINE_SPENDABLE);
1657 fImmatureCreditCached = true;
1658 return nImmatureCreditCached;
1661 return 0;
1664 CAmount CWalletTx::GetAvailableCredit(bool fUseCache) const
1666 if (pwallet == 0)
1667 return 0;
1669 // Must wait until coinbase is safely deep enough in the chain before valuing it
1670 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1671 return 0;
1673 if (fUseCache && fAvailableCreditCached)
1674 return nAvailableCreditCached;
1676 CAmount nCredit = 0;
1677 uint256 hashTx = GetHash();
1678 for (unsigned int i = 0; i < tx->vout.size(); i++)
1680 if (!pwallet->IsSpent(hashTx, i))
1682 const CTxOut &txout = tx->vout[i];
1683 nCredit += pwallet->GetCredit(txout, ISMINE_SPENDABLE);
1684 if (!MoneyRange(nCredit))
1685 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1689 nAvailableCreditCached = nCredit;
1690 fAvailableCreditCached = true;
1691 return nCredit;
1694 CAmount CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache) const
1696 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1698 if (fUseCache && fImmatureWatchCreditCached)
1699 return nImmatureWatchCreditCached;
1700 nImmatureWatchCreditCached = pwallet->GetCredit(*this, ISMINE_WATCH_ONLY);
1701 fImmatureWatchCreditCached = true;
1702 return nImmatureWatchCreditCached;
1705 return 0;
1708 CAmount CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache) const
1710 if (pwallet == 0)
1711 return 0;
1713 // Must wait until coinbase is safely deep enough in the chain before valuing it
1714 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1715 return 0;
1717 if (fUseCache && fAvailableWatchCreditCached)
1718 return nAvailableWatchCreditCached;
1720 CAmount nCredit = 0;
1721 for (unsigned int i = 0; i < tx->vout.size(); i++)
1723 if (!pwallet->IsSpent(GetHash(), i))
1725 const CTxOut &txout = tx->vout[i];
1726 nCredit += pwallet->GetCredit(txout, ISMINE_WATCH_ONLY);
1727 if (!MoneyRange(nCredit))
1728 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1732 nAvailableWatchCreditCached = nCredit;
1733 fAvailableWatchCreditCached = true;
1734 return nCredit;
1737 CAmount CWalletTx::GetChange() const
1739 if (fChangeCached)
1740 return nChangeCached;
1741 nChangeCached = pwallet->GetChange(*this);
1742 fChangeCached = true;
1743 return nChangeCached;
1746 bool CWalletTx::InMempool() const
1748 LOCK(mempool.cs);
1749 return mempool.exists(GetHash());
1752 bool CWalletTx::IsTrusted() const
1754 // Quick answer in most cases
1755 if (!CheckFinalTx(*this))
1756 return false;
1757 int nDepth = GetDepthInMainChain();
1758 if (nDepth >= 1)
1759 return true;
1760 if (nDepth < 0)
1761 return false;
1762 if (!bSpendZeroConfChange || !IsFromMe(ISMINE_ALL)) // using wtx's cached debit
1763 return false;
1765 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1766 if (!InMempool())
1767 return false;
1769 // Trusted if all inputs are from us and are in the mempool:
1770 BOOST_FOREACH(const CTxIn& txin, tx->vin)
1772 // Transactions not sent by us: not trusted
1773 const CWalletTx* parent = pwallet->GetWalletTx(txin.prevout.hash);
1774 if (parent == NULL)
1775 return false;
1776 const CTxOut& parentOut = parent->tx->vout[txin.prevout.n];
1777 if (pwallet->IsMine(parentOut) != ISMINE_SPENDABLE)
1778 return false;
1780 return true;
1783 bool CWalletTx::IsEquivalentTo(const CWalletTx& _tx) const
1785 CMutableTransaction tx1 = *this->tx;
1786 CMutableTransaction tx2 = *_tx.tx;
1787 for (auto& txin : tx1.vin) txin.scriptSig = CScript();
1788 for (auto& txin : tx2.vin) txin.scriptSig = CScript();
1789 return CTransaction(tx1) == CTransaction(tx2);
1792 std::vector<uint256> CWallet::ResendWalletTransactionsBefore(int64_t nTime, CConnman* connman)
1794 std::vector<uint256> result;
1796 LOCK(cs_wallet);
1797 // Sort them in chronological order
1798 std::multimap<unsigned int, CWalletTx*> mapSorted;
1799 BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet)
1801 CWalletTx& wtx = item.second;
1802 // Don't rebroadcast if newer than nTime:
1803 if (wtx.nTimeReceived > nTime)
1804 continue;
1805 mapSorted.insert(std::make_pair(wtx.nTimeReceived, &wtx));
1807 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted)
1809 CWalletTx& wtx = *item.second;
1810 if (wtx.RelayWalletTransaction(connman))
1811 result.push_back(wtx.GetHash());
1813 return result;
1816 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime, CConnman* connman)
1818 // Do this infrequently and randomly to avoid giving away
1819 // that these are our transactions.
1820 if (GetTime() < nNextResend || !fBroadcastTransactions)
1821 return;
1822 bool fFirst = (nNextResend == 0);
1823 nNextResend = GetTime() + GetRand(30 * 60);
1824 if (fFirst)
1825 return;
1827 // Only do it if there's been a new block since last time
1828 if (nBestBlockTime < nLastResend)
1829 return;
1830 nLastResend = GetTime();
1832 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1833 // block was found:
1834 std::vector<uint256> relayed = ResendWalletTransactionsBefore(nBestBlockTime-5*60, connman);
1835 if (!relayed.empty())
1836 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
1839 /** @} */ // end of mapWallet
1844 /** @defgroup Actions
1846 * @{
1850 CAmount CWallet::GetBalance() const
1852 CAmount nTotal = 0;
1854 LOCK2(cs_main, cs_wallet);
1855 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1857 const CWalletTx* pcoin = &(*it).second;
1858 if (pcoin->IsTrusted())
1859 nTotal += pcoin->GetAvailableCredit();
1863 return nTotal;
1866 CAmount CWallet::GetUnconfirmedBalance() const
1868 CAmount nTotal = 0;
1870 LOCK2(cs_main, cs_wallet);
1871 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1873 const CWalletTx* pcoin = &(*it).second;
1874 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1875 nTotal += pcoin->GetAvailableCredit();
1878 return nTotal;
1881 CAmount CWallet::GetImmatureBalance() const
1883 CAmount nTotal = 0;
1885 LOCK2(cs_main, cs_wallet);
1886 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1888 const CWalletTx* pcoin = &(*it).second;
1889 nTotal += pcoin->GetImmatureCredit();
1892 return nTotal;
1895 CAmount CWallet::GetWatchOnlyBalance() const
1897 CAmount nTotal = 0;
1899 LOCK2(cs_main, cs_wallet);
1900 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1902 const CWalletTx* pcoin = &(*it).second;
1903 if (pcoin->IsTrusted())
1904 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1908 return nTotal;
1911 CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const
1913 CAmount nTotal = 0;
1915 LOCK2(cs_main, cs_wallet);
1916 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1918 const CWalletTx* pcoin = &(*it).second;
1919 if (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0 && pcoin->InMempool())
1920 nTotal += pcoin->GetAvailableWatchOnlyCredit();
1923 return nTotal;
1926 CAmount CWallet::GetImmatureWatchOnlyBalance() const
1928 CAmount nTotal = 0;
1930 LOCK2(cs_main, cs_wallet);
1931 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
1933 const CWalletTx* pcoin = &(*it).second;
1934 nTotal += pcoin->GetImmatureWatchOnlyCredit();
1937 return nTotal;
1940 // Calculate total balance in a different way from GetBalance. The biggest
1941 // difference is that GetBalance sums up all unspent TxOuts paying to the
1942 // wallet, while this sums up both spent and unspent TxOuts paying to the
1943 // wallet, and then subtracts the values of TxIns spending from the wallet. This
1944 // also has fewer restrictions on which unconfirmed transactions are considered
1945 // trusted.
1946 CAmount CWallet::GetLegacyBalance(const isminefilter& filter, int minDepth, const std::string* account) const
1948 LOCK2(cs_main, cs_wallet);
1950 CAmount balance = 0;
1951 for (const auto& entry : mapWallet) {
1952 const CWalletTx& wtx = entry.second;
1953 const int depth = wtx.GetDepthInMainChain();
1954 if (depth < 0 || !CheckFinalTx(*wtx.tx) || wtx.GetBlocksToMaturity() > 0) {
1955 continue;
1958 // Loop through tx outputs and add incoming payments. For outgoing txs,
1959 // treat change outputs specially, as part of the amount debited.
1960 CAmount debit = wtx.GetDebit(filter);
1961 const bool outgoing = debit > 0;
1962 for (const CTxOut& out : wtx.tx->vout) {
1963 if (outgoing && IsChange(out)) {
1964 debit -= out.nValue;
1965 } else if (IsMine(out) & filter && depth >= minDepth && (!account || *account == GetAccountName(out.scriptPubKey))) {
1966 balance += out.nValue;
1970 // For outgoing txs, subtract amount debited.
1971 if (outgoing && (!account || *account == wtx.strFromAccount)) {
1972 balance -= debit;
1976 if (account) {
1977 balance += CWalletDB(*dbw).GetAccountCreditDebit(*account);
1980 return balance;
1983 CAmount CWallet::GetAvailableBalance(const CCoinControl* coinControl) const
1985 LOCK2(cs_main, cs_wallet);
1987 CAmount balance = 0;
1988 std::vector<COutput> vCoins;
1989 AvailableCoins(vCoins, true, coinControl);
1990 for (const COutput& out : vCoins) {
1991 if (out.fSpendable) {
1992 balance += out.tx->tx->vout[out.i].nValue;
1995 return balance;
1998 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
2000 vCoins.clear();
2003 LOCK2(cs_main, cs_wallet);
2005 CAmount nTotal = 0;
2007 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it)
2009 const uint256& wtxid = it->first;
2010 const CWalletTx* pcoin = &(*it).second;
2012 if (!CheckFinalTx(*pcoin))
2013 continue;
2015 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
2016 continue;
2018 int nDepth = pcoin->GetDepthInMainChain();
2019 if (nDepth < 0)
2020 continue;
2022 // We should not consider coins which aren't at least in our mempool
2023 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2024 if (nDepth == 0 && !pcoin->InMempool())
2025 continue;
2027 bool safeTx = pcoin->IsTrusted();
2029 // We should not consider coins from transactions that are replacing
2030 // other transactions.
2032 // Example: There is a transaction A which is replaced by bumpfee
2033 // transaction B. In this case, we want to prevent creation of
2034 // a transaction B' which spends an output of B.
2036 // Reason: If transaction A were initially confirmed, transactions B
2037 // and B' would no longer be valid, so the user would have to create
2038 // a new transaction C to replace B'. However, in the case of a
2039 // one-block reorg, transactions B' and C might BOTH be accepted,
2040 // when the user only wanted one of them. Specifically, there could
2041 // be a 1-block reorg away from the chain where transactions A and C
2042 // were accepted to another chain where B, B', and C were all
2043 // accepted.
2044 if (nDepth == 0 && pcoin->mapValue.count("replaces_txid")) {
2045 safeTx = false;
2048 // Similarly, we should not consider coins from transactions that
2049 // have been replaced. In the example above, we would want to prevent
2050 // creation of a transaction A' spending an output of A, because if
2051 // transaction B were initially confirmed, conflicting with A and
2052 // A', we wouldn't want to the user to create a transaction D
2053 // intending to replace A', but potentially resulting in a scenario
2054 // where A, A', and D could all be accepted (instead of just B and
2055 // D, or just A and A' like the user would want).
2056 if (nDepth == 0 && pcoin->mapValue.count("replaced_by_txid")) {
2057 safeTx = false;
2060 if (fOnlySafe && !safeTx) {
2061 continue;
2064 if (nDepth < nMinDepth || nDepth > nMaxDepth)
2065 continue;
2067 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++) {
2068 if (pcoin->tx->vout[i].nValue < nMinimumAmount || pcoin->tx->vout[i].nValue > nMaximumAmount)
2069 continue;
2071 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected(COutPoint((*it).first, i)))
2072 continue;
2074 if (IsLockedCoin((*it).first, i))
2075 continue;
2077 if (IsSpent(wtxid, i))
2078 continue;
2080 isminetype mine = IsMine(pcoin->tx->vout[i]);
2082 if (mine == ISMINE_NO) {
2083 continue;
2086 bool fSpendableIn = ((mine & ISMINE_SPENDABLE) != ISMINE_NO) || (coinControl && coinControl->fAllowWatchOnly && (mine & ISMINE_WATCH_SOLVABLE) != ISMINE_NO);
2087 bool fSolvableIn = (mine & (ISMINE_SPENDABLE | ISMINE_WATCH_SOLVABLE)) != ISMINE_NO;
2089 vCoins.push_back(COutput(pcoin, i, nDepth, fSpendableIn, fSolvableIn, safeTx));
2091 // Checks the sum amount of all UTXO's.
2092 if (nMinimumSumAmount != MAX_MONEY) {
2093 nTotal += pcoin->tx->vout[i].nValue;
2095 if (nTotal >= nMinimumSumAmount) {
2096 return;
2100 // Checks the maximum number of UTXO's.
2101 if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2102 return;
2109 std::map<CTxDestination, std::vector<COutput>> CWallet::ListCoins() const
2111 // TODO: Add AssertLockHeld(cs_wallet) here.
2113 // Because the return value from this function contains pointers to
2114 // CWalletTx objects, callers to this function really should acquire the
2115 // cs_wallet lock before calling it. However, the current caller doesn't
2116 // acquire this lock yet. There was an attempt to add the missing lock in
2117 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2118 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2119 // avoid adding some extra complexity to the Qt code.
2121 std::map<CTxDestination, std::vector<COutput>> result;
2123 std::vector<COutput> availableCoins;
2124 AvailableCoins(availableCoins);
2126 LOCK2(cs_main, cs_wallet);
2127 for (auto& coin : availableCoins) {
2128 CTxDestination address;
2129 if (coin.fSpendable &&
2130 ExtractDestination(FindNonChangeParentOutput(*coin.tx->tx, coin.i).scriptPubKey, address)) {
2131 result[address].emplace_back(std::move(coin));
2135 std::vector<COutPoint> lockedCoins;
2136 ListLockedCoins(lockedCoins);
2137 for (const auto& output : lockedCoins) {
2138 auto it = mapWallet.find(output.hash);
2139 if (it != mapWallet.end()) {
2140 int depth = it->second.GetDepthInMainChain();
2141 if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2142 IsMine(it->second.tx->vout[output.n]) == ISMINE_SPENDABLE) {
2143 CTxDestination address;
2144 if (ExtractDestination(FindNonChangeParentOutput(*it->second.tx, output.n).scriptPubKey, address)) {
2145 result[address].emplace_back(
2146 &it->second, output.n, depth, true /* spendable */, true /* solvable */, false /* safe */);
2152 return result;
2155 const CTxOut& CWallet::FindNonChangeParentOutput(const CTransaction& tx, int output) const
2157 const CTransaction* ptx = &tx;
2158 int n = output;
2159 while (IsChange(ptx->vout[n]) && ptx->vin.size() > 0) {
2160 const COutPoint& prevout = ptx->vin[0].prevout;
2161 auto it = mapWallet.find(prevout.hash);
2162 if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.n ||
2163 !IsMine(it->second.tx->vout[prevout.n])) {
2164 break;
2166 ptx = it->second.tx.get();
2167 n = prevout.n;
2169 return ptx->vout[n];
2172 static void ApproximateBestSubset(const std::vector<CInputCoin>& vValue, const CAmount& nTotalLower, const CAmount& nTargetValue,
2173 std::vector<char>& vfBest, CAmount& nBest, int iterations = 1000)
2175 std::vector<char> vfIncluded;
2177 vfBest.assign(vValue.size(), true);
2178 nBest = nTotalLower;
2180 FastRandomContext insecure_rand;
2182 for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++)
2184 vfIncluded.assign(vValue.size(), false);
2185 CAmount nTotal = 0;
2186 bool fReachedTarget = false;
2187 for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++)
2189 for (unsigned int i = 0; i < vValue.size(); i++)
2191 //The solver here uses a randomized algorithm,
2192 //the randomness serves no real security purpose but is just
2193 //needed to prevent degenerate behavior and it is important
2194 //that the rng is fast. We do not use a constant random sequence,
2195 //because there may be some privacy improvement by making
2196 //the selection random.
2197 if (nPass == 0 ? insecure_rand.randbool() : !vfIncluded[i])
2199 nTotal += vValue[i].txout.nValue;
2200 vfIncluded[i] = true;
2201 if (nTotal >= nTargetValue)
2203 fReachedTarget = true;
2204 if (nTotal < nBest)
2206 nBest = nTotal;
2207 vfBest = vfIncluded;
2209 nTotal -= vValue[i].txout.nValue;
2210 vfIncluded[i] = false;
2218 bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, const int nConfMine, const int nConfTheirs, const uint64_t nMaxAncestors, std::vector<COutput> vCoins,
2219 std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet) const
2221 setCoinsRet.clear();
2222 nValueRet = 0;
2224 // List of values less than target
2225 boost::optional<CInputCoin> coinLowestLarger;
2226 std::vector<CInputCoin> vValue;
2227 CAmount nTotalLower = 0;
2229 random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt);
2231 BOOST_FOREACH(const COutput &output, vCoins)
2233 if (!output.fSpendable)
2234 continue;
2236 const CWalletTx *pcoin = output.tx;
2238 if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs))
2239 continue;
2241 if (!mempool.TransactionWithinChainLimit(pcoin->GetHash(), nMaxAncestors))
2242 continue;
2244 int i = output.i;
2246 CInputCoin coin = CInputCoin(pcoin, i);
2248 if (coin.txout.nValue == nTargetValue)
2250 setCoinsRet.insert(coin);
2251 nValueRet += coin.txout.nValue;
2252 return true;
2254 else if (coin.txout.nValue < nTargetValue + MIN_CHANGE)
2256 vValue.push_back(coin);
2257 nTotalLower += coin.txout.nValue;
2259 else if (!coinLowestLarger || coin.txout.nValue < coinLowestLarger->txout.nValue)
2261 coinLowestLarger = coin;
2265 if (nTotalLower == nTargetValue)
2267 for (const auto& input : vValue)
2269 setCoinsRet.insert(input);
2270 nValueRet += input.txout.nValue;
2272 return true;
2275 if (nTotalLower < nTargetValue)
2277 if (!coinLowestLarger)
2278 return false;
2279 setCoinsRet.insert(coinLowestLarger.get());
2280 nValueRet += coinLowestLarger->txout.nValue;
2281 return true;
2284 // Solve subset sum by stochastic approximation
2285 std::sort(vValue.begin(), vValue.end(), CompareValueOnly());
2286 std::reverse(vValue.begin(), vValue.end());
2287 std::vector<char> vfBest;
2288 CAmount nBest;
2290 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2291 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2292 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2294 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2295 // or the next bigger coin is closer), return the bigger coin
2296 if (coinLowestLarger &&
2297 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger->txout.nValue <= nBest))
2299 setCoinsRet.insert(coinLowestLarger.get());
2300 nValueRet += coinLowestLarger->txout.nValue;
2302 else {
2303 for (unsigned int i = 0; i < vValue.size(); i++)
2304 if (vfBest[i])
2306 setCoinsRet.insert(vValue[i]);
2307 nValueRet += vValue[i].txout.nValue;
2310 if (LogAcceptCategory(BCLog::SELECTCOINS)) {
2311 LogPrint(BCLog::SELECTCOINS, "SelectCoins() best subset: ");
2312 for (unsigned int i = 0; i < vValue.size(); i++) {
2313 if (vfBest[i]) {
2314 LogPrint(BCLog::SELECTCOINS, "%s ", FormatMoney(vValue[i].txout.nValue));
2317 LogPrint(BCLog::SELECTCOINS, "total %s\n", FormatMoney(nBest));
2321 return true;
2324 bool CWallet::SelectCoins(const std::vector<COutput>& vAvailableCoins, const CAmount& nTargetValue, std::set<CInputCoin>& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl) const
2326 std::vector<COutput> vCoins(vAvailableCoins);
2328 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2329 if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs)
2331 BOOST_FOREACH(const COutput& out, vCoins)
2333 if (!out.fSpendable)
2334 continue;
2335 nValueRet += out.tx->tx->vout[out.i].nValue;
2336 setCoinsRet.insert(CInputCoin(out.tx, out.i));
2338 return (nValueRet >= nTargetValue);
2341 // calculate value from preset inputs and store them
2342 std::set<CInputCoin> setPresetCoins;
2343 CAmount nValueFromPresetInputs = 0;
2345 std::vector<COutPoint> vPresetInputs;
2346 if (coinControl)
2347 coinControl->ListSelected(vPresetInputs);
2348 BOOST_FOREACH(const COutPoint& outpoint, vPresetInputs)
2350 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2351 if (it != mapWallet.end())
2353 const CWalletTx* pcoin = &it->second;
2354 // Clearly invalid input, fail
2355 if (pcoin->tx->vout.size() <= outpoint.n)
2356 return false;
2357 nValueFromPresetInputs += pcoin->tx->vout[outpoint.n].nValue;
2358 setPresetCoins.insert(CInputCoin(pcoin, outpoint.n));
2359 } else
2360 return false; // TODO: Allow non-wallet inputs
2363 // remove preset inputs from vCoins
2364 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->HasSelected();)
2366 if (setPresetCoins.count(CInputCoin(it->tx, it->i)))
2367 it = vCoins.erase(it);
2368 else
2369 ++it;
2372 size_t nMaxChainLength = std::min(GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT), GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2373 bool fRejectLongChains = GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2375 bool res = nTargetValue <= nValueFromPresetInputs ||
2376 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2377 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2378 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, 2, vCoins, setCoinsRet, nValueRet)) ||
2379 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::min((size_t)4, nMaxChainLength/3), vCoins, setCoinsRet, nValueRet)) ||
2380 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength/2, vCoins, setCoinsRet, nValueRet)) ||
2381 (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, nMaxChainLength, vCoins, setCoinsRet, nValueRet)) ||
2382 (bSpendZeroConfChange && !fRejectLongChains && SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 0, 1, std::numeric_limits<uint64_t>::max(), vCoins, setCoinsRet, nValueRet));
2384 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2385 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2387 // add preset inputs to the total value selected
2388 nValueRet += nValueFromPresetInputs;
2390 return res;
2393 bool CWallet::SignTransaction(CMutableTransaction &tx)
2395 AssertLockHeld(cs_wallet); // mapWallet
2397 // sign the new tx
2398 CTransaction txNewConst(tx);
2399 int nIn = 0;
2400 for (const auto& input : tx.vin) {
2401 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2402 if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2403 return false;
2405 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2406 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2407 SignatureData sigdata;
2408 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, amount, SIGHASH_ALL), scriptPubKey, sigdata)) {
2409 return false;
2411 UpdateTransaction(tx, nIn, sigdata);
2412 nIn++;
2414 return true;
2417 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)
2419 std::vector<CRecipient> vecSend;
2421 // Turn the txout set into a CRecipient vector
2422 for (size_t idx = 0; idx < tx.vout.size(); idx++)
2424 const CTxOut& txOut = tx.vout[idx];
2425 CRecipient recipient = {txOut.scriptPubKey, txOut.nValue, setSubtractFeeFromOutputs.count(idx) == 1};
2426 vecSend.push_back(recipient);
2429 CCoinControl coinControl;
2430 coinControl.destChange = destChange;
2431 coinControl.fAllowOtherInputs = true;
2432 coinControl.fAllowWatchOnly = includeWatching;
2433 coinControl.fOverrideFeeRate = overrideEstimatedFeeRate;
2434 coinControl.nFeeRate = specificFeeRate;
2436 BOOST_FOREACH(const CTxIn& txin, tx.vin)
2437 coinControl.Select(txin.prevout);
2439 CReserveKey reservekey(this);
2440 CWalletTx wtx;
2441 if (!CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, &coinControl, false))
2442 return false;
2444 if (nChangePosInOut != -1)
2445 tx.vout.insert(tx.vout.begin() + nChangePosInOut, wtx.tx->vout[nChangePosInOut]);
2447 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2448 for (unsigned int idx = 0; idx < tx.vout.size(); idx++)
2449 tx.vout[idx].nValue = wtx.tx->vout[idx].nValue;
2451 // Add new txins (keeping original txin scriptSig/order)
2452 BOOST_FOREACH(const CTxIn& txin, wtx.tx->vin)
2454 if (!coinControl.IsSelected(txin.prevout))
2456 tx.vin.push_back(txin);
2458 if (lockUnspents)
2460 LOCK2(cs_main, cs_wallet);
2461 LockCoin(txin.prevout);
2466 // optionally keep the change output key
2467 if (keepReserveKey)
2468 reservekey.KeepKey();
2470 return true;
2473 bool CWallet::CreateTransaction(const std::vector<CRecipient>& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet,
2474 int& nChangePosInOut, std::string& strFailReason, const CCoinControl* coinControl, bool sign)
2476 CAmount nValue = 0;
2477 int nChangePosRequest = nChangePosInOut;
2478 unsigned int nSubtractFeeFromAmount = 0;
2479 for (const auto& recipient : vecSend)
2481 if (nValue < 0 || recipient.nAmount < 0)
2483 strFailReason = _("Transaction amounts must not be negative");
2484 return false;
2486 nValue += recipient.nAmount;
2488 if (recipient.fSubtractFeeFromAmount)
2489 nSubtractFeeFromAmount++;
2491 if (vecSend.empty())
2493 strFailReason = _("Transaction must have at least one recipient");
2494 return false;
2497 wtxNew.fTimeReceivedIsTxTime = true;
2498 wtxNew.BindWallet(this);
2499 CMutableTransaction txNew;
2501 // Discourage fee sniping.
2503 // For a large miner the value of the transactions in the best block and
2504 // the mempool can exceed the cost of deliberately attempting to mine two
2505 // blocks to orphan the current best block. By setting nLockTime such that
2506 // only the next block can include the transaction, we discourage this
2507 // practice as the height restricted and limited blocksize gives miners
2508 // considering fee sniping fewer options for pulling off this attack.
2510 // A simple way to think about this is from the wallet's point of view we
2511 // always want the blockchain to move forward. By setting nLockTime this
2512 // way we're basically making the statement that we only want this
2513 // transaction to appear in the next block; we don't want to potentially
2514 // encourage reorgs by allowing transactions to appear at lower heights
2515 // than the next block in forks of the best chain.
2517 // Of course, the subsidy is high enough, and transaction volume low
2518 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2519 // now we ensure code won't be written that makes assumptions about
2520 // nLockTime that preclude a fix later.
2521 txNew.nLockTime = chainActive.Height();
2523 // Secondly occasionally randomly pick a nLockTime even further back, so
2524 // that transactions that are delayed after signing for whatever reason,
2525 // e.g. high-latency mix networks and some CoinJoin implementations, have
2526 // better privacy.
2527 if (GetRandInt(10) == 0)
2528 txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100));
2530 assert(txNew.nLockTime <= (unsigned int)chainActive.Height());
2531 assert(txNew.nLockTime < LOCKTIME_THRESHOLD);
2534 std::set<CInputCoin> setCoins;
2535 LOCK2(cs_main, cs_wallet);
2537 std::vector<COutput> vAvailableCoins;
2538 AvailableCoins(vAvailableCoins, true, coinControl);
2540 nFeeRet = 0;
2541 // Start with no fee and loop until there is enough fee
2542 while (true)
2544 nChangePosInOut = nChangePosRequest;
2545 txNew.vin.clear();
2546 txNew.vout.clear();
2547 wtxNew.fFromMe = true;
2548 bool fFirst = true;
2550 CAmount nValueToSelect = nValue;
2551 if (nSubtractFeeFromAmount == 0)
2552 nValueToSelect += nFeeRet;
2553 // vouts to the payees
2554 for (const auto& recipient : vecSend)
2556 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2558 if (recipient.fSubtractFeeFromAmount)
2560 txout.nValue -= nFeeRet / nSubtractFeeFromAmount; // Subtract fee equally from each selected recipient
2562 if (fFirst) // first receiver pays the remainder not divisible by output count
2564 fFirst = false;
2565 txout.nValue -= nFeeRet % nSubtractFeeFromAmount;
2569 if (IsDust(txout, ::dustRelayFee))
2571 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2573 if (txout.nValue < 0)
2574 strFailReason = _("The transaction amount is too small to pay the fee");
2575 else
2576 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2578 else
2579 strFailReason = _("Transaction amount too small");
2580 return false;
2582 txNew.vout.push_back(txout);
2585 // Choose coins to use
2586 CAmount nValueIn = 0;
2587 setCoins.clear();
2588 if (!SelectCoins(vAvailableCoins, nValueToSelect, setCoins, nValueIn, coinControl))
2590 strFailReason = _("Insufficient funds");
2591 return false;
2594 const CAmount nChange = nValueIn - nValueToSelect;
2595 if (nChange > 0)
2597 // Fill a vout to ourself
2598 // TODO: pass in scriptChange instead of reservekey so
2599 // change transaction isn't always pay-to-bitcoin-address
2600 CScript scriptChange;
2602 // coin control: send change to custom address
2603 if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange))
2604 scriptChange = GetScriptForDestination(coinControl->destChange);
2606 // no coin control: send change to newly generated address
2607 else
2609 // Note: We use a new key here to keep it from being obvious which side is the change.
2610 // The drawback is that by not reusing a previous key, the change may be lost if a
2611 // backup is restored, if the backup doesn't have the new private key for the change.
2612 // If we reused the old key, it would be possible to add code to look for and
2613 // rediscover unknown transactions that were written with keys of ours to recover
2614 // post-backup change.
2616 // Reserve a new key pair from key pool
2617 CPubKey vchPubKey;
2618 bool ret;
2619 ret = reservekey.GetReservedKey(vchPubKey, true);
2620 if (!ret)
2622 strFailReason = _("Keypool ran out, please call keypoolrefill first");
2623 return false;
2626 scriptChange = GetScriptForDestination(vchPubKey.GetID());
2629 CTxOut newTxOut(nChange, scriptChange);
2631 // We do not move dust-change to fees, because the sender would end up paying more than requested.
2632 // This would be against the purpose of the all-inclusive feature.
2633 // So instead we raise the change and deduct from the recipient.
2634 if (nSubtractFeeFromAmount > 0 && IsDust(newTxOut, ::dustRelayFee))
2636 CAmount nDust = GetDustThreshold(newTxOut, ::dustRelayFee) - newTxOut.nValue;
2637 newTxOut.nValue += nDust; // raise change until no more dust
2638 for (unsigned int i = 0; i < vecSend.size(); i++) // subtract from first recipient
2640 if (vecSend[i].fSubtractFeeFromAmount)
2642 txNew.vout[i].nValue -= nDust;
2643 if (IsDust(txNew.vout[i], ::dustRelayFee))
2645 strFailReason = _("The transaction amount is too small to send after the fee has been deducted");
2646 return false;
2648 break;
2653 // Never create dust outputs; if we would, just
2654 // add the dust to the fee.
2655 if (IsDust(newTxOut, ::dustRelayFee))
2657 nChangePosInOut = -1;
2658 nFeeRet += nChange;
2659 reservekey.ReturnKey();
2661 else
2663 if (nChangePosInOut == -1)
2665 // Insert change txn at random position:
2666 nChangePosInOut = GetRandInt(txNew.vout.size()+1);
2668 else if ((unsigned int)nChangePosInOut > txNew.vout.size())
2670 strFailReason = _("Change index out of range");
2671 return false;
2674 std::vector<CTxOut>::iterator position = txNew.vout.begin()+nChangePosInOut;
2675 txNew.vout.insert(position, newTxOut);
2677 } else {
2678 reservekey.ReturnKey();
2679 nChangePosInOut = -1;
2682 // Fill vin
2684 // Note how the sequence number is set to non-maxint so that
2685 // the nLockTime set above actually works.
2687 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2688 // we use the highest possible value in that range (maxint-2)
2689 // to avoid conflicting with other possible uses of nSequence,
2690 // and in the spirit of "smallest possible change from prior
2691 // behavior."
2692 bool rbf = coinControl ? coinControl->signalRbf : fWalletRbf;
2693 for (const auto& coin : setCoins)
2694 txNew.vin.push_back(CTxIn(coin.outpoint,CScript(),
2695 std::numeric_limits<unsigned int>::max() - (rbf ? 2 : 1)));
2697 // Fill in dummy signatures for fee calculation.
2698 if (!DummySignTx(txNew, setCoins)) {
2699 strFailReason = _("Signing transaction failed");
2700 return false;
2703 unsigned int nBytes = GetVirtualTransactionSize(txNew);
2705 CTransaction txNewConst(txNew);
2707 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2708 for (auto& vin : txNew.vin) {
2709 vin.scriptSig = CScript();
2710 vin.scriptWitness.SetNull();
2713 // Allow to override the default confirmation target over the CoinControl instance
2714 int currentConfirmationTarget = nTxConfirmTarget;
2715 if (coinControl && coinControl->nConfirmTarget > 0)
2716 currentConfirmationTarget = coinControl->nConfirmTarget;
2718 CAmount nFeeNeeded = GetMinimumFee(nBytes, currentConfirmationTarget, ::mempool, ::feeEstimator);
2719 if (coinControl && coinControl->fOverrideFeeRate)
2720 nFeeNeeded = coinControl->nFeeRate.GetFee(nBytes);
2722 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2723 // because we must be at the maximum allowed fee.
2724 if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes))
2726 strFailReason = _("Transaction too large for fee policy");
2727 return false;
2730 if (nFeeRet >= nFeeNeeded) {
2731 // Reduce fee to only the needed amount if we have change
2732 // output to increase. This prevents potential overpayment
2733 // in fees if the coins selected to meet nFeeNeeded result
2734 // in a transaction that requires less fee than the prior
2735 // iteration.
2736 // TODO: The case where nSubtractFeeFromAmount > 0 remains
2737 // to be addressed because it requires returning the fee to
2738 // the payees and not the change output.
2739 // TODO: The case where there is no change output remains
2740 // to be addressed so we avoid creating too small an output.
2741 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2742 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2743 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2744 change_position->nValue += extraFeePaid;
2745 nFeeRet -= extraFeePaid;
2747 break; // Done, enough fee included.
2750 // Try to reduce change to include necessary fee
2751 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2752 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2753 std::vector<CTxOut>::iterator change_position = txNew.vout.begin()+nChangePosInOut;
2754 // Only reduce change if remaining amount is still a large enough output.
2755 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2756 change_position->nValue -= additionalFeeNeeded;
2757 nFeeRet += additionalFeeNeeded;
2758 break; // Done, able to increase fee from change
2762 // Include more fee and try again.
2763 nFeeRet = nFeeNeeded;
2764 continue;
2768 if (sign)
2770 CTransaction txNewConst(txNew);
2771 int nIn = 0;
2772 for (const auto& coin : setCoins)
2774 const CScript& scriptPubKey = coin.txout.scriptPubKey;
2775 SignatureData sigdata;
2777 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst, nIn, coin.txout.nValue, SIGHASH_ALL), scriptPubKey, sigdata))
2779 strFailReason = _("Signing transaction failed");
2780 return false;
2781 } else {
2782 UpdateTransaction(txNew, nIn, sigdata);
2785 nIn++;
2789 // Embed the constructed transaction data in wtxNew.
2790 wtxNew.SetTx(MakeTransactionRef(std::move(txNew)));
2792 // Limit size
2793 if (GetTransactionWeight(wtxNew) >= MAX_STANDARD_TX_WEIGHT)
2795 strFailReason = _("Transaction too large");
2796 return false;
2800 if (GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2801 // Lastly, ensure this tx will pass the mempool's chain limits
2802 LockPoints lp;
2803 CTxMemPoolEntry entry(wtxNew.tx, 0, 0, 0, false, 0, lp);
2804 CTxMemPool::setEntries setAncestors;
2805 size_t nLimitAncestors = GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2806 size_t nLimitAncestorSize = GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2807 size_t nLimitDescendants = GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2808 size_t nLimitDescendantSize = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2809 std::string errString;
2810 if (!mempool.CalculateMemPoolAncestors(entry, setAncestors, nLimitAncestors, nLimitAncestorSize, nLimitDescendants, nLimitDescendantSize, errString)) {
2811 strFailReason = _("Transaction has too long of a mempool chain");
2812 return false;
2815 return true;
2819 * Call after CreateTransaction unless you want to abort
2821 bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, CConnman* connman, CValidationState& state)
2824 LOCK2(cs_main, cs_wallet);
2825 LogPrintf("CommitTransaction:\n%s", wtxNew.tx->ToString());
2827 // Take key pair from key pool so it won't be used again
2828 reservekey.KeepKey();
2830 // Add tx to wallet, because if it has change it's also ours,
2831 // otherwise just for transaction history.
2832 AddToWallet(wtxNew);
2834 // Notify that old coins are spent
2835 BOOST_FOREACH(const CTxIn& txin, wtxNew.tx->vin)
2837 CWalletTx &coin = mapWallet[txin.prevout.hash];
2838 coin.BindWallet(this);
2839 NotifyTransactionChanged(this, coin.GetHash(), CT_UPDATED);
2843 // Track how many getdata requests our transaction gets
2844 mapRequestCount[wtxNew.GetHash()] = 0;
2846 if (fBroadcastTransactions)
2848 // Broadcast
2849 if (!wtxNew.AcceptToMemoryPool(maxTxFee, state)) {
2850 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state.GetRejectReason());
2851 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2852 } else {
2853 wtxNew.RelayWalletTransaction(connman);
2857 return true;
2860 void CWallet::ListAccountCreditDebit(const std::string& strAccount, std::list<CAccountingEntry>& entries) {
2861 CWalletDB walletdb(*dbw);
2862 return walletdb.ListAccountCreditDebit(strAccount, entries);
2865 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry)
2867 CWalletDB walletdb(*dbw);
2869 return AddAccountingEntry(acentry, &walletdb);
2872 bool CWallet::AddAccountingEntry(const CAccountingEntry& acentry, CWalletDB *pwalletdb)
2874 if (!pwalletdb->WriteAccountingEntry(++nAccountingEntryNumber, acentry))
2875 return false;
2877 laccentries.push_back(acentry);
2878 CAccountingEntry & entry = laccentries.back();
2879 wtxOrdered.insert(std::make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry)));
2881 return true;
2884 CAmount CWallet::GetRequiredFee(unsigned int nTxBytes)
2886 return std::max(minTxFee.GetFee(nTxBytes), ::minRelayTxFee.GetFee(nTxBytes));
2889 CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool, const CBlockPolicyEstimator& estimator, bool ignoreGlobalPayTxFee)
2891 // payTxFee is the user-set global for desired feerate
2892 CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes);
2893 // User didn't set: use -txconfirmtarget to estimate...
2894 if (nFeeNeeded == 0 || ignoreGlobalPayTxFee) {
2895 int estimateFoundTarget = nConfirmTarget;
2896 nFeeNeeded = estimator.estimateSmartFee(nConfirmTarget, &estimateFoundTarget, pool).GetFee(nTxBytes);
2897 // ... unless we don't have enough mempool data for estimatefee, then use fallbackFee
2898 if (nFeeNeeded == 0)
2899 nFeeNeeded = fallbackFee.GetFee(nTxBytes);
2901 // prevent user from paying a fee below minRelayTxFee or minTxFee
2902 nFeeNeeded = std::max(nFeeNeeded, GetRequiredFee(nTxBytes));
2903 // But always obey the maximum
2904 if (nFeeNeeded > maxTxFee)
2905 nFeeNeeded = maxTxFee;
2906 return nFeeNeeded;
2912 DBErrors CWallet::LoadWallet(bool& fFirstRunRet)
2914 fFirstRunRet = false;
2915 DBErrors nLoadWalletRet = CWalletDB(*dbw,"cr+").LoadWallet(this);
2916 if (nLoadWalletRet == DB_NEED_REWRITE)
2918 if (dbw->Rewrite("\x04pool"))
2920 LOCK(cs_wallet);
2921 setKeyPool.clear();
2922 // Note: can't top-up keypool here, because wallet is locked.
2923 // User will be prompted to unlock wallet the next operation
2924 // that requires a new key.
2928 if (nLoadWalletRet != DB_LOAD_OK)
2929 return nLoadWalletRet;
2930 fFirstRunRet = !vchDefaultKey.IsValid();
2932 uiInterface.LoadWallet(this);
2934 return DB_LOAD_OK;
2937 DBErrors CWallet::ZapSelectTx(std::vector<uint256>& vHashIn, std::vector<uint256>& vHashOut)
2939 AssertLockHeld(cs_wallet); // mapWallet
2940 vchDefaultKey = CPubKey();
2941 DBErrors nZapSelectTxRet = CWalletDB(*dbw,"cr+").ZapSelectTx(vHashIn, vHashOut);
2942 for (uint256 hash : vHashOut)
2943 mapWallet.erase(hash);
2945 if (nZapSelectTxRet == DB_NEED_REWRITE)
2947 if (dbw->Rewrite("\x04pool"))
2949 setKeyPool.clear();
2950 // Note: can't top-up keypool here, because wallet is locked.
2951 // User will be prompted to unlock wallet the next operation
2952 // that requires a new key.
2956 if (nZapSelectTxRet != DB_LOAD_OK)
2957 return nZapSelectTxRet;
2959 MarkDirty();
2961 return DB_LOAD_OK;
2965 DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx)
2967 vchDefaultKey = CPubKey();
2968 DBErrors nZapWalletTxRet = CWalletDB(*dbw,"cr+").ZapWalletTx(vWtx);
2969 if (nZapWalletTxRet == DB_NEED_REWRITE)
2971 if (dbw->Rewrite("\x04pool"))
2973 LOCK(cs_wallet);
2974 setKeyPool.clear();
2975 // Note: can't top-up keypool here, because wallet is locked.
2976 // User will be prompted to unlock wallet the next operation
2977 // that requires a new key.
2981 if (nZapWalletTxRet != DB_LOAD_OK)
2982 return nZapWalletTxRet;
2984 return DB_LOAD_OK;
2988 bool CWallet::SetAddressBook(const CTxDestination& address, const std::string& strName, const std::string& strPurpose)
2990 bool fUpdated = false;
2992 LOCK(cs_wallet); // mapAddressBook
2993 std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address);
2994 fUpdated = mi != mapAddressBook.end();
2995 mapAddressBook[address].name = strName;
2996 if (!strPurpose.empty()) /* update purpose only if requested */
2997 mapAddressBook[address].purpose = strPurpose;
2999 NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO,
3000 strPurpose, (fUpdated ? CT_UPDATED : CT_NEW) );
3001 if (!strPurpose.empty() && !CWalletDB(*dbw).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose))
3002 return false;
3003 return CWalletDB(*dbw).WriteName(CBitcoinAddress(address).ToString(), strName);
3006 bool CWallet::DelAddressBook(const CTxDestination& address)
3009 LOCK(cs_wallet); // mapAddressBook
3011 // Delete destdata tuples associated with address
3012 std::string strAddress = CBitcoinAddress(address).ToString();
3013 BOOST_FOREACH(const PAIRTYPE(std::string, std::string) &item, mapAddressBook[address].destdata)
3015 CWalletDB(*dbw).EraseDestData(strAddress, item.first);
3017 mapAddressBook.erase(address);
3020 NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED);
3022 CWalletDB(*dbw).ErasePurpose(CBitcoinAddress(address).ToString());
3023 return CWalletDB(*dbw).EraseName(CBitcoinAddress(address).ToString());
3026 const std::string& CWallet::GetAccountName(const CScript& scriptPubKey) const
3028 CTxDestination address;
3029 if (ExtractDestination(scriptPubKey, address) && !scriptPubKey.IsUnspendable()) {
3030 auto mi = mapAddressBook.find(address);
3031 if (mi != mapAddressBook.end()) {
3032 return mi->second.name;
3035 // A scriptPubKey that doesn't have an entry in the address book is
3036 // associated with the default account ("").
3037 const static std::string DEFAULT_ACCOUNT_NAME;
3038 return DEFAULT_ACCOUNT_NAME;
3041 bool CWallet::SetDefaultKey(const CPubKey &vchPubKey)
3043 if (!CWalletDB(*dbw).WriteDefaultKey(vchPubKey))
3044 return false;
3045 vchDefaultKey = vchPubKey;
3046 return true;
3050 * Mark old keypool keys as used,
3051 * and generate all new keys
3053 bool CWallet::NewKeyPool()
3056 LOCK(cs_wallet);
3057 CWalletDB walletdb(*dbw);
3058 BOOST_FOREACH(int64_t nIndex, setKeyPool)
3059 walletdb.ErasePool(nIndex);
3060 setKeyPool.clear();
3062 if (!TopUpKeyPool()) {
3063 return false;
3065 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3067 return true;
3070 size_t CWallet::KeypoolCountExternalKeys()
3072 AssertLockHeld(cs_wallet); // setKeyPool
3074 // immediately return setKeyPool's size if HD or HD_SPLIT is disabled or not supported
3075 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3076 return setKeyPool.size();
3078 CWalletDB walletdb(*dbw);
3080 // count amount of external keys
3081 size_t amountE = 0;
3082 for(const int64_t& id : setKeyPool)
3084 CKeyPool tmpKeypool;
3085 if (!walletdb.ReadPool(id, tmpKeypool))
3086 throw std::runtime_error(std::string(__func__) + ": read failed");
3087 amountE += !tmpKeypool.fInternal;
3090 return amountE;
3093 bool CWallet::TopUpKeyPool(unsigned int kpSize)
3096 LOCK(cs_wallet);
3098 if (IsLocked())
3099 return false;
3101 // Top up key pool
3102 unsigned int nTargetSize;
3103 if (kpSize > 0)
3104 nTargetSize = kpSize;
3105 else
3106 nTargetSize = std::max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3108 // count amount of available keys (internal, external)
3109 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3110 int64_t amountExternal = KeypoolCountExternalKeys();
3111 int64_t amountInternal = setKeyPool.size() - amountExternal;
3112 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - amountExternal, (int64_t) 0);
3113 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - amountInternal, (int64_t) 0);
3115 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT))
3117 // don't create extra internal keys
3118 missingInternal = 0;
3120 bool internal = false;
3121 CWalletDB walletdb(*dbw);
3122 for (int64_t i = missingInternal + missingExternal; i--;)
3124 int64_t nEnd = 1;
3125 if (i < missingInternal)
3126 internal = true;
3127 if (!setKeyPool.empty())
3128 nEnd = *(--setKeyPool.end()) + 1;
3129 if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey(internal), internal)))
3130 throw std::runtime_error(std::string(__func__) + ": writing generated key failed");
3131 setKeyPool.insert(nEnd);
3132 LogPrintf("keypool added key %d, size=%u, internal=%d\n", nEnd, setKeyPool.size(), internal);
3135 return true;
3138 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool, bool internal)
3140 nIndex = -1;
3141 keypool.vchPubKey = CPubKey();
3143 LOCK(cs_wallet);
3145 if (!IsLocked())
3146 TopUpKeyPool();
3148 // Get the oldest key
3149 if(setKeyPool.empty())
3150 return;
3152 CWalletDB walletdb(*dbw);
3154 // try to find a key that matches the internal/external filter
3155 for(const int64_t& id : setKeyPool)
3157 CKeyPool tmpKeypool;
3158 if (!walletdb.ReadPool(id, tmpKeypool))
3159 throw std::runtime_error(std::string(__func__) + ": read failed");
3160 if (!HaveKey(tmpKeypool.vchPubKey.GetID()))
3161 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3162 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT) || tmpKeypool.fInternal == internal)
3164 nIndex = id;
3165 keypool = tmpKeypool;
3166 setKeyPool.erase(id);
3167 assert(keypool.vchPubKey.IsValid());
3168 LogPrintf("keypool reserve %d\n", nIndex);
3169 return;
3175 void CWallet::KeepKey(int64_t nIndex)
3177 // Remove from key pool
3178 CWalletDB walletdb(*dbw);
3179 walletdb.ErasePool(nIndex);
3180 LogPrintf("keypool keep %d\n", nIndex);
3183 void CWallet::ReturnKey(int64_t nIndex)
3185 // Return to key pool
3187 LOCK(cs_wallet);
3188 setKeyPool.insert(nIndex);
3190 LogPrintf("keypool return %d\n", nIndex);
3193 bool CWallet::GetKeyFromPool(CPubKey& result, bool internal)
3195 int64_t nIndex = 0;
3196 CKeyPool keypool;
3198 LOCK(cs_wallet);
3199 ReserveKeyFromKeyPool(nIndex, keypool, internal);
3200 if (nIndex == -1)
3202 if (IsLocked()) return false;
3203 result = GenerateNewKey(internal);
3204 return true;
3206 KeepKey(nIndex);
3207 result = keypool.vchPubKey;
3209 return true;
3212 int64_t CWallet::GetOldestKeyPoolTime()
3214 LOCK(cs_wallet);
3216 // if the keypool is empty, return <NOW>
3217 if (setKeyPool.empty())
3218 return GetTime();
3220 CKeyPool keypool;
3221 CWalletDB walletdb(*dbw);
3223 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT))
3225 // if HD & HD Chain Split is enabled, response max(oldest-internal-key, oldest-external-key)
3226 int64_t now = GetTime();
3227 int64_t oldest_external = now, oldest_internal = now;
3229 for(const int64_t& id : setKeyPool)
3231 if (!walletdb.ReadPool(id, keypool)) {
3232 throw std::runtime_error(std::string(__func__) + ": read failed");
3234 if (keypool.fInternal && keypool.nTime < oldest_internal) {
3235 oldest_internal = keypool.nTime;
3237 else if (!keypool.fInternal && keypool.nTime < oldest_external) {
3238 oldest_external = keypool.nTime;
3240 if (oldest_internal != now && oldest_external != now) {
3241 break;
3244 return std::max(oldest_internal, oldest_external);
3246 // load oldest key from keypool, get time and return
3247 int64_t nIndex = *(setKeyPool.begin());
3248 if (!walletdb.ReadPool(nIndex, keypool))
3249 throw std::runtime_error(std::string(__func__) + ": read oldest key in keypool failed");
3250 assert(keypool.vchPubKey.IsValid());
3251 return keypool.nTime;
3254 std::map<CTxDestination, CAmount> CWallet::GetAddressBalances()
3256 std::map<CTxDestination, CAmount> balances;
3259 LOCK(cs_wallet);
3260 for (const auto& walletEntry : mapWallet)
3262 const CWalletTx *pcoin = &walletEntry.second;
3264 if (!pcoin->IsTrusted())
3265 continue;
3267 if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0)
3268 continue;
3270 int nDepth = pcoin->GetDepthInMainChain();
3271 if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1))
3272 continue;
3274 for (unsigned int i = 0; i < pcoin->tx->vout.size(); i++)
3276 CTxDestination addr;
3277 if (!IsMine(pcoin->tx->vout[i]))
3278 continue;
3279 if(!ExtractDestination(pcoin->tx->vout[i].scriptPubKey, addr))
3280 continue;
3282 CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->tx->vout[i].nValue;
3284 if (!balances.count(addr))
3285 balances[addr] = 0;
3286 balances[addr] += n;
3291 return balances;
3294 std::set< std::set<CTxDestination> > CWallet::GetAddressGroupings()
3296 AssertLockHeld(cs_wallet); // mapWallet
3297 std::set< std::set<CTxDestination> > groupings;
3298 std::set<CTxDestination> grouping;
3300 for (const auto& walletEntry : mapWallet)
3302 const CWalletTx *pcoin = &walletEntry.second;
3304 if (pcoin->tx->vin.size() > 0)
3306 bool any_mine = false;
3307 // group all input addresses with each other
3308 BOOST_FOREACH(CTxIn txin, pcoin->tx->vin)
3310 CTxDestination address;
3311 if(!IsMine(txin)) /* If this input isn't mine, ignore it */
3312 continue;
3313 if(!ExtractDestination(mapWallet[txin.prevout.hash].tx->vout[txin.prevout.n].scriptPubKey, address))
3314 continue;
3315 grouping.insert(address);
3316 any_mine = true;
3319 // group change with input addresses
3320 if (any_mine)
3322 BOOST_FOREACH(CTxOut txout, pcoin->tx->vout)
3323 if (IsChange(txout))
3325 CTxDestination txoutAddr;
3326 if(!ExtractDestination(txout.scriptPubKey, txoutAddr))
3327 continue;
3328 grouping.insert(txoutAddr);
3331 if (grouping.size() > 0)
3333 groupings.insert(grouping);
3334 grouping.clear();
3338 // group lone addrs by themselves
3339 for (const auto& txout : pcoin->tx->vout)
3340 if (IsMine(txout))
3342 CTxDestination address;
3343 if(!ExtractDestination(txout.scriptPubKey, address))
3344 continue;
3345 grouping.insert(address);
3346 groupings.insert(grouping);
3347 grouping.clear();
3351 std::set< std::set<CTxDestination>* > uniqueGroupings; // a set of pointers to groups of addresses
3352 std::map< CTxDestination, std::set<CTxDestination>* > setmap; // map addresses to the unique group containing it
3353 BOOST_FOREACH(std::set<CTxDestination> _grouping, groupings)
3355 // make a set of all the groups hit by this new group
3356 std::set< std::set<CTxDestination>* > hits;
3357 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3358 BOOST_FOREACH(CTxDestination address, _grouping)
3359 if ((it = setmap.find(address)) != setmap.end())
3360 hits.insert((*it).second);
3362 // merge all hit groups into a new single group and delete old groups
3363 std::set<CTxDestination>* merged = new std::set<CTxDestination>(_grouping);
3364 BOOST_FOREACH(std::set<CTxDestination>* hit, hits)
3366 merged->insert(hit->begin(), hit->end());
3367 uniqueGroupings.erase(hit);
3368 delete hit;
3370 uniqueGroupings.insert(merged);
3372 // update setmap
3373 BOOST_FOREACH(CTxDestination element, *merged)
3374 setmap[element] = merged;
3377 std::set< std::set<CTxDestination> > ret;
3378 BOOST_FOREACH(std::set<CTxDestination>* uniqueGrouping, uniqueGroupings)
3380 ret.insert(*uniqueGrouping);
3381 delete uniqueGrouping;
3384 return ret;
3387 std::set<CTxDestination> CWallet::GetAccountAddresses(const std::string& strAccount) const
3389 LOCK(cs_wallet);
3390 std::set<CTxDestination> result;
3391 BOOST_FOREACH(const PAIRTYPE(CTxDestination, CAddressBookData)& item, mapAddressBook)
3393 const CTxDestination& address = item.first;
3394 const std::string& strName = item.second.name;
3395 if (strName == strAccount)
3396 result.insert(address);
3398 return result;
3401 bool CReserveKey::GetReservedKey(CPubKey& pubkey, bool internal)
3403 if (nIndex == -1)
3405 CKeyPool keypool;
3406 pwallet->ReserveKeyFromKeyPool(nIndex, keypool, internal);
3407 if (nIndex != -1)
3408 vchPubKey = keypool.vchPubKey;
3409 else {
3410 return false;
3413 assert(vchPubKey.IsValid());
3414 pubkey = vchPubKey;
3415 return true;
3418 void CReserveKey::KeepKey()
3420 if (nIndex != -1)
3421 pwallet->KeepKey(nIndex);
3422 nIndex = -1;
3423 vchPubKey = CPubKey();
3426 void CReserveKey::ReturnKey()
3428 if (nIndex != -1)
3429 pwallet->ReturnKey(nIndex);
3430 nIndex = -1;
3431 vchPubKey = CPubKey();
3434 void CWallet::GetAllReserveKeys(std::set<CKeyID>& setAddress) const
3436 setAddress.clear();
3438 CWalletDB walletdb(*dbw);
3440 LOCK2(cs_main, cs_wallet);
3441 BOOST_FOREACH(const int64_t& id, setKeyPool)
3443 CKeyPool keypool;
3444 if (!walletdb.ReadPool(id, keypool))
3445 throw std::runtime_error(std::string(__func__) + ": read failed");
3446 assert(keypool.vchPubKey.IsValid());
3447 CKeyID keyID = keypool.vchPubKey.GetID();
3448 if (!HaveKey(keyID))
3449 throw std::runtime_error(std::string(__func__) + ": unknown key in key pool");
3450 setAddress.insert(keyID);
3454 void CWallet::GetScriptForMining(std::shared_ptr<CReserveScript> &script)
3456 std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(this);
3457 CPubKey pubkey;
3458 if (!rKey->GetReservedKey(pubkey))
3459 return;
3461 script = rKey;
3462 script->reserveScript = CScript() << ToByteVector(pubkey) << OP_CHECKSIG;
3465 void CWallet::LockCoin(const COutPoint& output)
3467 AssertLockHeld(cs_wallet); // setLockedCoins
3468 setLockedCoins.insert(output);
3471 void CWallet::UnlockCoin(const COutPoint& output)
3473 AssertLockHeld(cs_wallet); // setLockedCoins
3474 setLockedCoins.erase(output);
3477 void CWallet::UnlockAllCoins()
3479 AssertLockHeld(cs_wallet); // setLockedCoins
3480 setLockedCoins.clear();
3483 bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const
3485 AssertLockHeld(cs_wallet); // setLockedCoins
3486 COutPoint outpt(hash, n);
3488 return (setLockedCoins.count(outpt) > 0);
3491 void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) const
3493 AssertLockHeld(cs_wallet); // setLockedCoins
3494 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3495 it != setLockedCoins.end(); it++) {
3496 COutPoint outpt = (*it);
3497 vOutpts.push_back(outpt);
3501 /** @} */ // end of Actions
3503 class CAffectedKeysVisitor : public boost::static_visitor<void> {
3504 private:
3505 const CKeyStore &keystore;
3506 std::vector<CKeyID> &vKeys;
3508 public:
3509 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
3511 void Process(const CScript &script) {
3512 txnouttype type;
3513 std::vector<CTxDestination> vDest;
3514 int nRequired;
3515 if (ExtractDestinations(script, type, vDest, nRequired)) {
3516 BOOST_FOREACH(const CTxDestination &dest, vDest)
3517 boost::apply_visitor(*this, dest);
3521 void operator()(const CKeyID &keyId) {
3522 if (keystore.HaveKey(keyId))
3523 vKeys.push_back(keyId);
3526 void operator()(const CScriptID &scriptId) {
3527 CScript script;
3528 if (keystore.GetCScript(scriptId, script))
3529 Process(script);
3532 void operator()(const CNoDestination &none) {}
3535 void CWallet::GetKeyBirthTimes(std::map<CTxDestination, int64_t> &mapKeyBirth) const {
3536 AssertLockHeld(cs_wallet); // mapKeyMetadata
3537 mapKeyBirth.clear();
3539 // get birth times for keys with metadata
3540 for (const auto& entry : mapKeyMetadata) {
3541 if (entry.second.nCreateTime) {
3542 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3546 // map in which we'll infer heights of other keys
3547 CBlockIndex *pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3548 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3549 std::set<CKeyID> setKeys;
3550 GetKeys(setKeys);
3551 BOOST_FOREACH(const CKeyID &keyid, setKeys) {
3552 if (mapKeyBirth.count(keyid) == 0)
3553 mapKeyFirstBlock[keyid] = pindexMax;
3555 setKeys.clear();
3557 // if there are no such keys, we're done
3558 if (mapKeyFirstBlock.empty())
3559 return;
3561 // find first block that affects those keys, if there are any left
3562 std::vector<CKeyID> vAffected;
3563 for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) {
3564 // iterate over all wallet transactions...
3565 const CWalletTx &wtx = (*it).second;
3566 BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock);
3567 if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) {
3568 // ... which are already in a block
3569 int nHeight = blit->second->nHeight;
3570 BOOST_FOREACH(const CTxOut &txout, wtx.tx->vout) {
3571 // iterate over all their outputs
3572 CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey);
3573 BOOST_FOREACH(const CKeyID &keyid, vAffected) {
3574 // ... and all their affected keys
3575 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3576 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3577 rit->second = blit->second;
3579 vAffected.clear();
3584 // Extract block timestamps for those keys
3585 for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++)
3586 mapKeyBirth[it->first] = it->second->GetBlockTime() - TIMESTAMP_WINDOW; // block times can be 2h off
3590 * Compute smart timestamp for a transaction being added to the wallet.
3592 * Logic:
3593 * - If sending a transaction, assign its timestamp to the current time.
3594 * - If receiving a transaction outside a block, assign its timestamp to the
3595 * current time.
3596 * - If receiving a block with a future timestamp, assign all its (not already
3597 * known) transactions' timestamps to the current time.
3598 * - If receiving a block with a past timestamp, before the most recent known
3599 * transaction (that we care about), assign all its (not already known)
3600 * transactions' timestamps to the same timestamp as that most-recent-known
3601 * transaction.
3602 * - If receiving a block with a past timestamp, but after the most recent known
3603 * transaction, assign all its (not already known) transactions' timestamps to
3604 * the block time.
3606 * For more information see CWalletTx::nTimeSmart,
3607 * https://bitcointalk.org/?topic=54527, or
3608 * https://github.com/bitcoin/bitcoin/pull/1393.
3610 unsigned int CWallet::ComputeTimeSmart(const CWalletTx& wtx) const
3612 unsigned int nTimeSmart = wtx.nTimeReceived;
3613 if (!wtx.hashUnset()) {
3614 if (mapBlockIndex.count(wtx.hashBlock)) {
3615 int64_t latestNow = wtx.nTimeReceived;
3616 int64_t latestEntry = 0;
3618 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3619 int64_t latestTolerated = latestNow + 300;
3620 const TxItems& txOrdered = wtxOrdered;
3621 for (auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3622 CWalletTx* const pwtx = it->second.first;
3623 if (pwtx == &wtx) {
3624 continue;
3626 CAccountingEntry* const pacentry = it->second.second;
3627 int64_t nSmartTime;
3628 if (pwtx) {
3629 nSmartTime = pwtx->nTimeSmart;
3630 if (!nSmartTime) {
3631 nSmartTime = pwtx->nTimeReceived;
3633 } else {
3634 nSmartTime = pacentry->nTime;
3636 if (nSmartTime <= latestTolerated) {
3637 latestEntry = nSmartTime;
3638 if (nSmartTime > latestNow) {
3639 latestNow = nSmartTime;
3641 break;
3645 int64_t blocktime = mapBlockIndex[wtx.hashBlock]->GetBlockTime();
3646 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3647 } else {
3648 LogPrintf("%s: found %s in block %s not in index\n", __func__, wtx.GetHash().ToString(), wtx.hashBlock.ToString());
3651 return nTimeSmart;
3654 bool CWallet::AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3656 if (boost::get<CNoDestination>(&dest))
3657 return false;
3659 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3660 return CWalletDB(*dbw).WriteDestData(CBitcoinAddress(dest).ToString(), key, value);
3663 bool CWallet::EraseDestData(const CTxDestination &dest, const std::string &key)
3665 if (!mapAddressBook[dest].destdata.erase(key))
3666 return false;
3667 return CWalletDB(*dbw).EraseDestData(CBitcoinAddress(dest).ToString(), key);
3670 bool CWallet::LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
3672 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3673 return true;
3676 bool CWallet::GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
3678 std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest);
3679 if(i != mapAddressBook.end())
3681 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3682 if(j != i->second.destdata.end())
3684 if(value)
3685 *value = j->second;
3686 return true;
3689 return false;
3692 std::vector<std::string> CWallet::GetDestValues(const std::string& prefix) const
3694 LOCK(cs_wallet);
3695 std::vector<std::string> values;
3696 for (const auto& address : mapAddressBook) {
3697 for (const auto& data : address.second.destdata) {
3698 if (!data.first.compare(0, prefix.size(), prefix)) {
3699 values.emplace_back(data.second);
3703 return values;
3706 std::string CWallet::GetWalletHelpString(bool showDebug)
3708 std::string strUsage = HelpMessageGroup(_("Wallet options:"));
3709 strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
3710 strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE));
3711 strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
3712 CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)));
3713 strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
3714 CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)));
3715 strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
3716 CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
3717 strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
3718 strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup"));
3719 strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE));
3720 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));
3721 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));
3722 strUsage += HelpMessageOpt("-walletrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (default: %u)"), DEFAULT_WALLET_RBF));
3723 strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
3724 strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT));
3725 strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST));
3726 strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
3727 strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
3728 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
3730 if (showDebug)
3732 strUsage += HelpMessageGroup(_("Wallet debugging/testing options:"));
3734 strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE));
3735 strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET));
3736 strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB));
3737 strUsage += HelpMessageOpt("-walletrejectlongchains", strprintf(_("Wallet will not create transactions that violate mempool chain limits (default: %u)"), DEFAULT_WALLET_REJECT_LONG_CHAINS));
3740 return strUsage;
3743 CWallet* CWallet::CreateWalletFromFile(const std::string walletFile)
3745 // needed to restore wallet transaction meta data after -zapwallettxes
3746 std::vector<CWalletTx> vWtx;
3748 if (GetBoolArg("-zapwallettxes", false)) {
3749 uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
3751 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3752 CWallet *tempWallet = new CWallet(std::move(dbw));
3753 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3754 if (nZapWalletRet != DB_LOAD_OK) {
3755 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3756 return NULL;
3759 delete tempWallet;
3760 tempWallet = NULL;
3763 uiInterface.InitMessage(_("Loading wallet..."));
3765 int64_t nStart = GetTimeMillis();
3766 bool fFirstRun = true;
3767 std::unique_ptr<CWalletDBWrapper> dbw(new CWalletDBWrapper(&bitdb, walletFile));
3768 CWallet *walletInstance = new CWallet(std::move(dbw));
3769 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3770 if (nLoadWalletRet != DB_LOAD_OK)
3772 if (nLoadWalletRet == DB_CORRUPT) {
3773 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile));
3774 return NULL;
3776 else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
3778 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3779 " or address book entries might be missing or incorrect."),
3780 walletFile));
3782 else if (nLoadWalletRet == DB_TOO_NEW) {
3783 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile, _(PACKAGE_NAME)));
3784 return NULL;
3786 else if (nLoadWalletRet == DB_NEED_REWRITE)
3788 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME)));
3789 return NULL;
3791 else {
3792 InitError(strprintf(_("Error loading %s"), walletFile));
3793 return NULL;
3797 if (GetBoolArg("-upgradewallet", fFirstRun))
3799 int nMaxVersion = GetArg("-upgradewallet", 0);
3800 if (nMaxVersion == 0) // the -upgradewallet without argument case
3802 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
3803 nMaxVersion = CLIENT_VERSION;
3804 walletInstance->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
3806 else
3807 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
3808 if (nMaxVersion < walletInstance->GetVersion())
3810 InitError(_("Cannot downgrade wallet"));
3811 return NULL;
3813 walletInstance->SetMaxVersion(nMaxVersion);
3816 if (fFirstRun)
3818 // Create new keyUser and set as default key
3819 if (GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET) && !walletInstance->IsHDEnabled()) {
3821 // ensure this wallet.dat can only be opened by clients supporting HD with chain split
3822 walletInstance->SetMinVersion(FEATURE_HD_SPLIT);
3824 // generate a new master key
3825 CPubKey masterPubKey = walletInstance->GenerateNewHDMasterKey();
3826 if (!walletInstance->SetHDMasterKey(masterPubKey))
3827 throw std::runtime_error(std::string(__func__) + ": Storing master key failed");
3829 CPubKey newDefaultKey;
3830 if (walletInstance->GetKeyFromPool(newDefaultKey, false)) {
3831 walletInstance->SetDefaultKey(newDefaultKey);
3832 if (!walletInstance->SetAddressBook(walletInstance->vchDefaultKey.GetID(), "", "receive")) {
3833 InitError(_("Cannot write default address") += "\n");
3834 return NULL;
3838 walletInstance->SetBestChain(chainActive.GetLocator());
3840 else if (IsArgSet("-usehd")) {
3841 bool useHD = GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET);
3842 if (walletInstance->IsHDEnabled() && !useHD) {
3843 InitError(strprintf(_("Error loading %s: You can't disable HD on a already existing HD wallet"), walletFile));
3844 return NULL;
3846 if (!walletInstance->IsHDEnabled() && useHD) {
3847 InitError(strprintf(_("Error loading %s: You can't enable HD on a already existing non-HD wallet"), walletFile));
3848 return NULL;
3852 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
3854 RegisterValidationInterface(walletInstance);
3856 CBlockIndex *pindexRescan = chainActive.Genesis();
3857 if (!GetBoolArg("-rescan", false))
3859 CWalletDB walletdb(*walletInstance->dbw);
3860 CBlockLocator locator;
3861 if (walletdb.ReadBestBlock(locator))
3862 pindexRescan = FindForkInGlobalIndex(chainActive, locator);
3864 if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
3866 //We can't rescan beyond non-pruned blocks, stop and throw an error
3867 //this might happen if a user uses a old wallet within a pruned node
3868 // or if he ran -disablewallet for a longer time, then decided to re-enable
3869 if (fPruneMode)
3871 CBlockIndex *block = chainActive.Tip();
3872 while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
3873 block = block->pprev;
3875 if (pindexRescan != block) {
3876 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3877 return NULL;
3881 uiInterface.InitMessage(_("Rescanning..."));
3882 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
3883 nStart = GetTimeMillis();
3884 walletInstance->ScanForWalletTransactions(pindexRescan, true);
3885 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
3886 walletInstance->SetBestChain(chainActive.GetLocator());
3887 walletInstance->dbw->IncrementUpdateCounter();
3889 // Restore wallet transaction metadata after -zapwallettxes=1
3890 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
3892 CWalletDB walletdb(*walletInstance->dbw);
3894 BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
3896 uint256 hash = wtxOld.GetHash();
3897 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
3898 if (mi != walletInstance->mapWallet.end())
3900 const CWalletTx* copyFrom = &wtxOld;
3901 CWalletTx* copyTo = &mi->second;
3902 copyTo->mapValue = copyFrom->mapValue;
3903 copyTo->vOrderForm = copyFrom->vOrderForm;
3904 copyTo->nTimeReceived = copyFrom->nTimeReceived;
3905 copyTo->nTimeSmart = copyFrom->nTimeSmart;
3906 copyTo->fFromMe = copyFrom->fFromMe;
3907 copyTo->strFromAccount = copyFrom->strFromAccount;
3908 copyTo->nOrderPos = copyFrom->nOrderPos;
3909 walletdb.WriteTx(*copyTo);
3914 walletInstance->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
3917 LOCK(walletInstance->cs_wallet);
3918 LogPrintf("setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
3919 LogPrintf("mapWallet.size() = %u\n", walletInstance->mapWallet.size());
3920 LogPrintf("mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
3923 return walletInstance;
3926 bool CWallet::InitLoadWallet()
3928 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) {
3929 pwalletMain = NULL;
3930 LogPrintf("Wallet disabled!\n");
3931 return true;
3934 std::string walletFile = GetArg("-wallet", DEFAULT_WALLET_DAT);
3936 if (boost::filesystem::path(walletFile).filename() != walletFile) {
3937 return InitError(_("-wallet parameter must only specify a filename (not a path)"));
3938 } else if (SanitizeString(walletFile, SAFE_CHARS_FILENAME) != walletFile) {
3939 return InitError(_("Invalid characters in -wallet filename"));
3942 CWallet * const pwallet = CreateWalletFromFile(walletFile);
3943 if (!pwallet) {
3944 return false;
3946 pwalletMain = pwallet;
3948 return true;
3951 std::atomic<bool> CWallet::fFlushScheduled(false);
3953 void CWallet::postInitProcess(CScheduler& scheduler)
3955 // Add wallet transactions that aren't already in a block to mempool
3956 // Do this here as mempool requires genesis block to be loaded
3957 ReacceptWalletTransactions();
3959 // Run a thread to flush wallet periodically
3960 if (!CWallet::fFlushScheduled.exchange(true)) {
3961 scheduler.scheduleEvery(MaybeCompactWalletDB, 500);
3965 bool CWallet::ParameterInteraction()
3967 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET))
3968 return true;
3970 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && SoftSetBoolArg("-walletbroadcast", false)) {
3971 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
3974 if (GetBoolArg("-salvagewallet", false) && SoftSetBoolArg("-rescan", true)) {
3975 // Rewrite just private keys: rescan to find transactions
3976 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
3979 // -zapwallettx implies a rescan
3980 if (GetBoolArg("-zapwallettxes", false) && SoftSetBoolArg("-rescan", true)) {
3981 LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
3984 if (GetBoolArg("-sysperms", false))
3985 return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
3986 if (GetArg("-prune", 0) && GetBoolArg("-rescan", false))
3987 return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
3989 if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB)
3990 InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
3991 _("The wallet will avoid paying less than the minimum relay fee."));
3993 if (IsArgSet("-mintxfee"))
3995 CAmount n = 0;
3996 if (!ParseMoney(GetArg("-mintxfee", ""), n) || 0 == n)
3997 return InitError(AmountErrMsg("mintxfee", GetArg("-mintxfee", "")));
3998 if (n > HIGH_TX_FEE_PER_KB)
3999 InitWarning(AmountHighWarn("-mintxfee") + " " +
4000 _("This is the minimum transaction fee you pay on every transaction."));
4001 CWallet::minTxFee = CFeeRate(n);
4003 if (IsArgSet("-fallbackfee"))
4005 CAmount nFeePerK = 0;
4006 if (!ParseMoney(GetArg("-fallbackfee", ""), nFeePerK))
4007 return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), GetArg("-fallbackfee", "")));
4008 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4009 InitWarning(AmountHighWarn("-fallbackfee") + " " +
4010 _("This is the transaction fee you may pay when fee estimates are not available."));
4011 CWallet::fallbackFee = CFeeRate(nFeePerK);
4013 if (IsArgSet("-paytxfee"))
4015 CAmount nFeePerK = 0;
4016 if (!ParseMoney(GetArg("-paytxfee", ""), nFeePerK))
4017 return InitError(AmountErrMsg("paytxfee", GetArg("-paytxfee", "")));
4018 if (nFeePerK > HIGH_TX_FEE_PER_KB)
4019 InitWarning(AmountHighWarn("-paytxfee") + " " +
4020 _("This is the transaction fee you will pay if you send a transaction."));
4022 payTxFee = CFeeRate(nFeePerK, 1000);
4023 if (payTxFee < ::minRelayTxFee)
4025 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
4026 GetArg("-paytxfee", ""), ::minRelayTxFee.ToString()));
4029 if (IsArgSet("-maxtxfee"))
4031 CAmount nMaxFee = 0;
4032 if (!ParseMoney(GetArg("-maxtxfee", ""), nMaxFee))
4033 return InitError(AmountErrMsg("maxtxfee", GetArg("-maxtxfee", "")));
4034 if (nMaxFee > HIGH_MAX_TX_FEE)
4035 InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
4036 maxTxFee = nMaxFee;
4037 if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
4039 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
4040 GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString()));
4043 nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
4044 bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
4045 fWalletRbf = GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF);
4047 return true;
4050 bool CWallet::BackupWallet(const std::string& strDest)
4052 return dbw->Backup(strDest);
4055 CKeyPool::CKeyPool()
4057 nTime = GetTime();
4058 fInternal = false;
4061 CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn, bool internalIn)
4063 nTime = GetTime();
4064 vchPubKey = vchPubKeyIn;
4065 fInternal = internalIn;
4068 CWalletKey::CWalletKey(int64_t nExpires)
4070 nTimeCreated = (nExpires ? GetTime() : 0);
4071 nTimeExpires = nExpires;
4074 void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock)
4076 // Update the tx's hashBlock
4077 hashBlock = pindex->GetBlockHash();
4079 // set the position of the transaction in the block
4080 nIndex = posInBlock;
4083 int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
4085 if (hashUnset())
4086 return 0;
4088 AssertLockHeld(cs_main);
4090 // Find the block it claims to be in
4091 BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
4092 if (mi == mapBlockIndex.end())
4093 return 0;
4094 CBlockIndex* pindex = (*mi).second;
4095 if (!pindex || !chainActive.Contains(pindex))
4096 return 0;
4098 pindexRet = pindex;
4099 return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1);
4102 int CMerkleTx::GetBlocksToMaturity() const
4104 if (!IsCoinBase())
4105 return 0;
4106 return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
4110 bool CMerkleTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state)
4112 return ::AcceptToMemoryPool(mempool, state, tx, true, NULL, NULL, false, nAbsurdFee);