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>
9 #include <checkpoints.h>
11 #include <wallet/coincontrol.h>
12 #include <consensus/consensus.h>
13 #include <consensus/validation.h>
15 #include <wallet/init.h>
18 #include <validation.h>
20 #include <policy/fees.h>
21 #include <policy/policy.h>
22 #include <policy/rbf.h>
23 #include <primitives/block.h>
24 #include <primitives/transaction.h>
25 #include <script/script.h>
26 #include <script/sign.h>
27 #include <scheduler.h>
29 #include <txmempool.h>
31 #include <ui_interface.h>
32 #include <utilmoneystr.h>
33 #include <wallet/fees.h>
38 #include <boost/algorithm/string/replace.hpp>
39 #include <boost/thread.hpp>
41 std::vector
<CWalletRef
> vpwallets
;
42 /** Transaction fee set by the user */
43 CFeeRate
payTxFee(DEFAULT_TRANSACTION_FEE
);
44 unsigned int nTxConfirmTarget
= DEFAULT_TX_CONFIRM_TARGET
;
45 bool bSpendZeroConfChange
= DEFAULT_SPEND_ZEROCONF_CHANGE
;
46 bool fWalletRbf
= DEFAULT_WALLET_RBF
;
48 const char * DEFAULT_WALLET_DAT
= "wallet.dat";
49 const uint32_t BIP32_HARDENED_KEY_LIMIT
= 0x80000000;
52 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
53 * Override with -mintxfee
55 CFeeRate
CWallet::minTxFee
= CFeeRate(DEFAULT_TRANSACTION_MINFEE
);
57 * If fee estimation does not have enough data to provide estimates, use this fee instead.
58 * Has no effect if not using fee estimation
59 * Override with -fallbackfee
61 CFeeRate
CWallet::fallbackFee
= CFeeRate(DEFAULT_FALLBACK_FEE
);
63 CFeeRate
CWallet::m_discard_rate
= CFeeRate(DEFAULT_DISCARD_FEE
);
65 const uint256
CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
67 /** @defgroup mapWallet
72 struct CompareValueOnly
74 bool operator()(const CInputCoin
& t1
,
75 const CInputCoin
& t2
) const
77 return t1
.txout
.nValue
< t2
.txout
.nValue
;
81 std::string
COutput::ToString() const
83 return strprintf("COutput(%s, %d, %d) [%s]", tx
->GetHash().ToString(), i
, nDepth
, FormatMoney(tx
->tx
->vout
[i
].nValue
));
86 class CAffectedKeysVisitor
: public boost::static_visitor
<void> {
88 const CKeyStore
&keystore
;
89 std::vector
<CKeyID
> &vKeys
;
92 CAffectedKeysVisitor(const CKeyStore
&keystoreIn
, std::vector
<CKeyID
> &vKeysIn
) : keystore(keystoreIn
), vKeys(vKeysIn
) {}
94 void Process(const CScript
&script
) {
96 std::vector
<CTxDestination
> vDest
;
98 if (ExtractDestinations(script
, type
, vDest
, nRequired
)) {
99 for (const CTxDestination
&dest
: vDest
)
100 boost::apply_visitor(*this, dest
);
104 void operator()(const CKeyID
&keyId
) {
105 if (keystore
.HaveKey(keyId
))
106 vKeys
.push_back(keyId
);
109 void operator()(const CScriptID
&scriptId
) {
111 if (keystore
.GetCScript(scriptId
, script
))
115 void operator()(const WitnessV0ScriptHash
& scriptID
)
118 CRIPEMD160().Write(scriptID
.begin(), 32).Finalize(id
.begin());
120 if (keystore
.GetCScript(id
, script
)) {
125 void operator()(const WitnessV0KeyHash
& keyid
)
128 if (keystore
.HaveKey(id
)) {
134 void operator()(const X
&none
) {}
137 const CWalletTx
* CWallet::GetWalletTx(const uint256
& hash
) const
140 std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.find(hash
);
141 if (it
== mapWallet
.end())
143 return &(it
->second
);
146 CPubKey
CWallet::GenerateNewKey(CWalletDB
&walletdb
, bool internal
)
148 AssertLockHeld(cs_wallet
); // mapKeyMetadata
149 bool fCompressed
= CanSupportFeature(FEATURE_COMPRPUBKEY
); // default to compressed public keys if we want 0.6.0 wallets
153 // Create new metadata
154 int64_t nCreationTime
= GetTime();
155 CKeyMetadata
metadata(nCreationTime
);
157 // use HD key derivation if HD was enabled during wallet creation
159 DeriveNewChildKey(walletdb
, metadata
, secret
, (CanSupportFeature(FEATURE_HD_SPLIT
) ? internal
: false));
161 secret
.MakeNewKey(fCompressed
);
164 // Compressed public keys were introduced in version 0.6.0
166 SetMinVersion(FEATURE_COMPRPUBKEY
);
169 CPubKey pubkey
= secret
.GetPubKey();
170 assert(secret
.VerifyPubKey(pubkey
));
172 mapKeyMetadata
[pubkey
.GetID()] = metadata
;
173 UpdateTimeFirstKey(nCreationTime
);
175 if (!AddKeyPubKeyWithDB(walletdb
, secret
, pubkey
)) {
176 throw std::runtime_error(std::string(__func__
) + ": AddKey failed");
181 void CWallet::DeriveNewChildKey(CWalletDB
&walletdb
, CKeyMetadata
& metadata
, CKey
& secret
, bool internal
)
183 // for now we use a fixed keypath scheme of m/0'/0'/k
184 CKey key
; //master key seed (256bit)
185 CExtKey masterKey
; //hd master key
186 CExtKey accountKey
; //key at m/0'
187 CExtKey chainChildKey
; //key at m/0'/0' (external) or m/0'/1' (internal)
188 CExtKey childKey
; //key at m/0'/0'/<n>'
190 // try to get the master key
191 if (!GetKey(hdChain
.masterKeyID
, key
))
192 throw std::runtime_error(std::string(__func__
) + ": Master key not found");
194 masterKey
.SetMaster(key
.begin(), key
.size());
197 // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
198 masterKey
.Derive(accountKey
, BIP32_HARDENED_KEY_LIMIT
);
200 // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
201 assert(internal
? CanSupportFeature(FEATURE_HD_SPLIT
) : true);
202 accountKey
.Derive(chainChildKey
, BIP32_HARDENED_KEY_LIMIT
+(internal
? 1 : 0));
204 // derive child key at next index, skip keys already known to the wallet
206 // always derive hardened keys
207 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
208 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
210 chainChildKey
.Derive(childKey
, hdChain
.nInternalChainCounter
| BIP32_HARDENED_KEY_LIMIT
);
211 metadata
.hdKeypath
= "m/0'/1'/" + std::to_string(hdChain
.nInternalChainCounter
) + "'";
212 hdChain
.nInternalChainCounter
++;
215 chainChildKey
.Derive(childKey
, hdChain
.nExternalChainCounter
| BIP32_HARDENED_KEY_LIMIT
);
216 metadata
.hdKeypath
= "m/0'/0'/" + std::to_string(hdChain
.nExternalChainCounter
) + "'";
217 hdChain
.nExternalChainCounter
++;
219 } while (HaveKey(childKey
.key
.GetPubKey().GetID()));
220 secret
= childKey
.key
;
221 metadata
.hdMasterKeyID
= hdChain
.masterKeyID
;
222 // update the chain model in the database
223 if (!walletdb
.WriteHDChain(hdChain
))
224 throw std::runtime_error(std::string(__func__
) + ": Writing HD chain model failed");
227 bool CWallet::AddKeyPubKeyWithDB(CWalletDB
&walletdb
, const CKey
& secret
, const CPubKey
&pubkey
)
229 AssertLockHeld(cs_wallet
); // mapKeyMetadata
231 // CCryptoKeyStore has no concept of wallet databases, but calls AddCryptedKey
232 // which is overridden below. To avoid flushes, the database handle is
233 // tunneled through to it.
234 bool needsDB
= !pwalletdbEncryption
;
236 pwalletdbEncryption
= &walletdb
;
238 if (!CCryptoKeyStore::AddKeyPubKey(secret
, pubkey
)) {
239 if (needsDB
) pwalletdbEncryption
= nullptr;
242 if (needsDB
) pwalletdbEncryption
= nullptr;
244 // check if we need to remove from watch-only
246 script
= GetScriptForDestination(pubkey
.GetID());
247 if (HaveWatchOnly(script
)) {
248 RemoveWatchOnly(script
);
250 script
= GetScriptForRawPubKey(pubkey
);
251 if (HaveWatchOnly(script
)) {
252 RemoveWatchOnly(script
);
256 return walletdb
.WriteKey(pubkey
,
258 mapKeyMetadata
[pubkey
.GetID()]);
263 bool CWallet::AddKeyPubKey(const CKey
& secret
, const CPubKey
&pubkey
)
265 CWalletDB
walletdb(*dbw
);
266 return CWallet::AddKeyPubKeyWithDB(walletdb
, secret
, pubkey
);
269 bool CWallet::AddCryptedKey(const CPubKey
&vchPubKey
,
270 const std::vector
<unsigned char> &vchCryptedSecret
)
272 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey
, vchCryptedSecret
))
276 if (pwalletdbEncryption
)
277 return pwalletdbEncryption
->WriteCryptedKey(vchPubKey
,
279 mapKeyMetadata
[vchPubKey
.GetID()]);
281 return CWalletDB(*dbw
).WriteCryptedKey(vchPubKey
,
283 mapKeyMetadata
[vchPubKey
.GetID()]);
287 bool CWallet::LoadKeyMetadata(const CTxDestination
& keyID
, const CKeyMetadata
&meta
)
289 AssertLockHeld(cs_wallet
); // mapKeyMetadata
290 UpdateTimeFirstKey(meta
.nCreateTime
);
291 mapKeyMetadata
[keyID
] = meta
;
295 bool CWallet::LoadCryptedKey(const CPubKey
&vchPubKey
, const std::vector
<unsigned char> &vchCryptedSecret
)
297 return CCryptoKeyStore::AddCryptedKey(vchPubKey
, vchCryptedSecret
);
301 * Update wallet first key creation time. This should be called whenever keys
302 * are added to the wallet, with the oldest key creation time.
304 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime
)
306 AssertLockHeld(cs_wallet
);
307 if (nCreateTime
<= 1) {
308 // Cannot determine birthday information, so set the wallet birthday to
309 // the beginning of time.
311 } else if (!nTimeFirstKey
|| nCreateTime
< nTimeFirstKey
) {
312 nTimeFirstKey
= nCreateTime
;
316 bool CWallet::AddCScript(const CScript
& redeemScript
)
318 if (!CCryptoKeyStore::AddCScript(redeemScript
))
320 return CWalletDB(*dbw
).WriteCScript(Hash160(redeemScript
), redeemScript
);
323 bool CWallet::LoadCScript(const CScript
& redeemScript
)
325 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
326 * that never can be redeemed. However, old wallets may still contain
327 * these. Do not add them to the wallet and warn. */
328 if (redeemScript
.size() > MAX_SCRIPT_ELEMENT_SIZE
)
330 std::string strAddr
= EncodeDestination(CScriptID(redeemScript
));
331 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",
332 __func__
, redeemScript
.size(), MAX_SCRIPT_ELEMENT_SIZE
, strAddr
);
336 return CCryptoKeyStore::AddCScript(redeemScript
);
339 bool CWallet::AddWatchOnly(const CScript
& dest
)
341 if (!CCryptoKeyStore::AddWatchOnly(dest
))
343 const CKeyMetadata
& meta
= mapKeyMetadata
[CScriptID(dest
)];
344 UpdateTimeFirstKey(meta
.nCreateTime
);
345 NotifyWatchonlyChanged(true);
346 return CWalletDB(*dbw
).WriteWatchOnly(dest
, meta
);
349 bool CWallet::AddWatchOnly(const CScript
& dest
, int64_t nCreateTime
)
351 mapKeyMetadata
[CScriptID(dest
)].nCreateTime
= nCreateTime
;
352 return AddWatchOnly(dest
);
355 bool CWallet::RemoveWatchOnly(const CScript
&dest
)
357 AssertLockHeld(cs_wallet
);
358 if (!CCryptoKeyStore::RemoveWatchOnly(dest
))
360 if (!HaveWatchOnly())
361 NotifyWatchonlyChanged(false);
362 if (!CWalletDB(*dbw
).EraseWatchOnly(dest
))
368 bool CWallet::LoadWatchOnly(const CScript
&dest
)
370 return CCryptoKeyStore::AddWatchOnly(dest
);
373 bool CWallet::Unlock(const SecureString
& strWalletPassphrase
)
376 CKeyingMaterial _vMasterKey
;
380 for (const MasterKeyMap::value_type
& pMasterKey
: mapMasterKeys
)
382 if(!crypter
.SetKeyFromPassphrase(strWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
))
384 if (!crypter
.Decrypt(pMasterKey
.second
.vchCryptedKey
, _vMasterKey
))
385 continue; // try another master key
386 if (CCryptoKeyStore::Unlock(_vMasterKey
))
393 bool CWallet::ChangeWalletPassphrase(const SecureString
& strOldWalletPassphrase
, const SecureString
& strNewWalletPassphrase
)
395 bool fWasLocked
= IsLocked();
402 CKeyingMaterial _vMasterKey
;
403 for (MasterKeyMap::value_type
& pMasterKey
: mapMasterKeys
)
405 if(!crypter
.SetKeyFromPassphrase(strOldWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
))
407 if (!crypter
.Decrypt(pMasterKey
.second
.vchCryptedKey
, _vMasterKey
))
409 if (CCryptoKeyStore::Unlock(_vMasterKey
))
411 int64_t nStartTime
= GetTimeMillis();
412 crypter
.SetKeyFromPassphrase(strNewWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
);
413 pMasterKey
.second
.nDeriveIterations
= static_cast<unsigned int>(pMasterKey
.second
.nDeriveIterations
* (100 / ((double)(GetTimeMillis() - nStartTime
))));
415 nStartTime
= GetTimeMillis();
416 crypter
.SetKeyFromPassphrase(strNewWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
);
417 pMasterKey
.second
.nDeriveIterations
= (pMasterKey
.second
.nDeriveIterations
+ static_cast<unsigned int>(pMasterKey
.second
.nDeriveIterations
* 100 / ((double)(GetTimeMillis() - nStartTime
)))) / 2;
419 if (pMasterKey
.second
.nDeriveIterations
< 25000)
420 pMasterKey
.second
.nDeriveIterations
= 25000;
422 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey
.second
.nDeriveIterations
);
424 if (!crypter
.SetKeyFromPassphrase(strNewWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
))
426 if (!crypter
.Encrypt(_vMasterKey
, pMasterKey
.second
.vchCryptedKey
))
428 CWalletDB(*dbw
).WriteMasterKey(pMasterKey
.first
, pMasterKey
.second
);
439 void CWallet::SetBestChain(const CBlockLocator
& loc
)
441 CWalletDB
walletdb(*dbw
);
442 walletdb
.WriteBestBlock(loc
);
445 bool CWallet::SetMinVersion(enum WalletFeature nVersion
, CWalletDB
* pwalletdbIn
, bool fExplicit
)
447 LOCK(cs_wallet
); // nWalletVersion
448 if (nWalletVersion
>= nVersion
)
451 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
452 if (fExplicit
&& nVersion
> nWalletMaxVersion
)
453 nVersion
= FEATURE_LATEST
;
455 nWalletVersion
= nVersion
;
457 if (nVersion
> nWalletMaxVersion
)
458 nWalletMaxVersion
= nVersion
;
461 CWalletDB
* pwalletdb
= pwalletdbIn
? pwalletdbIn
: new CWalletDB(*dbw
);
462 if (nWalletVersion
> 40000)
463 pwalletdb
->WriteMinVersion(nWalletVersion
);
471 bool CWallet::SetMaxVersion(int nVersion
)
473 LOCK(cs_wallet
); // nWalletVersion, nWalletMaxVersion
474 // cannot downgrade below current version
475 if (nWalletVersion
> nVersion
)
478 nWalletMaxVersion
= nVersion
;
483 std::set
<uint256
> CWallet::GetConflicts(const uint256
& txid
) const
485 std::set
<uint256
> result
;
486 AssertLockHeld(cs_wallet
);
488 std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.find(txid
);
489 if (it
== mapWallet
.end())
491 const CWalletTx
& wtx
= it
->second
;
493 std::pair
<TxSpends::const_iterator
, TxSpends::const_iterator
> range
;
495 for (const CTxIn
& txin
: wtx
.tx
->vin
)
497 if (mapTxSpends
.count(txin
.prevout
) <= 1)
498 continue; // No conflict if zero or one spends
499 range
= mapTxSpends
.equal_range(txin
.prevout
);
500 for (TxSpends::const_iterator _it
= range
.first
; _it
!= range
.second
; ++_it
)
501 result
.insert(_it
->second
);
506 bool CWallet::HasWalletSpend(const uint256
& txid
) const
508 AssertLockHeld(cs_wallet
);
509 auto iter
= mapTxSpends
.lower_bound(COutPoint(txid
, 0));
510 return (iter
!= mapTxSpends
.end() && iter
->first
.hash
== txid
);
513 void CWallet::Flush(bool shutdown
)
515 dbw
->Flush(shutdown
);
518 void CWallet::SyncMetaData(std::pair
<TxSpends::iterator
, TxSpends::iterator
> range
)
520 // We want all the wallet transactions in range to have the same metadata as
521 // the oldest (smallest nOrderPos).
522 // So: find smallest nOrderPos:
524 int nMinOrderPos
= std::numeric_limits
<int>::max();
525 const CWalletTx
* copyFrom
= nullptr;
526 for (TxSpends::iterator it
= range
.first
; it
!= range
.second
; ++it
)
528 const uint256
& hash
= it
->second
;
529 int n
= mapWallet
[hash
].nOrderPos
;
530 if (n
< nMinOrderPos
)
533 copyFrom
= &mapWallet
[hash
];
539 // Now copy data from copyFrom to rest:
540 for (TxSpends::iterator it
= range
.first
; it
!= range
.second
; ++it
)
542 const uint256
& hash
= it
->second
;
543 CWalletTx
* copyTo
= &mapWallet
[hash
];
544 if (copyFrom
== copyTo
) continue;
545 assert(copyFrom
&& "Oldest wallet transaction in range assumed to have been found.");
546 if (!copyFrom
->IsEquivalentTo(*copyTo
)) continue;
547 copyTo
->mapValue
= copyFrom
->mapValue
;
548 copyTo
->vOrderForm
= copyFrom
->vOrderForm
;
549 // fTimeReceivedIsTxTime not copied on purpose
550 // nTimeReceived not copied on purpose
551 copyTo
->nTimeSmart
= copyFrom
->nTimeSmart
;
552 copyTo
->fFromMe
= copyFrom
->fFromMe
;
553 copyTo
->strFromAccount
= copyFrom
->strFromAccount
;
554 // nOrderPos not copied on purpose
555 // cached members not copied on purpose
560 * Outpoint is spent if any non-conflicted transaction
563 bool CWallet::IsSpent(const uint256
& hash
, unsigned int n
) const
565 const COutPoint
outpoint(hash
, n
);
566 std::pair
<TxSpends::const_iterator
, TxSpends::const_iterator
> range
;
567 range
= mapTxSpends
.equal_range(outpoint
);
569 for (TxSpends::const_iterator it
= range
.first
; it
!= range
.second
; ++it
)
571 const uint256
& wtxid
= it
->second
;
572 std::map
<uint256
, CWalletTx
>::const_iterator mit
= mapWallet
.find(wtxid
);
573 if (mit
!= mapWallet
.end()) {
574 int depth
= mit
->second
.GetDepthInMainChain();
575 if (depth
> 0 || (depth
== 0 && !mit
->second
.isAbandoned()))
576 return true; // Spent
582 void CWallet::AddToSpends(const COutPoint
& outpoint
, const uint256
& wtxid
)
584 mapTxSpends
.insert(std::make_pair(outpoint
, wtxid
));
586 std::pair
<TxSpends::iterator
, TxSpends::iterator
> range
;
587 range
= mapTxSpends
.equal_range(outpoint
);
592 void CWallet::AddToSpends(const uint256
& wtxid
)
594 auto it
= mapWallet
.find(wtxid
);
595 assert(it
!= mapWallet
.end());
596 CWalletTx
& thisTx
= it
->second
;
597 if (thisTx
.IsCoinBase()) // Coinbases don't spend anything!
600 for (const CTxIn
& txin
: thisTx
.tx
->vin
)
601 AddToSpends(txin
.prevout
, wtxid
);
604 bool CWallet::EncryptWallet(const SecureString
& strWalletPassphrase
)
609 CKeyingMaterial _vMasterKey
;
611 _vMasterKey
.resize(WALLET_CRYPTO_KEY_SIZE
);
612 GetStrongRandBytes(&_vMasterKey
[0], WALLET_CRYPTO_KEY_SIZE
);
614 CMasterKey kMasterKey
;
616 kMasterKey
.vchSalt
.resize(WALLET_CRYPTO_SALT_SIZE
);
617 GetStrongRandBytes(&kMasterKey
.vchSalt
[0], WALLET_CRYPTO_SALT_SIZE
);
620 int64_t nStartTime
= GetTimeMillis();
621 crypter
.SetKeyFromPassphrase(strWalletPassphrase
, kMasterKey
.vchSalt
, 25000, kMasterKey
.nDerivationMethod
);
622 kMasterKey
.nDeriveIterations
= static_cast<unsigned int>(2500000 / ((double)(GetTimeMillis() - nStartTime
)));
624 nStartTime
= GetTimeMillis();
625 crypter
.SetKeyFromPassphrase(strWalletPassphrase
, kMasterKey
.vchSalt
, kMasterKey
.nDeriveIterations
, kMasterKey
.nDerivationMethod
);
626 kMasterKey
.nDeriveIterations
= (kMasterKey
.nDeriveIterations
+ static_cast<unsigned int>(kMasterKey
.nDeriveIterations
* 100 / ((double)(GetTimeMillis() - nStartTime
)))) / 2;
628 if (kMasterKey
.nDeriveIterations
< 25000)
629 kMasterKey
.nDeriveIterations
= 25000;
631 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey
.nDeriveIterations
);
633 if (!crypter
.SetKeyFromPassphrase(strWalletPassphrase
, kMasterKey
.vchSalt
, kMasterKey
.nDeriveIterations
, kMasterKey
.nDerivationMethod
))
635 if (!crypter
.Encrypt(_vMasterKey
, kMasterKey
.vchCryptedKey
))
640 mapMasterKeys
[++nMasterKeyMaxID
] = kMasterKey
;
641 assert(!pwalletdbEncryption
);
642 pwalletdbEncryption
= new CWalletDB(*dbw
);
643 if (!pwalletdbEncryption
->TxnBegin()) {
644 delete pwalletdbEncryption
;
645 pwalletdbEncryption
= nullptr;
648 pwalletdbEncryption
->WriteMasterKey(nMasterKeyMaxID
, kMasterKey
);
650 if (!EncryptKeys(_vMasterKey
))
652 pwalletdbEncryption
->TxnAbort();
653 delete pwalletdbEncryption
;
654 // We now probably have half of our keys encrypted in memory, and half not...
655 // die and let the user reload the unencrypted wallet.
659 // Encryption was introduced in version 0.4.0
660 SetMinVersion(FEATURE_WALLETCRYPT
, pwalletdbEncryption
, true);
662 if (!pwalletdbEncryption
->TxnCommit()) {
663 delete pwalletdbEncryption
;
664 // We now have keys encrypted in memory, but not on disk...
665 // die to avoid confusion and let the user reload the unencrypted wallet.
669 delete pwalletdbEncryption
;
670 pwalletdbEncryption
= nullptr;
673 Unlock(strWalletPassphrase
);
675 // if we are using HD, replace the HD master key (seed) with a new one
677 if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
685 // Need to completely rewrite the wallet file; if we don't, bdb might keep
686 // bits of the unencrypted private key in slack space in the database file.
690 NotifyStatusChanged(this);
695 DBErrors
CWallet::ReorderTransactions()
698 CWalletDB
walletdb(*dbw
);
700 // Old wallets didn't have any defined order for transactions
701 // Probably a bad idea to change the output of this
703 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
704 typedef std::pair
<CWalletTx
*, CAccountingEntry
*> TxPair
;
705 typedef std::multimap
<int64_t, TxPair
> TxItems
;
708 for (std::map
<uint256
, CWalletTx
>::iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
710 CWalletTx
* wtx
= &((*it
).second
);
711 txByTime
.insert(std::make_pair(wtx
->nTimeReceived
, TxPair(wtx
, nullptr)));
713 std::list
<CAccountingEntry
> acentries
;
714 walletdb
.ListAccountCreditDebit("", acentries
);
715 for (CAccountingEntry
& entry
: acentries
)
717 txByTime
.insert(std::make_pair(entry
.nTime
, TxPair(nullptr, &entry
)));
721 std::vector
<int64_t> nOrderPosOffsets
;
722 for (TxItems::iterator it
= txByTime
.begin(); it
!= txByTime
.end(); ++it
)
724 CWalletTx
*const pwtx
= (*it
).second
.first
;
725 CAccountingEntry
*const pacentry
= (*it
).second
.second
;
726 int64_t& nOrderPos
= (pwtx
!= nullptr) ? pwtx
->nOrderPos
: pacentry
->nOrderPos
;
730 nOrderPos
= nOrderPosNext
++;
731 nOrderPosOffsets
.push_back(nOrderPos
);
735 if (!walletdb
.WriteTx(*pwtx
))
739 if (!walletdb
.WriteAccountingEntry(pacentry
->nEntryNo
, *pacentry
))
744 int64_t nOrderPosOff
= 0;
745 for (const int64_t& nOffsetStart
: nOrderPosOffsets
)
747 if (nOrderPos
>= nOffsetStart
)
750 nOrderPos
+= nOrderPosOff
;
751 nOrderPosNext
= std::max(nOrderPosNext
, nOrderPos
+ 1);
756 // Since we're changing the order, write it back
759 if (!walletdb
.WriteTx(*pwtx
))
763 if (!walletdb
.WriteAccountingEntry(pacentry
->nEntryNo
, *pacentry
))
767 walletdb
.WriteOrderPosNext(nOrderPosNext
);
772 int64_t CWallet::IncOrderPosNext(CWalletDB
*pwalletdb
)
774 AssertLockHeld(cs_wallet
); // nOrderPosNext
775 int64_t nRet
= nOrderPosNext
++;
777 pwalletdb
->WriteOrderPosNext(nOrderPosNext
);
779 CWalletDB(*dbw
).WriteOrderPosNext(nOrderPosNext
);
784 bool CWallet::AccountMove(std::string strFrom
, std::string strTo
, CAmount nAmount
, std::string strComment
)
786 CWalletDB
walletdb(*dbw
);
787 if (!walletdb
.TxnBegin())
790 int64_t nNow
= GetAdjustedTime();
793 CAccountingEntry debit
;
794 debit
.nOrderPos
= IncOrderPosNext(&walletdb
);
795 debit
.strAccount
= strFrom
;
796 debit
.nCreditDebit
= -nAmount
;
798 debit
.strOtherAccount
= strTo
;
799 debit
.strComment
= strComment
;
800 AddAccountingEntry(debit
, &walletdb
);
803 CAccountingEntry credit
;
804 credit
.nOrderPos
= IncOrderPosNext(&walletdb
);
805 credit
.strAccount
= strTo
;
806 credit
.nCreditDebit
= nAmount
;
808 credit
.strOtherAccount
= strFrom
;
809 credit
.strComment
= strComment
;
810 AddAccountingEntry(credit
, &walletdb
);
812 if (!walletdb
.TxnCommit())
818 bool CWallet::GetAccountPubkey(CPubKey
&pubKey
, std::string strAccount
, bool bForceNew
)
820 CWalletDB
walletdb(*dbw
);
823 walletdb
.ReadAccount(strAccount
, account
);
826 if (!account
.vchPubKey
.IsValid())
829 // Check if the current key has been used
830 CScript scriptPubKey
= GetScriptForDestination(account
.vchPubKey
.GetID());
831 for (std::map
<uint256
, CWalletTx
>::iterator it
= mapWallet
.begin();
832 it
!= mapWallet
.end() && account
.vchPubKey
.IsValid();
834 for (const CTxOut
& txout
: (*it
).second
.tx
->vout
)
835 if (txout
.scriptPubKey
== scriptPubKey
) {
842 // Generate a new key
844 if (!GetKeyFromPool(account
.vchPubKey
, false))
847 SetAddressBook(account
.vchPubKey
.GetID(), strAccount
, "receive");
848 walletdb
.WriteAccount(strAccount
, account
);
851 pubKey
= account
.vchPubKey
;
856 void CWallet::MarkDirty()
860 for (std::pair
<const uint256
, CWalletTx
>& item
: mapWallet
)
861 item
.second
.MarkDirty();
865 bool CWallet::MarkReplaced(const uint256
& originalHash
, const uint256
& newHash
)
869 auto mi
= mapWallet
.find(originalHash
);
871 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
872 assert(mi
!= mapWallet
.end());
874 CWalletTx
& wtx
= (*mi
).second
;
876 // Ensure for now that we're not overwriting data
877 assert(wtx
.mapValue
.count("replaced_by_txid") == 0);
879 wtx
.mapValue
["replaced_by_txid"] = newHash
.ToString();
881 CWalletDB
walletdb(*dbw
, "r+");
884 if (!walletdb
.WriteTx(wtx
)) {
885 LogPrintf("%s: Updating walletdb tx %s failed", __func__
, wtx
.GetHash().ToString());
889 NotifyTransactionChanged(this, originalHash
, CT_UPDATED
);
894 bool CWallet::AddToWallet(const CWalletTx
& wtxIn
, bool fFlushOnClose
)
898 CWalletDB
walletdb(*dbw
, "r+", fFlushOnClose
);
900 uint256 hash
= wtxIn
.GetHash();
902 // Inserts only if not already there, returns tx inserted or tx found
903 std::pair
<std::map
<uint256
, CWalletTx
>::iterator
, bool> ret
= mapWallet
.insert(std::make_pair(hash
, wtxIn
));
904 CWalletTx
& wtx
= (*ret
.first
).second
;
905 wtx
.BindWallet(this);
906 bool fInsertedNew
= ret
.second
;
909 wtx
.nTimeReceived
= GetAdjustedTime();
910 wtx
.nOrderPos
= IncOrderPosNext(&walletdb
);
911 wtxOrdered
.insert(std::make_pair(wtx
.nOrderPos
, TxPair(&wtx
, nullptr)));
912 wtx
.nTimeSmart
= ComputeTimeSmart(wtx
);
916 bool fUpdated
= false;
920 if (!wtxIn
.hashUnset() && wtxIn
.hashBlock
!= wtx
.hashBlock
)
922 wtx
.hashBlock
= wtxIn
.hashBlock
;
925 // If no longer abandoned, update
926 if (wtxIn
.hashBlock
.IsNull() && wtx
.isAbandoned())
928 wtx
.hashBlock
= wtxIn
.hashBlock
;
931 if (wtxIn
.nIndex
!= -1 && (wtxIn
.nIndex
!= wtx
.nIndex
))
933 wtx
.nIndex
= wtxIn
.nIndex
;
936 if (wtxIn
.fFromMe
&& wtxIn
.fFromMe
!= wtx
.fFromMe
)
938 wtx
.fFromMe
= wtxIn
.fFromMe
;
941 // If we have a witness-stripped version of this transaction, and we
942 // see a new version with a witness, then we must be upgrading a pre-segwit
943 // wallet. Store the new version of the transaction with the witness,
944 // as the stripped-version must be invalid.
945 // TODO: Store all versions of the transaction, instead of just one.
946 if (wtxIn
.tx
->HasWitness() && !wtx
.tx
->HasWitness()) {
953 LogPrintf("AddToWallet %s %s%s\n", wtxIn
.GetHash().ToString(), (fInsertedNew
? "new" : ""), (fUpdated
? "update" : ""));
956 if (fInsertedNew
|| fUpdated
)
957 if (!walletdb
.WriteTx(wtx
))
960 // Break debit/credit balance caches:
963 // Notify UI of new or updated transaction
964 NotifyTransactionChanged(this, hash
, fInsertedNew
? CT_NEW
: CT_UPDATED
);
966 // notify an external script when a wallet transaction comes in or is updated
967 std::string strCmd
= gArgs
.GetArg("-walletnotify", "");
971 boost::replace_all(strCmd
, "%s", wtxIn
.GetHash().GetHex());
972 boost::thread
t(runCommand
, strCmd
); // thread runs free
978 bool CWallet::LoadToWallet(const CWalletTx
& wtxIn
)
980 uint256 hash
= wtxIn
.GetHash();
982 mapWallet
[hash
] = wtxIn
;
983 CWalletTx
& wtx
= mapWallet
[hash
];
984 wtx
.BindWallet(this);
985 wtxOrdered
.insert(std::make_pair(wtx
.nOrderPos
, TxPair(&wtx
, nullptr)));
987 for (const CTxIn
& txin
: wtx
.tx
->vin
) {
988 auto it
= mapWallet
.find(txin
.prevout
.hash
);
989 if (it
!= mapWallet
.end()) {
990 CWalletTx
& prevtx
= it
->second
;
991 if (prevtx
.nIndex
== -1 && !prevtx
.hashUnset()) {
992 MarkConflicted(prevtx
.hashBlock
, wtx
.GetHash());
1001 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
1002 * be set when the transaction was known to be included in a block. When
1003 * pIndex == nullptr, then wallet state is not updated in AddToWallet, but
1004 * notifications happen and cached balances are marked dirty.
1006 * If fUpdate is true, existing transactions will be updated.
1007 * TODO: One exception to this is that the abandoned state is cleared under the
1008 * assumption that any further notification of a transaction that was considered
1009 * abandoned is an indication that it is not safe to be considered abandoned.
1010 * Abandoned state should probably be more carefully tracked via different
1011 * posInBlock signals or by checking mempool presence when necessary.
1013 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef
& ptx
, const CBlockIndex
* pIndex
, int posInBlock
, bool fUpdate
)
1015 const CTransaction
& tx
= *ptx
;
1017 AssertLockHeld(cs_wallet
);
1019 if (pIndex
!= nullptr) {
1020 for (const CTxIn
& txin
: tx
.vin
) {
1021 std::pair
<TxSpends::const_iterator
, TxSpends::const_iterator
> range
= mapTxSpends
.equal_range(txin
.prevout
);
1022 while (range
.first
!= range
.second
) {
1023 if (range
.first
->second
!= tx
.GetHash()) {
1024 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
);
1025 MarkConflicted(pIndex
->GetBlockHash(), range
.first
->second
);
1032 bool fExisted
= mapWallet
.count(tx
.GetHash()) != 0;
1033 if (fExisted
&& !fUpdate
) return false;
1034 if (fExisted
|| IsMine(tx
) || IsFromMe(tx
))
1036 /* Check if any keys in the wallet keypool that were supposed to be unused
1037 * have appeared in a new transaction. If so, remove those keys from the keypool.
1038 * This can happen when restoring an old wallet backup that does not contain
1039 * the mostly recently created transactions from newer versions of the wallet.
1042 // loop though all outputs
1043 for (const CTxOut
& txout
: tx
.vout
) {
1044 // extract addresses and check if they match with an unused keypool key
1045 std::vector
<CKeyID
> vAffected
;
1046 CAffectedKeysVisitor(*this, vAffected
).Process(txout
.scriptPubKey
);
1047 for (const CKeyID
&keyid
: vAffected
) {
1048 std::map
<CKeyID
, int64_t>::const_iterator mi
= m_pool_key_to_index
.find(keyid
);
1049 if (mi
!= m_pool_key_to_index
.end()) {
1050 LogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__
);
1051 MarkReserveKeysAsUsed(mi
->second
);
1053 if (!TopUpKeyPool()) {
1054 LogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__
);
1060 CWalletTx
wtx(this, ptx
);
1062 // Get merkle branch if transaction was found in a block
1063 if (pIndex
!= nullptr)
1064 wtx
.SetMerkleBranch(pIndex
, posInBlock
);
1066 return AddToWallet(wtx
, false);
1072 bool CWallet::TransactionCanBeAbandoned(const uint256
& hashTx
) const
1074 LOCK2(cs_main
, cs_wallet
);
1075 const CWalletTx
* wtx
= GetWalletTx(hashTx
);
1076 return wtx
&& !wtx
->isAbandoned() && wtx
->GetDepthInMainChain() <= 0 && !wtx
->InMempool();
1079 bool CWallet::AbandonTransaction(const uint256
& hashTx
)
1081 LOCK2(cs_main
, cs_wallet
);
1083 CWalletDB
walletdb(*dbw
, "r+");
1085 std::set
<uint256
> todo
;
1086 std::set
<uint256
> done
;
1088 // Can't mark abandoned if confirmed or in mempool
1089 auto it
= mapWallet
.find(hashTx
);
1090 assert(it
!= mapWallet
.end());
1091 CWalletTx
& origtx
= it
->second
;
1092 if (origtx
.GetDepthInMainChain() > 0 || origtx
.InMempool()) {
1096 todo
.insert(hashTx
);
1098 while (!todo
.empty()) {
1099 uint256 now
= *todo
.begin();
1102 auto it
= mapWallet
.find(now
);
1103 assert(it
!= mapWallet
.end());
1104 CWalletTx
& wtx
= it
->second
;
1105 int currentconfirm
= wtx
.GetDepthInMainChain();
1106 // If the orig tx was not in block, none of its spends can be
1107 assert(currentconfirm
<= 0);
1108 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1109 if (currentconfirm
== 0 && !wtx
.isAbandoned()) {
1110 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1111 assert(!wtx
.InMempool());
1115 walletdb
.WriteTx(wtx
);
1116 NotifyTransactionChanged(this, wtx
.GetHash(), CT_UPDATED
);
1117 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1118 TxSpends::const_iterator iter
= mapTxSpends
.lower_bound(COutPoint(hashTx
, 0));
1119 while (iter
!= mapTxSpends
.end() && iter
->first
.hash
== now
) {
1120 if (!done
.count(iter
->second
)) {
1121 todo
.insert(iter
->second
);
1125 // If a transaction changes 'conflicted' state, that changes the balance
1126 // available of the outputs it spends. So force those to be recomputed
1127 for (const CTxIn
& txin
: wtx
.tx
->vin
)
1129 auto it
= mapWallet
.find(txin
.prevout
.hash
);
1130 if (it
!= mapWallet
.end()) {
1131 it
->second
.MarkDirty();
1140 void CWallet::MarkConflicted(const uint256
& hashBlock
, const uint256
& hashTx
)
1142 LOCK2(cs_main
, cs_wallet
);
1144 int conflictconfirms
= 0;
1145 if (mapBlockIndex
.count(hashBlock
)) {
1146 CBlockIndex
* pindex
= mapBlockIndex
[hashBlock
];
1147 if (chainActive
.Contains(pindex
)) {
1148 conflictconfirms
= -(chainActive
.Height() - pindex
->nHeight
+ 1);
1151 // If number of conflict confirms cannot be determined, this means
1152 // that the block is still unknown or not yet part of the main chain,
1153 // for example when loading the wallet during a reindex. Do nothing in that
1155 if (conflictconfirms
>= 0)
1158 // Do not flush the wallet here for performance reasons
1159 CWalletDB
walletdb(*dbw
, "r+", false);
1161 std::set
<uint256
> todo
;
1162 std::set
<uint256
> done
;
1164 todo
.insert(hashTx
);
1166 while (!todo
.empty()) {
1167 uint256 now
= *todo
.begin();
1170 auto it
= mapWallet
.find(now
);
1171 assert(it
!= mapWallet
.end());
1172 CWalletTx
& wtx
= it
->second
;
1173 int currentconfirm
= wtx
.GetDepthInMainChain();
1174 if (conflictconfirms
< currentconfirm
) {
1175 // Block is 'more conflicted' than current confirm; update.
1176 // Mark transaction as conflicted with this block.
1178 wtx
.hashBlock
= hashBlock
;
1180 walletdb
.WriteTx(wtx
);
1181 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1182 TxSpends::const_iterator iter
= mapTxSpends
.lower_bound(COutPoint(now
, 0));
1183 while (iter
!= mapTxSpends
.end() && iter
->first
.hash
== now
) {
1184 if (!done
.count(iter
->second
)) {
1185 todo
.insert(iter
->second
);
1189 // If a transaction changes 'conflicted' state, that changes the balance
1190 // available of the outputs it spends. So force those to be recomputed
1191 for (const CTxIn
& txin
: wtx
.tx
->vin
) {
1192 auto it
= mapWallet
.find(txin
.prevout
.hash
);
1193 if (it
!= mapWallet
.end()) {
1194 it
->second
.MarkDirty();
1201 void CWallet::SyncTransaction(const CTransactionRef
& ptx
, const CBlockIndex
*pindex
, int posInBlock
) {
1202 const CTransaction
& tx
= *ptx
;
1204 if (!AddToWalletIfInvolvingMe(ptx
, pindex
, posInBlock
, true))
1205 return; // Not one of ours
1207 // If a transaction changes 'conflicted' state, that changes the balance
1208 // available of the outputs it spends. So force those to be
1209 // recomputed, also:
1210 for (const CTxIn
& txin
: tx
.vin
) {
1211 auto it
= mapWallet
.find(txin
.prevout
.hash
);
1212 if (it
!= mapWallet
.end()) {
1213 it
->second
.MarkDirty();
1218 void CWallet::TransactionAddedToMempool(const CTransactionRef
& ptx
) {
1219 LOCK2(cs_main
, cs_wallet
);
1220 SyncTransaction(ptx
);
1222 auto it
= mapWallet
.find(ptx
->GetHash());
1223 if (it
!= mapWallet
.end()) {
1224 it
->second
.fInMempool
= true;
1228 void CWallet::TransactionRemovedFromMempool(const CTransactionRef
&ptx
) {
1230 auto it
= mapWallet
.find(ptx
->GetHash());
1231 if (it
!= mapWallet
.end()) {
1232 it
->second
.fInMempool
= false;
1236 void CWallet::BlockConnected(const std::shared_ptr
<const CBlock
>& pblock
, const CBlockIndex
*pindex
, const std::vector
<CTransactionRef
>& vtxConflicted
) {
1237 LOCK2(cs_main
, cs_wallet
);
1238 // TODO: Temporarily ensure that mempool removals are notified before
1239 // connected transactions. This shouldn't matter, but the abandoned
1240 // state of transactions in our wallet is currently cleared when we
1241 // receive another notification and there is a race condition where
1242 // notification of a connected conflict might cause an outside process
1243 // to abandon a transaction and then have it inadvertently cleared by
1244 // the notification that the conflicted transaction was evicted.
1246 for (const CTransactionRef
& ptx
: vtxConflicted
) {
1247 SyncTransaction(ptx
);
1248 TransactionRemovedFromMempool(ptx
);
1250 for (size_t i
= 0; i
< pblock
->vtx
.size(); i
++) {
1251 SyncTransaction(pblock
->vtx
[i
], pindex
, i
);
1252 TransactionRemovedFromMempool(pblock
->vtx
[i
]);
1255 m_last_block_processed
= pindex
;
1258 void CWallet::BlockDisconnected(const std::shared_ptr
<const CBlock
>& pblock
) {
1259 LOCK2(cs_main
, cs_wallet
);
1261 for (const CTransactionRef
& ptx
: pblock
->vtx
) {
1262 SyncTransaction(ptx
);
1268 void CWallet::BlockUntilSyncedToCurrentChain() {
1269 AssertLockNotHeld(cs_main
);
1270 AssertLockNotHeld(cs_wallet
);
1273 // Skip the queue-draining stuff if we know we're caught up with
1274 // chainActive.Tip()...
1275 // We could also take cs_wallet here, and call m_last_block_processed
1276 // protected by cs_wallet instead of cs_main, but as long as we need
1277 // cs_main here anyway, its easier to just call it cs_main-protected.
1279 const CBlockIndex
* initialChainTip
= chainActive
.Tip();
1281 if (m_last_block_processed
->GetAncestor(initialChainTip
->nHeight
) == initialChainTip
) {
1286 // ...otherwise put a callback in the validation interface queue and wait
1287 // for the queue to drain enough to execute it (indicating we are caught up
1288 // at least with the time we entered this function).
1290 std::promise
<void> promise
;
1291 CallFunctionInValidationInterfaceQueue([&promise
] {
1292 promise
.set_value();
1294 promise
.get_future().wait();
1298 isminetype
CWallet::IsMine(const CTxIn
&txin
) const
1302 std::map
<uint256
, CWalletTx
>::const_iterator mi
= mapWallet
.find(txin
.prevout
.hash
);
1303 if (mi
!= mapWallet
.end())
1305 const CWalletTx
& prev
= (*mi
).second
;
1306 if (txin
.prevout
.n
< prev
.tx
->vout
.size())
1307 return IsMine(prev
.tx
->vout
[txin
.prevout
.n
]);
1313 // Note that this function doesn't distinguish between a 0-valued input,
1314 // and a not-"is mine" (according to the filter) input.
1315 CAmount
CWallet::GetDebit(const CTxIn
&txin
, const isminefilter
& filter
) const
1319 std::map
<uint256
, CWalletTx
>::const_iterator mi
= mapWallet
.find(txin
.prevout
.hash
);
1320 if (mi
!= mapWallet
.end())
1322 const CWalletTx
& prev
= (*mi
).second
;
1323 if (txin
.prevout
.n
< prev
.tx
->vout
.size())
1324 if (IsMine(prev
.tx
->vout
[txin
.prevout
.n
]) & filter
)
1325 return prev
.tx
->vout
[txin
.prevout
.n
].nValue
;
1331 isminetype
CWallet::IsMine(const CTxOut
& txout
) const
1333 return ::IsMine(*this, txout
.scriptPubKey
);
1336 CAmount
CWallet::GetCredit(const CTxOut
& txout
, const isminefilter
& filter
) const
1338 if (!MoneyRange(txout
.nValue
))
1339 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1340 return ((IsMine(txout
) & filter
) ? txout
.nValue
: 0);
1343 bool CWallet::IsChange(const CTxOut
& txout
) const
1345 // TODO: fix handling of 'change' outputs. The assumption is that any
1346 // payment to a script that is ours, but is not in the address book
1347 // is change. That assumption is likely to break when we implement multisignature
1348 // wallets that return change back into a multi-signature-protected address;
1349 // a better way of identifying which outputs are 'the send' and which are
1350 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1351 // which output, if any, was change).
1352 if (::IsMine(*this, txout
.scriptPubKey
))
1354 CTxDestination address
;
1355 if (!ExtractDestination(txout
.scriptPubKey
, address
))
1359 if (!mapAddressBook
.count(address
))
1365 CAmount
CWallet::GetChange(const CTxOut
& txout
) const
1367 if (!MoneyRange(txout
.nValue
))
1368 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1369 return (IsChange(txout
) ? txout
.nValue
: 0);
1372 bool CWallet::IsMine(const CTransaction
& tx
) const
1374 for (const CTxOut
& txout
: tx
.vout
)
1380 bool CWallet::IsFromMe(const CTransaction
& tx
) const
1382 return (GetDebit(tx
, ISMINE_ALL
) > 0);
1385 CAmount
CWallet::GetDebit(const CTransaction
& tx
, const isminefilter
& filter
) const
1388 for (const CTxIn
& txin
: tx
.vin
)
1390 nDebit
+= GetDebit(txin
, filter
);
1391 if (!MoneyRange(nDebit
))
1392 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1397 bool CWallet::IsAllFromMe(const CTransaction
& tx
, const isminefilter
& filter
) const
1401 for (const CTxIn
& txin
: tx
.vin
)
1403 auto mi
= mapWallet
.find(txin
.prevout
.hash
);
1404 if (mi
== mapWallet
.end())
1405 return false; // any unknown inputs can't be from us
1407 const CWalletTx
& prev
= (*mi
).second
;
1409 if (txin
.prevout
.n
>= prev
.tx
->vout
.size())
1410 return false; // invalid input!
1412 if (!(IsMine(prev
.tx
->vout
[txin
.prevout
.n
]) & filter
))
1418 CAmount
CWallet::GetCredit(const CTransaction
& tx
, const isminefilter
& filter
) const
1420 CAmount nCredit
= 0;
1421 for (const CTxOut
& txout
: tx
.vout
)
1423 nCredit
+= GetCredit(txout
, filter
);
1424 if (!MoneyRange(nCredit
))
1425 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1430 CAmount
CWallet::GetChange(const CTransaction
& tx
) const
1432 CAmount nChange
= 0;
1433 for (const CTxOut
& txout
: tx
.vout
)
1435 nChange
+= GetChange(txout
);
1436 if (!MoneyRange(nChange
))
1437 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1442 CPubKey
CWallet::GenerateNewHDMasterKey()
1445 key
.MakeNewKey(true);
1447 int64_t nCreationTime
= GetTime();
1448 CKeyMetadata
metadata(nCreationTime
);
1450 // calculate the pubkey
1451 CPubKey pubkey
= key
.GetPubKey();
1452 assert(key
.VerifyPubKey(pubkey
));
1454 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1455 metadata
.hdKeypath
= "m";
1456 metadata
.hdMasterKeyID
= pubkey
.GetID();
1461 // mem store the metadata
1462 mapKeyMetadata
[pubkey
.GetID()] = metadata
;
1464 // write the key&metadata to the database
1465 if (!AddKeyPubKey(key
, pubkey
))
1466 throw std::runtime_error(std::string(__func__
) + ": AddKeyPubKey failed");
1472 bool CWallet::SetHDMasterKey(const CPubKey
& pubkey
)
1475 // store the keyid (hash160) together with
1476 // the child index counter in the database
1477 // as a hdchain object
1478 CHDChain newHdChain
;
1479 newHdChain
.nVersion
= CanSupportFeature(FEATURE_HD_SPLIT
) ? CHDChain::VERSION_HD_CHAIN_SPLIT
: CHDChain::VERSION_HD_BASE
;
1480 newHdChain
.masterKeyID
= pubkey
.GetID();
1481 SetHDChain(newHdChain
, false);
1486 bool CWallet::SetHDChain(const CHDChain
& chain
, bool memonly
)
1489 if (!memonly
&& !CWalletDB(*dbw
).WriteHDChain(chain
))
1490 throw std::runtime_error(std::string(__func__
) + ": writing chain failed");
1496 bool CWallet::IsHDEnabled() const
1498 return !hdChain
.masterKeyID
.IsNull();
1501 int64_t CWalletTx::GetTxTime() const
1503 int64_t n
= nTimeSmart
;
1504 return n
? n
: nTimeReceived
;
1507 int CWalletTx::GetRequestCount() const
1509 // Returns -1 if it wasn't being tracked
1512 LOCK(pwallet
->cs_wallet
);
1518 std::map
<uint256
, int>::const_iterator mi
= pwallet
->mapRequestCount
.find(hashBlock
);
1519 if (mi
!= pwallet
->mapRequestCount
.end())
1520 nRequests
= (*mi
).second
;
1525 // Did anyone request this transaction?
1526 std::map
<uint256
, int>::const_iterator mi
= pwallet
->mapRequestCount
.find(GetHash());
1527 if (mi
!= pwallet
->mapRequestCount
.end())
1529 nRequests
= (*mi
).second
;
1531 // How about the block it's in?
1532 if (nRequests
== 0 && !hashUnset())
1534 std::map
<uint256
, int>::const_iterator _mi
= pwallet
->mapRequestCount
.find(hashBlock
);
1535 if (_mi
!= pwallet
->mapRequestCount
.end())
1536 nRequests
= (*_mi
).second
;
1538 nRequests
= 1; // If it's in someone else's block it must have got out
1546 void CWalletTx::GetAmounts(std::list
<COutputEntry
>& listReceived
,
1547 std::list
<COutputEntry
>& listSent
, CAmount
& nFee
, std::string
& strSentAccount
, const isminefilter
& filter
) const
1550 listReceived
.clear();
1552 strSentAccount
= strFromAccount
;
1555 CAmount nDebit
= GetDebit(filter
);
1556 if (nDebit
> 0) // debit>0 means we signed/sent this transaction
1558 CAmount nValueOut
= tx
->GetValueOut();
1559 nFee
= nDebit
- nValueOut
;
1563 for (unsigned int i
= 0; i
< tx
->vout
.size(); ++i
)
1565 const CTxOut
& txout
= tx
->vout
[i
];
1566 isminetype fIsMine
= pwallet
->IsMine(txout
);
1567 // Only need to handle txouts if AT LEAST one of these is true:
1568 // 1) they debit from us (sent)
1569 // 2) the output is to us (received)
1572 // Don't report 'change' txouts
1573 if (pwallet
->IsChange(txout
))
1576 else if (!(fIsMine
& filter
))
1579 // In either case, we need to get the destination address
1580 CTxDestination address
;
1582 if (!ExtractDestination(txout
.scriptPubKey
, address
) && !txout
.scriptPubKey
.IsUnspendable())
1584 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1585 this->GetHash().ToString());
1586 address
= CNoDestination();
1589 COutputEntry output
= {address
, txout
.nValue
, (int)i
};
1591 // If we are debited by the transaction, add the output as a "sent" entry
1593 listSent
.push_back(output
);
1595 // If we are receiving the output, add it as a "received" entry
1596 if (fIsMine
& filter
)
1597 listReceived
.push_back(output
);
1603 * Scan active chain for relevant transactions after importing keys. This should
1604 * be called whenever new keys are added to the wallet, with the oldest key
1607 * @return Earliest timestamp that could be successfully scanned from. Timestamp
1608 * returned will be higher than startTime if relevant blocks could not be read.
1610 int64_t CWallet::RescanFromTime(int64_t startTime
, bool update
)
1612 AssertLockHeld(cs_main
);
1613 AssertLockHeld(cs_wallet
);
1615 // Find starting block. May be null if nCreateTime is greater than the
1616 // highest blockchain timestamp, in which case there is nothing that needs
1618 CBlockIndex
* const startBlock
= chainActive
.FindEarliestAtLeast(startTime
- TIMESTAMP_WINDOW
);
1619 LogPrintf("%s: Rescanning last %i blocks\n", __func__
, startBlock
? chainActive
.Height() - startBlock
->nHeight
+ 1 : 0);
1622 const CBlockIndex
* const failedBlock
= ScanForWalletTransactions(startBlock
, nullptr, update
);
1624 return failedBlock
->GetBlockTimeMax() + TIMESTAMP_WINDOW
+ 1;
1631 * Scan the block chain (starting in pindexStart) for transactions
1632 * from or to us. If fUpdate is true, found transactions that already
1633 * exist in the wallet will be updated.
1635 * Returns null if scan was successful. Otherwise, if a complete rescan was not
1636 * possible (due to pruning or corruption), returns pointer to the most recent
1637 * block that could not be scanned.
1639 * If pindexStop is not a nullptr, the scan will stop at the block-index
1640 * defined by pindexStop
1642 CBlockIndex
* CWallet::ScanForWalletTransactions(CBlockIndex
* pindexStart
, CBlockIndex
* pindexStop
, bool fUpdate
)
1644 int64_t nNow
= GetTime();
1645 const CChainParams
& chainParams
= Params();
1648 assert(pindexStop
->nHeight
>= pindexStart
->nHeight
);
1651 CBlockIndex
* pindex
= pindexStart
;
1652 CBlockIndex
* ret
= nullptr;
1654 LOCK2(cs_main
, cs_wallet
);
1655 fAbortRescan
= false;
1656 fScanningWallet
= true;
1658 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1659 double dProgressStart
= GuessVerificationProgress(chainParams
.TxData(), pindex
);
1660 double dProgressTip
= GuessVerificationProgress(chainParams
.TxData(), chainActive
.Tip());
1661 while (pindex
&& !fAbortRescan
)
1663 if (pindex
->nHeight
% 100 == 0 && dProgressTip
- dProgressStart
> 0.0)
1664 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams
.TxData(), pindex
) - dProgressStart
) / (dProgressTip
- dProgressStart
) * 100))));
1665 if (GetTime() >= nNow
+ 60) {
1667 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex
->nHeight
, GuessVerificationProgress(chainParams
.TxData(), pindex
));
1671 if (ReadBlockFromDisk(block
, pindex
, Params().GetConsensus())) {
1672 for (size_t posInBlock
= 0; posInBlock
< block
.vtx
.size(); ++posInBlock
) {
1673 AddToWalletIfInvolvingMe(block
.vtx
[posInBlock
], pindex
, posInBlock
, fUpdate
);
1678 if (pindex
== pindexStop
) {
1681 pindex
= chainActive
.Next(pindex
);
1683 if (pindex
&& fAbortRescan
) {
1684 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex
->nHeight
, GuessVerificationProgress(chainParams
.TxData(), pindex
));
1686 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1688 fScanningWallet
= false;
1693 void CWallet::ReacceptWalletTransactions()
1695 // If transactions aren't being broadcasted, don't let them into local mempool either
1696 if (!fBroadcastTransactions
)
1698 LOCK2(cs_main
, cs_wallet
);
1699 std::map
<int64_t, CWalletTx
*> mapSorted
;
1701 // Sort pending wallet transactions based on their initial wallet insertion order
1702 for (std::pair
<const uint256
, CWalletTx
>& item
: mapWallet
)
1704 const uint256
& wtxid
= item
.first
;
1705 CWalletTx
& wtx
= item
.second
;
1706 assert(wtx
.GetHash() == wtxid
);
1708 int nDepth
= wtx
.GetDepthInMainChain();
1710 if (!wtx
.IsCoinBase() && (nDepth
== 0 && !wtx
.isAbandoned())) {
1711 mapSorted
.insert(std::make_pair(wtx
.nOrderPos
, &wtx
));
1715 // Try to add wallet transactions to memory pool
1716 for (std::pair
<const int64_t, CWalletTx
*>& item
: mapSorted
)
1718 CWalletTx
& wtx
= *(item
.second
);
1721 CValidationState state
;
1722 wtx
.AcceptToMemoryPool(maxTxFee
, state
);
1726 bool CWalletTx::RelayWalletTransaction(CConnman
* connman
)
1728 assert(pwallet
->GetBroadcastTransactions());
1729 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1731 CValidationState state
;
1732 /* GetDepthInMainChain already catches known conflicts. */
1733 if (InMempool() || AcceptToMemoryPool(maxTxFee
, state
)) {
1734 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1736 CInv
inv(MSG_TX
, GetHash());
1737 connman
->ForEachNode([&inv
](CNode
* pnode
)
1739 pnode
->PushInventory(inv
);
1748 std::set
<uint256
> CWalletTx::GetConflicts() const
1750 std::set
<uint256
> result
;
1751 if (pwallet
!= nullptr)
1753 uint256 myHash
= GetHash();
1754 result
= pwallet
->GetConflicts(myHash
);
1755 result
.erase(myHash
);
1760 CAmount
CWalletTx::GetDebit(const isminefilter
& filter
) const
1762 if (tx
->vin
.empty())
1766 if(filter
& ISMINE_SPENDABLE
)
1769 debit
+= nDebitCached
;
1772 nDebitCached
= pwallet
->GetDebit(*tx
, ISMINE_SPENDABLE
);
1773 fDebitCached
= true;
1774 debit
+= nDebitCached
;
1777 if(filter
& ISMINE_WATCH_ONLY
)
1779 if(fWatchDebitCached
)
1780 debit
+= nWatchDebitCached
;
1783 nWatchDebitCached
= pwallet
->GetDebit(*tx
, ISMINE_WATCH_ONLY
);
1784 fWatchDebitCached
= true;
1785 debit
+= nWatchDebitCached
;
1791 CAmount
CWalletTx::GetCredit(const isminefilter
& filter
) const
1793 // Must wait until coinbase is safely deep enough in the chain before valuing it
1794 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1798 if (filter
& ISMINE_SPENDABLE
)
1800 // GetBalance can assume transactions in mapWallet won't change
1802 credit
+= nCreditCached
;
1805 nCreditCached
= pwallet
->GetCredit(*tx
, ISMINE_SPENDABLE
);
1806 fCreditCached
= true;
1807 credit
+= nCreditCached
;
1810 if (filter
& ISMINE_WATCH_ONLY
)
1812 if (fWatchCreditCached
)
1813 credit
+= nWatchCreditCached
;
1816 nWatchCreditCached
= pwallet
->GetCredit(*tx
, ISMINE_WATCH_ONLY
);
1817 fWatchCreditCached
= true;
1818 credit
+= nWatchCreditCached
;
1824 CAmount
CWalletTx::GetImmatureCredit(bool fUseCache
) const
1826 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1828 if (fUseCache
&& fImmatureCreditCached
)
1829 return nImmatureCreditCached
;
1830 nImmatureCreditCached
= pwallet
->GetCredit(*tx
, ISMINE_SPENDABLE
);
1831 fImmatureCreditCached
= true;
1832 return nImmatureCreditCached
;
1838 CAmount
CWalletTx::GetAvailableCredit(bool fUseCache
) const
1840 if (pwallet
== nullptr)
1843 // Must wait until coinbase is safely deep enough in the chain before valuing it
1844 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1847 if (fUseCache
&& fAvailableCreditCached
)
1848 return nAvailableCreditCached
;
1850 CAmount nCredit
= 0;
1851 uint256 hashTx
= GetHash();
1852 for (unsigned int i
= 0; i
< tx
->vout
.size(); i
++)
1854 if (!pwallet
->IsSpent(hashTx
, i
))
1856 const CTxOut
&txout
= tx
->vout
[i
];
1857 nCredit
+= pwallet
->GetCredit(txout
, ISMINE_SPENDABLE
);
1858 if (!MoneyRange(nCredit
))
1859 throw std::runtime_error(std::string(__func__
) + " : value out of range");
1863 nAvailableCreditCached
= nCredit
;
1864 fAvailableCreditCached
= true;
1868 CAmount
CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache
) const
1870 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1872 if (fUseCache
&& fImmatureWatchCreditCached
)
1873 return nImmatureWatchCreditCached
;
1874 nImmatureWatchCreditCached
= pwallet
->GetCredit(*tx
, ISMINE_WATCH_ONLY
);
1875 fImmatureWatchCreditCached
= true;
1876 return nImmatureWatchCreditCached
;
1882 CAmount
CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache
) const
1884 if (pwallet
== nullptr)
1887 // Must wait until coinbase is safely deep enough in the chain before valuing it
1888 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1891 if (fUseCache
&& fAvailableWatchCreditCached
)
1892 return nAvailableWatchCreditCached
;
1894 CAmount nCredit
= 0;
1895 for (unsigned int i
= 0; i
< tx
->vout
.size(); i
++)
1897 if (!pwallet
->IsSpent(GetHash(), i
))
1899 const CTxOut
&txout
= tx
->vout
[i
];
1900 nCredit
+= pwallet
->GetCredit(txout
, ISMINE_WATCH_ONLY
);
1901 if (!MoneyRange(nCredit
))
1902 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1906 nAvailableWatchCreditCached
= nCredit
;
1907 fAvailableWatchCreditCached
= true;
1911 CAmount
CWalletTx::GetChange() const
1914 return nChangeCached
;
1915 nChangeCached
= pwallet
->GetChange(*tx
);
1916 fChangeCached
= true;
1917 return nChangeCached
;
1920 bool CWalletTx::InMempool() const
1925 bool CWalletTx::IsTrusted() const
1927 // Quick answer in most cases
1928 if (!CheckFinalTx(*tx
))
1930 int nDepth
= GetDepthInMainChain();
1935 if (!bSpendZeroConfChange
|| !IsFromMe(ISMINE_ALL
)) // using wtx's cached debit
1938 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1942 // Trusted if all inputs are from us and are in the mempool:
1943 for (const CTxIn
& txin
: tx
->vin
)
1945 // Transactions not sent by us: not trusted
1946 const CWalletTx
* parent
= pwallet
->GetWalletTx(txin
.prevout
.hash
);
1947 if (parent
== nullptr)
1949 const CTxOut
& parentOut
= parent
->tx
->vout
[txin
.prevout
.n
];
1950 if (pwallet
->IsMine(parentOut
) != ISMINE_SPENDABLE
)
1956 bool CWalletTx::IsEquivalentTo(const CWalletTx
& _tx
) const
1958 CMutableTransaction tx1
= *this->tx
;
1959 CMutableTransaction tx2
= *_tx
.tx
;
1960 for (auto& txin
: tx1
.vin
) txin
.scriptSig
= CScript();
1961 for (auto& txin
: tx2
.vin
) txin
.scriptSig
= CScript();
1962 return CTransaction(tx1
) == CTransaction(tx2
);
1965 std::vector
<uint256
> CWallet::ResendWalletTransactionsBefore(int64_t nTime
, CConnman
* connman
)
1967 std::vector
<uint256
> result
;
1971 // Sort them in chronological order
1972 std::multimap
<unsigned int, CWalletTx
*> mapSorted
;
1973 for (std::pair
<const uint256
, CWalletTx
>& item
: mapWallet
)
1975 CWalletTx
& wtx
= item
.second
;
1976 // Don't rebroadcast if newer than nTime:
1977 if (wtx
.nTimeReceived
> nTime
)
1979 mapSorted
.insert(std::make_pair(wtx
.nTimeReceived
, &wtx
));
1981 for (std::pair
<const unsigned int, CWalletTx
*>& item
: mapSorted
)
1983 CWalletTx
& wtx
= *item
.second
;
1984 if (wtx
.RelayWalletTransaction(connman
))
1985 result
.push_back(wtx
.GetHash());
1990 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime
, CConnman
* connman
)
1992 // Do this infrequently and randomly to avoid giving away
1993 // that these are our transactions.
1994 if (GetTime() < nNextResend
|| !fBroadcastTransactions
)
1996 bool fFirst
= (nNextResend
== 0);
1997 nNextResend
= GetTime() + GetRand(30 * 60);
2001 // Only do it if there's been a new block since last time
2002 if (nBestBlockTime
< nLastResend
)
2004 nLastResend
= GetTime();
2006 // Rebroadcast unconfirmed txes older than 5 minutes before the last
2008 std::vector
<uint256
> relayed
= ResendWalletTransactionsBefore(nBestBlockTime
-5*60, connman
);
2009 if (!relayed
.empty())
2010 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__
, relayed
.size());
2013 /** @} */ // end of mapWallet
2018 /** @defgroup Actions
2024 CAmount
CWallet::GetBalance() const
2028 LOCK2(cs_main
, cs_wallet
);
2029 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
2031 const CWalletTx
* pcoin
= &(*it
).second
;
2032 if (pcoin
->IsTrusted())
2033 nTotal
+= pcoin
->GetAvailableCredit();
2040 CAmount
CWallet::GetUnconfirmedBalance() const
2044 LOCK2(cs_main
, cs_wallet
);
2045 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
2047 const CWalletTx
* pcoin
= &(*it
).second
;
2048 if (!pcoin
->IsTrusted() && pcoin
->GetDepthInMainChain() == 0 && pcoin
->InMempool())
2049 nTotal
+= pcoin
->GetAvailableCredit();
2055 CAmount
CWallet::GetImmatureBalance() const
2059 LOCK2(cs_main
, cs_wallet
);
2060 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
2062 const CWalletTx
* pcoin
= &(*it
).second
;
2063 nTotal
+= pcoin
->GetImmatureCredit();
2069 CAmount
CWallet::GetWatchOnlyBalance() const
2073 LOCK2(cs_main
, cs_wallet
);
2074 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
2076 const CWalletTx
* pcoin
= &(*it
).second
;
2077 if (pcoin
->IsTrusted())
2078 nTotal
+= pcoin
->GetAvailableWatchOnlyCredit();
2085 CAmount
CWallet::GetUnconfirmedWatchOnlyBalance() const
2089 LOCK2(cs_main
, cs_wallet
);
2090 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
2092 const CWalletTx
* pcoin
= &(*it
).second
;
2093 if (!pcoin
->IsTrusted() && pcoin
->GetDepthInMainChain() == 0 && pcoin
->InMempool())
2094 nTotal
+= pcoin
->GetAvailableWatchOnlyCredit();
2100 CAmount
CWallet::GetImmatureWatchOnlyBalance() const
2104 LOCK2(cs_main
, cs_wallet
);
2105 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
2107 const CWalletTx
* pcoin
= &(*it
).second
;
2108 nTotal
+= pcoin
->GetImmatureWatchOnlyCredit();
2114 // Calculate total balance in a different way from GetBalance. The biggest
2115 // difference is that GetBalance sums up all unspent TxOuts paying to the
2116 // wallet, while this sums up both spent and unspent TxOuts paying to the
2117 // wallet, and then subtracts the values of TxIns spending from the wallet. This
2118 // also has fewer restrictions on which unconfirmed transactions are considered
2120 CAmount
CWallet::GetLegacyBalance(const isminefilter
& filter
, int minDepth
, const std::string
* account
) const
2122 LOCK2(cs_main
, cs_wallet
);
2124 CAmount balance
= 0;
2125 for (const auto& entry
: mapWallet
) {
2126 const CWalletTx
& wtx
= entry
.second
;
2127 const int depth
= wtx
.GetDepthInMainChain();
2128 if (depth
< 0 || !CheckFinalTx(*wtx
.tx
) || wtx
.GetBlocksToMaturity() > 0) {
2132 // Loop through tx outputs and add incoming payments. For outgoing txs,
2133 // treat change outputs specially, as part of the amount debited.
2134 CAmount debit
= wtx
.GetDebit(filter
);
2135 const bool outgoing
= debit
> 0;
2136 for (const CTxOut
& out
: wtx
.tx
->vout
) {
2137 if (outgoing
&& IsChange(out
)) {
2138 debit
-= out
.nValue
;
2139 } else if (IsMine(out
) & filter
&& depth
>= minDepth
&& (!account
|| *account
== GetAccountName(out
.scriptPubKey
))) {
2140 balance
+= out
.nValue
;
2144 // For outgoing txs, subtract amount debited.
2145 if (outgoing
&& (!account
|| *account
== wtx
.strFromAccount
)) {
2151 balance
+= CWalletDB(*dbw
).GetAccountCreditDebit(*account
);
2157 CAmount
CWallet::GetAvailableBalance(const CCoinControl
* coinControl
) const
2159 LOCK2(cs_main
, cs_wallet
);
2161 CAmount balance
= 0;
2162 std::vector
<COutput
> vCoins
;
2163 AvailableCoins(vCoins
, true, coinControl
);
2164 for (const COutput
& out
: vCoins
) {
2165 if (out
.fSpendable
) {
2166 balance
+= out
.tx
->tx
->vout
[out
.i
].nValue
;
2172 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
2177 LOCK2(cs_main
, cs_wallet
);
2181 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
2183 const uint256
& wtxid
= it
->first
;
2184 const CWalletTx
* pcoin
= &(*it
).second
;
2186 if (!CheckFinalTx(*pcoin
->tx
))
2189 if (pcoin
->IsCoinBase() && pcoin
->GetBlocksToMaturity() > 0)
2192 int nDepth
= pcoin
->GetDepthInMainChain();
2196 // We should not consider coins which aren't at least in our mempool
2197 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2198 if (nDepth
== 0 && !pcoin
->InMempool())
2201 bool safeTx
= pcoin
->IsTrusted();
2203 // We should not consider coins from transactions that are replacing
2204 // other transactions.
2206 // Example: There is a transaction A which is replaced by bumpfee
2207 // transaction B. In this case, we want to prevent creation of
2208 // a transaction B' which spends an output of B.
2210 // Reason: If transaction A were initially confirmed, transactions B
2211 // and B' would no longer be valid, so the user would have to create
2212 // a new transaction C to replace B'. However, in the case of a
2213 // one-block reorg, transactions B' and C might BOTH be accepted,
2214 // when the user only wanted one of them. Specifically, there could
2215 // be a 1-block reorg away from the chain where transactions A and C
2216 // were accepted to another chain where B, B', and C were all
2218 if (nDepth
== 0 && pcoin
->mapValue
.count("replaces_txid")) {
2222 // Similarly, we should not consider coins from transactions that
2223 // have been replaced. In the example above, we would want to prevent
2224 // creation of a transaction A' spending an output of A, because if
2225 // transaction B were initially confirmed, conflicting with A and
2226 // A', we wouldn't want to the user to create a transaction D
2227 // intending to replace A', but potentially resulting in a scenario
2228 // where A, A', and D could all be accepted (instead of just B and
2229 // D, or just A and A' like the user would want).
2230 if (nDepth
== 0 && pcoin
->mapValue
.count("replaced_by_txid")) {
2234 if (fOnlySafe
&& !safeTx
) {
2238 if (nDepth
< nMinDepth
|| nDepth
> nMaxDepth
)
2241 for (unsigned int i
= 0; i
< pcoin
->tx
->vout
.size(); i
++) {
2242 if (pcoin
->tx
->vout
[i
].nValue
< nMinimumAmount
|| pcoin
->tx
->vout
[i
].nValue
> nMaximumAmount
)
2245 if (coinControl
&& coinControl
->HasSelected() && !coinControl
->fAllowOtherInputs
&& !coinControl
->IsSelected(COutPoint((*it
).first
, i
)))
2248 if (IsLockedCoin((*it
).first
, i
))
2251 if (IsSpent(wtxid
, i
))
2254 isminetype mine
= IsMine(pcoin
->tx
->vout
[i
]);
2256 if (mine
== ISMINE_NO
) {
2260 bool fSpendableIn
= ((mine
& ISMINE_SPENDABLE
) != ISMINE_NO
) || (coinControl
&& coinControl
->fAllowWatchOnly
&& (mine
& ISMINE_WATCH_SOLVABLE
) != ISMINE_NO
);
2261 bool fSolvableIn
= (mine
& (ISMINE_SPENDABLE
| ISMINE_WATCH_SOLVABLE
)) != ISMINE_NO
;
2263 vCoins
.push_back(COutput(pcoin
, i
, nDepth
, fSpendableIn
, fSolvableIn
, safeTx
));
2265 // Checks the sum amount of all UTXO's.
2266 if (nMinimumSumAmount
!= MAX_MONEY
) {
2267 nTotal
+= pcoin
->tx
->vout
[i
].nValue
;
2269 if (nTotal
>= nMinimumSumAmount
) {
2274 // Checks the maximum number of UTXO's.
2275 if (nMaximumCount
> 0 && vCoins
.size() >= nMaximumCount
) {
2283 std::map
<CTxDestination
, std::vector
<COutput
>> CWallet::ListCoins() const
2285 // TODO: Add AssertLockHeld(cs_wallet) here.
2287 // Because the return value from this function contains pointers to
2288 // CWalletTx objects, callers to this function really should acquire the
2289 // cs_wallet lock before calling it. However, the current caller doesn't
2290 // acquire this lock yet. There was an attempt to add the missing lock in
2291 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2292 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2293 // avoid adding some extra complexity to the Qt code.
2295 std::map
<CTxDestination
, std::vector
<COutput
>> result
;
2297 std::vector
<COutput
> availableCoins
;
2298 AvailableCoins(availableCoins
);
2300 LOCK2(cs_main
, cs_wallet
);
2301 for (auto& coin
: availableCoins
) {
2302 CTxDestination address
;
2303 if (coin
.fSpendable
&&
2304 ExtractDestination(FindNonChangeParentOutput(*coin
.tx
->tx
, coin
.i
).scriptPubKey
, address
)) {
2305 result
[address
].emplace_back(std::move(coin
));
2309 std::vector
<COutPoint
> lockedCoins
;
2310 ListLockedCoins(lockedCoins
);
2311 for (const auto& output
: lockedCoins
) {
2312 auto it
= mapWallet
.find(output
.hash
);
2313 if (it
!= mapWallet
.end()) {
2314 int depth
= it
->second
.GetDepthInMainChain();
2315 if (depth
>= 0 && output
.n
< it
->second
.tx
->vout
.size() &&
2316 IsMine(it
->second
.tx
->vout
[output
.n
]) == ISMINE_SPENDABLE
) {
2317 CTxDestination address
;
2318 if (ExtractDestination(FindNonChangeParentOutput(*it
->second
.tx
, output
.n
).scriptPubKey
, address
)) {
2319 result
[address
].emplace_back(
2320 &it
->second
, output
.n
, depth
, true /* spendable */, true /* solvable */, false /* safe */);
2329 const CTxOut
& CWallet::FindNonChangeParentOutput(const CTransaction
& tx
, int output
) const
2331 const CTransaction
* ptx
= &tx
;
2333 while (IsChange(ptx
->vout
[n
]) && ptx
->vin
.size() > 0) {
2334 const COutPoint
& prevout
= ptx
->vin
[0].prevout
;
2335 auto it
= mapWallet
.find(prevout
.hash
);
2336 if (it
== mapWallet
.end() || it
->second
.tx
->vout
.size() <= prevout
.n
||
2337 !IsMine(it
->second
.tx
->vout
[prevout
.n
])) {
2340 ptx
= it
->second
.tx
.get();
2343 return ptx
->vout
[n
];
2346 static void ApproximateBestSubset(const std::vector
<CInputCoin
>& vValue
, const CAmount
& nTotalLower
, const CAmount
& nTargetValue
,
2347 std::vector
<char>& vfBest
, CAmount
& nBest
, int iterations
= 1000)
2349 std::vector
<char> vfIncluded
;
2351 vfBest
.assign(vValue
.size(), true);
2352 nBest
= nTotalLower
;
2354 FastRandomContext insecure_rand
;
2356 for (int nRep
= 0; nRep
< iterations
&& nBest
!= nTargetValue
; nRep
++)
2358 vfIncluded
.assign(vValue
.size(), false);
2360 bool fReachedTarget
= false;
2361 for (int nPass
= 0; nPass
< 2 && !fReachedTarget
; nPass
++)
2363 for (unsigned int i
= 0; i
< vValue
.size(); i
++)
2365 //The solver here uses a randomized algorithm,
2366 //the randomness serves no real security purpose but is just
2367 //needed to prevent degenerate behavior and it is important
2368 //that the rng is fast. We do not use a constant random sequence,
2369 //because there may be some privacy improvement by making
2370 //the selection random.
2371 if (nPass
== 0 ? insecure_rand
.randbool() : !vfIncluded
[i
])
2373 nTotal
+= vValue
[i
].txout
.nValue
;
2374 vfIncluded
[i
] = true;
2375 if (nTotal
>= nTargetValue
)
2377 fReachedTarget
= true;
2381 vfBest
= vfIncluded
;
2383 nTotal
-= vValue
[i
].txout
.nValue
;
2384 vfIncluded
[i
] = false;
2392 bool CWallet::SelectCoinsMinConf(const CAmount
& nTargetValue
, const int nConfMine
, const int nConfTheirs
, const uint64_t nMaxAncestors
, std::vector
<COutput
> vCoins
,
2393 std::set
<CInputCoin
>& setCoinsRet
, CAmount
& nValueRet
) const
2395 setCoinsRet
.clear();
2398 // List of values less than target
2399 boost::optional
<CInputCoin
> coinLowestLarger
;
2400 std::vector
<CInputCoin
> vValue
;
2401 CAmount nTotalLower
= 0;
2403 random_shuffle(vCoins
.begin(), vCoins
.end(), GetRandInt
);
2405 for (const COutput
&output
: vCoins
)
2407 if (!output
.fSpendable
)
2410 const CWalletTx
*pcoin
= output
.tx
;
2412 if (output
.nDepth
< (pcoin
->IsFromMe(ISMINE_ALL
) ? nConfMine
: nConfTheirs
))
2415 if (!mempool
.TransactionWithinChainLimit(pcoin
->GetHash(), nMaxAncestors
))
2420 CInputCoin coin
= CInputCoin(pcoin
, i
);
2422 if (coin
.txout
.nValue
== nTargetValue
)
2424 setCoinsRet
.insert(coin
);
2425 nValueRet
+= coin
.txout
.nValue
;
2428 else if (coin
.txout
.nValue
< nTargetValue
+ MIN_CHANGE
)
2430 vValue
.push_back(coin
);
2431 nTotalLower
+= coin
.txout
.nValue
;
2433 else if (!coinLowestLarger
|| coin
.txout
.nValue
< coinLowestLarger
->txout
.nValue
)
2435 coinLowestLarger
= coin
;
2439 if (nTotalLower
== nTargetValue
)
2441 for (const auto& input
: vValue
)
2443 setCoinsRet
.insert(input
);
2444 nValueRet
+= input
.txout
.nValue
;
2449 if (nTotalLower
< nTargetValue
)
2451 if (!coinLowestLarger
)
2453 setCoinsRet
.insert(coinLowestLarger
.get());
2454 nValueRet
+= coinLowestLarger
->txout
.nValue
;
2458 // Solve subset sum by stochastic approximation
2459 std::sort(vValue
.begin(), vValue
.end(), CompareValueOnly());
2460 std::reverse(vValue
.begin(), vValue
.end());
2461 std::vector
<char> vfBest
;
2464 ApproximateBestSubset(vValue
, nTotalLower
, nTargetValue
, vfBest
, nBest
);
2465 if (nBest
!= nTargetValue
&& nTotalLower
>= nTargetValue
+ MIN_CHANGE
)
2466 ApproximateBestSubset(vValue
, nTotalLower
, nTargetValue
+ MIN_CHANGE
, vfBest
, nBest
);
2468 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2469 // or the next bigger coin is closer), return the bigger coin
2470 if (coinLowestLarger
&&
2471 ((nBest
!= nTargetValue
&& nBest
< nTargetValue
+ MIN_CHANGE
) || coinLowestLarger
->txout
.nValue
<= nBest
))
2473 setCoinsRet
.insert(coinLowestLarger
.get());
2474 nValueRet
+= coinLowestLarger
->txout
.nValue
;
2477 for (unsigned int i
= 0; i
< vValue
.size(); i
++)
2480 setCoinsRet
.insert(vValue
[i
]);
2481 nValueRet
+= vValue
[i
].txout
.nValue
;
2484 if (LogAcceptCategory(BCLog::SELECTCOINS
)) {
2485 LogPrint(BCLog::SELECTCOINS
, "SelectCoins() best subset: ");
2486 for (unsigned int i
= 0; i
< vValue
.size(); i
++) {
2488 LogPrint(BCLog::SELECTCOINS
, "%s ", FormatMoney(vValue
[i
].txout
.nValue
));
2491 LogPrint(BCLog::SELECTCOINS
, "total %s\n", FormatMoney(nBest
));
2498 bool CWallet::SelectCoins(const std::vector
<COutput
>& vAvailableCoins
, const CAmount
& nTargetValue
, std::set
<CInputCoin
>& setCoinsRet
, CAmount
& nValueRet
, const CCoinControl
* coinControl
) const
2500 std::vector
<COutput
> vCoins(vAvailableCoins
);
2502 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2503 if (coinControl
&& coinControl
->HasSelected() && !coinControl
->fAllowOtherInputs
)
2505 for (const COutput
& out
: vCoins
)
2507 if (!out
.fSpendable
)
2509 nValueRet
+= out
.tx
->tx
->vout
[out
.i
].nValue
;
2510 setCoinsRet
.insert(CInputCoin(out
.tx
, out
.i
));
2512 return (nValueRet
>= nTargetValue
);
2515 // calculate value from preset inputs and store them
2516 std::set
<CInputCoin
> setPresetCoins
;
2517 CAmount nValueFromPresetInputs
= 0;
2519 std::vector
<COutPoint
> vPresetInputs
;
2521 coinControl
->ListSelected(vPresetInputs
);
2522 for (const COutPoint
& outpoint
: vPresetInputs
)
2524 std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.find(outpoint
.hash
);
2525 if (it
!= mapWallet
.end())
2527 const CWalletTx
* pcoin
= &it
->second
;
2528 // Clearly invalid input, fail
2529 if (pcoin
->tx
->vout
.size() <= outpoint
.n
)
2531 nValueFromPresetInputs
+= pcoin
->tx
->vout
[outpoint
.n
].nValue
;
2532 setPresetCoins
.insert(CInputCoin(pcoin
, outpoint
.n
));
2534 return false; // TODO: Allow non-wallet inputs
2537 // remove preset inputs from vCoins
2538 for (std::vector
<COutput
>::iterator it
= vCoins
.begin(); it
!= vCoins
.end() && coinControl
&& coinControl
->HasSelected();)
2540 if (setPresetCoins
.count(CInputCoin(it
->tx
, it
->i
)))
2541 it
= vCoins
.erase(it
);
2546 size_t nMaxChainLength
= std::min(gArgs
.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT
), gArgs
.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT
));
2547 bool fRejectLongChains
= gArgs
.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS
);
2549 bool res
= nTargetValue
<= nValueFromPresetInputs
||
2550 SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 1, 6, 0, vCoins
, setCoinsRet
, nValueRet
) ||
2551 SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 1, 1, 0, vCoins
, setCoinsRet
, nValueRet
) ||
2552 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, 2, vCoins
, setCoinsRet
, nValueRet
)) ||
2553 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, std::min((size_t)4, nMaxChainLength
/3), vCoins
, setCoinsRet
, nValueRet
)) ||
2554 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, nMaxChainLength
/2, vCoins
, setCoinsRet
, nValueRet
)) ||
2555 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, nMaxChainLength
, vCoins
, setCoinsRet
, nValueRet
)) ||
2556 (bSpendZeroConfChange
&& !fRejectLongChains
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, std::numeric_limits
<uint64_t>::max(), vCoins
, setCoinsRet
, nValueRet
));
2558 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2559 setCoinsRet
.insert(setPresetCoins
.begin(), setPresetCoins
.end());
2561 // add preset inputs to the total value selected
2562 nValueRet
+= nValueFromPresetInputs
;
2567 bool CWallet::SignTransaction(CMutableTransaction
&tx
)
2569 AssertLockHeld(cs_wallet
); // mapWallet
2572 CTransaction
txNewConst(tx
);
2574 for (const auto& input
: tx
.vin
) {
2575 std::map
<uint256
, CWalletTx
>::const_iterator mi
= mapWallet
.find(input
.prevout
.hash
);
2576 if(mi
== mapWallet
.end() || input
.prevout
.n
>= mi
->second
.tx
->vout
.size()) {
2579 const CScript
& scriptPubKey
= mi
->second
.tx
->vout
[input
.prevout
.n
].scriptPubKey
;
2580 const CAmount
& amount
= mi
->second
.tx
->vout
[input
.prevout
.n
].nValue
;
2581 SignatureData sigdata
;
2582 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst
, nIn
, amount
, SIGHASH_ALL
), scriptPubKey
, sigdata
)) {
2585 UpdateTransaction(tx
, nIn
, sigdata
);
2591 bool CWallet::FundTransaction(CMutableTransaction
& tx
, CAmount
& nFeeRet
, int& nChangePosInOut
, std::string
& strFailReason
, bool lockUnspents
, const std::set
<int>& setSubtractFeeFromOutputs
, CCoinControl coinControl
)
2593 std::vector
<CRecipient
> vecSend
;
2595 // Turn the txout set into a CRecipient vector
2596 for (size_t idx
= 0; idx
< tx
.vout
.size(); idx
++)
2598 const CTxOut
& txOut
= tx
.vout
[idx
];
2599 CRecipient recipient
= {txOut
.scriptPubKey
, txOut
.nValue
, setSubtractFeeFromOutputs
.count(idx
) == 1};
2600 vecSend
.push_back(recipient
);
2603 coinControl
.fAllowOtherInputs
= true;
2605 for (const CTxIn
& txin
: tx
.vin
)
2606 coinControl
.Select(txin
.prevout
);
2608 CReserveKey
reservekey(this);
2610 if (!CreateTransaction(vecSend
, wtx
, reservekey
, nFeeRet
, nChangePosInOut
, strFailReason
, coinControl
, false)) {
2614 if (nChangePosInOut
!= -1) {
2615 tx
.vout
.insert(tx
.vout
.begin() + nChangePosInOut
, wtx
.tx
->vout
[nChangePosInOut
]);
2616 // we don't have the normal Create/Commit cycle, and don't want to risk reusing change,
2617 // so just remove the key from the keypool here.
2618 reservekey
.KeepKey();
2621 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2622 for (unsigned int idx
= 0; idx
< tx
.vout
.size(); idx
++)
2623 tx
.vout
[idx
].nValue
= wtx
.tx
->vout
[idx
].nValue
;
2625 // Add new txins (keeping original txin scriptSig/order)
2626 for (const CTxIn
& txin
: wtx
.tx
->vin
)
2628 if (!coinControl
.IsSelected(txin
.prevout
))
2630 tx
.vin
.push_back(txin
);
2634 LOCK2(cs_main
, cs_wallet
);
2635 LockCoin(txin
.prevout
);
2644 bool CWallet::CreateTransaction(const std::vector
<CRecipient
>& vecSend
, CWalletTx
& wtxNew
, CReserveKey
& reservekey
, CAmount
& nFeeRet
,
2645 int& nChangePosInOut
, std::string
& strFailReason
, const CCoinControl
& coin_control
, bool sign
)
2648 int nChangePosRequest
= nChangePosInOut
;
2649 unsigned int nSubtractFeeFromAmount
= 0;
2650 for (const auto& recipient
: vecSend
)
2652 if (nValue
< 0 || recipient
.nAmount
< 0)
2654 strFailReason
= _("Transaction amounts must not be negative");
2657 nValue
+= recipient
.nAmount
;
2659 if (recipient
.fSubtractFeeFromAmount
)
2660 nSubtractFeeFromAmount
++;
2662 if (vecSend
.empty())
2664 strFailReason
= _("Transaction must have at least one recipient");
2668 wtxNew
.fTimeReceivedIsTxTime
= true;
2669 wtxNew
.BindWallet(this);
2670 CMutableTransaction txNew
;
2672 // Discourage fee sniping.
2674 // For a large miner the value of the transactions in the best block and
2675 // the mempool can exceed the cost of deliberately attempting to mine two
2676 // blocks to orphan the current best block. By setting nLockTime such that
2677 // only the next block can include the transaction, we discourage this
2678 // practice as the height restricted and limited blocksize gives miners
2679 // considering fee sniping fewer options for pulling off this attack.
2681 // A simple way to think about this is from the wallet's point of view we
2682 // always want the blockchain to move forward. By setting nLockTime this
2683 // way we're basically making the statement that we only want this
2684 // transaction to appear in the next block; we don't want to potentially
2685 // encourage reorgs by allowing transactions to appear at lower heights
2686 // than the next block in forks of the best chain.
2688 // Of course, the subsidy is high enough, and transaction volume low
2689 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2690 // now we ensure code won't be written that makes assumptions about
2691 // nLockTime that preclude a fix later.
2692 txNew
.nLockTime
= chainActive
.Height();
2694 // Secondly occasionally randomly pick a nLockTime even further back, so
2695 // that transactions that are delayed after signing for whatever reason,
2696 // e.g. high-latency mix networks and some CoinJoin implementations, have
2698 if (GetRandInt(10) == 0)
2699 txNew
.nLockTime
= std::max(0, (int)txNew
.nLockTime
- GetRandInt(100));
2701 assert(txNew
.nLockTime
<= (unsigned int)chainActive
.Height());
2702 assert(txNew
.nLockTime
< LOCKTIME_THRESHOLD
);
2703 FeeCalculation feeCalc
;
2705 unsigned int nBytes
;
2707 std::set
<CInputCoin
> setCoins
;
2708 LOCK2(cs_main
, cs_wallet
);
2710 std::vector
<COutput
> vAvailableCoins
;
2711 AvailableCoins(vAvailableCoins
, true, &coin_control
);
2713 // Create change script that will be used if we need change
2714 // TODO: pass in scriptChange instead of reservekey so
2715 // change transaction isn't always pay-to-bitcoin-address
2716 CScript scriptChange
;
2718 // coin control: send change to custom address
2719 if (!boost::get
<CNoDestination
>(&coin_control
.destChange
)) {
2720 scriptChange
= GetScriptForDestination(coin_control
.destChange
);
2721 } else { // no coin control: send change to newly generated address
2722 // Note: We use a new key here to keep it from being obvious which side is the change.
2723 // The drawback is that by not reusing a previous key, the change may be lost if a
2724 // backup is restored, if the backup doesn't have the new private key for the change.
2725 // If we reused the old key, it would be possible to add code to look for and
2726 // rediscover unknown transactions that were written with keys of ours to recover
2727 // post-backup change.
2729 // Reserve a new key pair from key pool
2732 ret
= reservekey
.GetReservedKey(vchPubKey
, true);
2735 strFailReason
= _("Keypool ran out, please call keypoolrefill first");
2739 scriptChange
= GetScriptForDestination(vchPubKey
.GetID());
2741 CTxOut
change_prototype_txout(0, scriptChange
);
2742 size_t change_prototype_size
= GetSerializeSize(change_prototype_txout
, SER_DISK
, 0);
2744 CFeeRate discard_rate
= GetDiscardRate(::feeEstimator
);
2746 bool pick_new_inputs
= true;
2747 CAmount nValueIn
= 0;
2748 // Start with no fee and loop until there is enough fee
2751 nChangePosInOut
= nChangePosRequest
;
2754 wtxNew
.fFromMe
= true;
2757 CAmount nValueToSelect
= nValue
;
2758 if (nSubtractFeeFromAmount
== 0)
2759 nValueToSelect
+= nFeeRet
;
2760 // vouts to the payees
2761 for (const auto& recipient
: vecSend
)
2763 CTxOut
txout(recipient
.nAmount
, recipient
.scriptPubKey
);
2765 if (recipient
.fSubtractFeeFromAmount
)
2767 assert(nSubtractFeeFromAmount
!= 0);
2768 txout
.nValue
-= nFeeRet
/ nSubtractFeeFromAmount
; // Subtract fee equally from each selected recipient
2770 if (fFirst
) // first receiver pays the remainder not divisible by output count
2773 txout
.nValue
-= nFeeRet
% nSubtractFeeFromAmount
;
2777 if (IsDust(txout
, ::dustRelayFee
))
2779 if (recipient
.fSubtractFeeFromAmount
&& nFeeRet
> 0)
2781 if (txout
.nValue
< 0)
2782 strFailReason
= _("The transaction amount is too small to pay the fee");
2784 strFailReason
= _("The transaction amount is too small to send after the fee has been deducted");
2787 strFailReason
= _("Transaction amount too small");
2790 txNew
.vout
.push_back(txout
);
2793 // Choose coins to use
2794 if (pick_new_inputs
) {
2797 if (!SelectCoins(vAvailableCoins
, nValueToSelect
, setCoins
, nValueIn
, &coin_control
))
2799 strFailReason
= _("Insufficient funds");
2804 const CAmount nChange
= nValueIn
- nValueToSelect
;
2808 // Fill a vout to ourself
2809 CTxOut
newTxOut(nChange
, scriptChange
);
2811 // Never create dust outputs; if we would, just
2812 // add the dust to the fee.
2813 if (IsDust(newTxOut
, discard_rate
))
2815 nChangePosInOut
= -1;
2820 if (nChangePosInOut
== -1)
2822 // Insert change txn at random position:
2823 nChangePosInOut
= GetRandInt(txNew
.vout
.size()+1);
2825 else if ((unsigned int)nChangePosInOut
> txNew
.vout
.size())
2827 strFailReason
= _("Change index out of range");
2831 std::vector
<CTxOut
>::iterator position
= txNew
.vout
.begin()+nChangePosInOut
;
2832 txNew
.vout
.insert(position
, newTxOut
);
2835 nChangePosInOut
= -1;
2840 // Note how the sequence number is set to non-maxint so that
2841 // the nLockTime set above actually works.
2843 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2844 // we use the highest possible value in that range (maxint-2)
2845 // to avoid conflicting with other possible uses of nSequence,
2846 // and in the spirit of "smallest possible change from prior
2848 const uint32_t nSequence
= coin_control
.signalRbf
? MAX_BIP125_RBF_SEQUENCE
: (CTxIn::SEQUENCE_FINAL
- 1);
2849 for (const auto& coin
: setCoins
)
2850 txNew
.vin
.push_back(CTxIn(coin
.outpoint
,CScript(),
2853 // Fill in dummy signatures for fee calculation.
2854 if (!DummySignTx(txNew
, setCoins
)) {
2855 strFailReason
= _("Signing transaction failed");
2859 nBytes
= GetVirtualTransactionSize(txNew
);
2861 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2862 for (auto& vin
: txNew
.vin
) {
2863 vin
.scriptSig
= CScript();
2864 vin
.scriptWitness
.SetNull();
2867 nFeeNeeded
= GetMinimumFee(nBytes
, coin_control
, ::mempool
, ::feeEstimator
, &feeCalc
);
2869 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2870 // because we must be at the maximum allowed fee.
2871 if (nFeeNeeded
< ::minRelayTxFee
.GetFee(nBytes
))
2873 strFailReason
= _("Transaction too large for fee policy");
2877 if (nFeeRet
>= nFeeNeeded
) {
2878 // Reduce fee to only the needed amount if possible. This
2879 // prevents potential overpayment in fees if the coins
2880 // selected to meet nFeeNeeded result in a transaction that
2881 // requires less fee than the prior iteration.
2883 // If we have no change and a big enough excess fee, then
2884 // try to construct transaction again only without picking
2885 // new inputs. We now know we only need the smaller fee
2886 // (because of reduced tx size) and so we should add a
2887 // change output. Only try this once.
2888 if (nChangePosInOut
== -1 && nSubtractFeeFromAmount
== 0 && pick_new_inputs
) {
2889 unsigned int tx_size_with_change
= nBytes
+ change_prototype_size
+ 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
2890 CAmount fee_needed_with_change
= GetMinimumFee(tx_size_with_change
, coin_control
, ::mempool
, ::feeEstimator
, nullptr);
2891 CAmount minimum_value_for_change
= GetDustThreshold(change_prototype_txout
, discard_rate
);
2892 if (nFeeRet
>= fee_needed_with_change
+ minimum_value_for_change
) {
2893 pick_new_inputs
= false;
2894 nFeeRet
= fee_needed_with_change
;
2899 // If we have change output already, just increase it
2900 if (nFeeRet
> nFeeNeeded
&& nChangePosInOut
!= -1 && nSubtractFeeFromAmount
== 0) {
2901 CAmount extraFeePaid
= nFeeRet
- nFeeNeeded
;
2902 std::vector
<CTxOut
>::iterator change_position
= txNew
.vout
.begin()+nChangePosInOut
;
2903 change_position
->nValue
+= extraFeePaid
;
2904 nFeeRet
-= extraFeePaid
;
2906 break; // Done, enough fee included.
2908 else if (!pick_new_inputs
) {
2909 // This shouldn't happen, we should have had enough excess
2910 // fee to pay for the new output and still meet nFeeNeeded
2911 // Or we should have just subtracted fee from recipients and
2912 // nFeeNeeded should not have changed
2913 strFailReason
= _("Transaction fee and change calculation failed");
2917 // Try to reduce change to include necessary fee
2918 if (nChangePosInOut
!= -1 && nSubtractFeeFromAmount
== 0) {
2919 CAmount additionalFeeNeeded
= nFeeNeeded
- nFeeRet
;
2920 std::vector
<CTxOut
>::iterator change_position
= txNew
.vout
.begin()+nChangePosInOut
;
2921 // Only reduce change if remaining amount is still a large enough output.
2922 if (change_position
->nValue
>= MIN_FINAL_CHANGE
+ additionalFeeNeeded
) {
2923 change_position
->nValue
-= additionalFeeNeeded
;
2924 nFeeRet
+= additionalFeeNeeded
;
2925 break; // Done, able to increase fee from change
2929 // If subtracting fee from recipients, we now know what fee we
2930 // need to subtract, we have no reason to reselect inputs
2931 if (nSubtractFeeFromAmount
> 0) {
2932 pick_new_inputs
= false;
2935 // Include more fee and try again.
2936 nFeeRet
= nFeeNeeded
;
2941 if (nChangePosInOut
== -1) reservekey
.ReturnKey(); // Return any reserved key if we don't have change
2945 CTransaction
txNewConst(txNew
);
2947 for (const auto& coin
: setCoins
)
2949 const CScript
& scriptPubKey
= coin
.txout
.scriptPubKey
;
2950 SignatureData sigdata
;
2952 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst
, nIn
, coin
.txout
.nValue
, SIGHASH_ALL
), scriptPubKey
, sigdata
))
2954 strFailReason
= _("Signing transaction failed");
2957 UpdateTransaction(txNew
, nIn
, sigdata
);
2964 // Embed the constructed transaction data in wtxNew.
2965 wtxNew
.SetTx(MakeTransactionRef(std::move(txNew
)));
2968 if (GetTransactionWeight(*wtxNew
.tx
) >= MAX_STANDARD_TX_WEIGHT
)
2970 strFailReason
= _("Transaction too large");
2975 if (gArgs
.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS
)) {
2976 // Lastly, ensure this tx will pass the mempool's chain limits
2978 CTxMemPoolEntry
entry(wtxNew
.tx
, 0, 0, 0, false, 0, lp
);
2979 CTxMemPool::setEntries setAncestors
;
2980 size_t nLimitAncestors
= gArgs
.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT
);
2981 size_t nLimitAncestorSize
= gArgs
.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT
)*1000;
2982 size_t nLimitDescendants
= gArgs
.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT
);
2983 size_t nLimitDescendantSize
= gArgs
.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT
)*1000;
2984 std::string errString
;
2985 if (!mempool
.CalculateMemPoolAncestors(entry
, setAncestors
, nLimitAncestors
, nLimitAncestorSize
, nLimitDescendants
, nLimitDescendantSize
, errString
)) {
2986 strFailReason
= _("Transaction has too long of a mempool chain");
2991 LogPrintf("Fee Calculation: Fee:%d Bytes:%u Needed:%d Tgt:%d (requested %d) Reason:\"%s\" Decay %.5f: Estimation: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out) Fail: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out)\n",
2992 nFeeRet
, nBytes
, nFeeNeeded
, feeCalc
.returnedTarget
, feeCalc
.desiredTarget
, StringForFeeReason(feeCalc
.reason
), feeCalc
.est
.decay
,
2993 feeCalc
.est
.pass
.start
, feeCalc
.est
.pass
.end
,
2994 100 * feeCalc
.est
.pass
.withinTarget
/ (feeCalc
.est
.pass
.totalConfirmed
+ feeCalc
.est
.pass
.inMempool
+ feeCalc
.est
.pass
.leftMempool
),
2995 feeCalc
.est
.pass
.withinTarget
, feeCalc
.est
.pass
.totalConfirmed
, feeCalc
.est
.pass
.inMempool
, feeCalc
.est
.pass
.leftMempool
,
2996 feeCalc
.est
.fail
.start
, feeCalc
.est
.fail
.end
,
2997 100 * feeCalc
.est
.fail
.withinTarget
/ (feeCalc
.est
.fail
.totalConfirmed
+ feeCalc
.est
.fail
.inMempool
+ feeCalc
.est
.fail
.leftMempool
),
2998 feeCalc
.est
.fail
.withinTarget
, feeCalc
.est
.fail
.totalConfirmed
, feeCalc
.est
.fail
.inMempool
, feeCalc
.est
.fail
.leftMempool
);
3003 * Call after CreateTransaction unless you want to abort
3005 bool CWallet::CommitTransaction(CWalletTx
& wtxNew
, CReserveKey
& reservekey
, CConnman
* connman
, CValidationState
& state
)
3008 LOCK2(cs_main
, cs_wallet
);
3009 LogPrintf("CommitTransaction:\n%s", wtxNew
.tx
->ToString());
3011 // Take key pair from key pool so it won't be used again
3012 reservekey
.KeepKey();
3014 // Add tx to wallet, because if it has change it's also ours,
3015 // otherwise just for transaction history.
3016 AddToWallet(wtxNew
);
3018 // Notify that old coins are spent
3019 for (const CTxIn
& txin
: wtxNew
.tx
->vin
)
3021 CWalletTx
&coin
= mapWallet
[txin
.prevout
.hash
];
3022 coin
.BindWallet(this);
3023 NotifyTransactionChanged(this, coin
.GetHash(), CT_UPDATED
);
3027 // Track how many getdata requests our transaction gets
3028 mapRequestCount
[wtxNew
.GetHash()] = 0;
3030 // Get the inserted-CWalletTx from mapWallet so that the
3031 // fInMempool flag is cached properly
3032 CWalletTx
& wtx
= mapWallet
[wtxNew
.GetHash()];
3034 if (fBroadcastTransactions
)
3037 if (!wtx
.AcceptToMemoryPool(maxTxFee
, state
)) {
3038 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state
.GetRejectReason());
3039 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
3041 wtx
.RelayWalletTransaction(connman
);
3048 void CWallet::ListAccountCreditDebit(const std::string
& strAccount
, std::list
<CAccountingEntry
>& entries
) {
3049 CWalletDB
walletdb(*dbw
);
3050 return walletdb
.ListAccountCreditDebit(strAccount
, entries
);
3053 bool CWallet::AddAccountingEntry(const CAccountingEntry
& acentry
)
3055 CWalletDB
walletdb(*dbw
);
3057 return AddAccountingEntry(acentry
, &walletdb
);
3060 bool CWallet::AddAccountingEntry(const CAccountingEntry
& acentry
, CWalletDB
*pwalletdb
)
3062 if (!pwalletdb
->WriteAccountingEntry(++nAccountingEntryNumber
, acentry
)) {
3066 laccentries
.push_back(acentry
);
3067 CAccountingEntry
& entry
= laccentries
.back();
3068 wtxOrdered
.insert(std::make_pair(entry
.nOrderPos
, TxPair(nullptr, &entry
)));
3073 DBErrors
CWallet::LoadWallet(bool& fFirstRunRet
)
3075 LOCK2(cs_main
, cs_wallet
);
3077 fFirstRunRet
= false;
3078 DBErrors nLoadWalletRet
= CWalletDB(*dbw
,"cr+").LoadWallet(this);
3079 if (nLoadWalletRet
== DB_NEED_REWRITE
)
3081 if (dbw
->Rewrite("\x04pool"))
3083 setInternalKeyPool
.clear();
3084 setExternalKeyPool
.clear();
3085 m_pool_key_to_index
.clear();
3086 // Note: can't top-up keypool here, because wallet is locked.
3087 // User will be prompted to unlock wallet the next operation
3088 // that requires a new key.
3092 // This wallet is in its first run if all of these are empty
3093 fFirstRunRet
= mapKeys
.empty() && mapCryptedKeys
.empty() && mapWatchKeys
.empty() && setWatchOnly
.empty() && mapScripts
.empty();
3095 if (nLoadWalletRet
!= DB_LOAD_OK
)
3096 return nLoadWalletRet
;
3098 uiInterface
.LoadWallet(this);
3103 DBErrors
CWallet::ZapSelectTx(std::vector
<uint256
>& vHashIn
, std::vector
<uint256
>& vHashOut
)
3105 AssertLockHeld(cs_wallet
); // mapWallet
3106 DBErrors nZapSelectTxRet
= CWalletDB(*dbw
,"cr+").ZapSelectTx(vHashIn
, vHashOut
);
3107 for (uint256 hash
: vHashOut
)
3108 mapWallet
.erase(hash
);
3110 if (nZapSelectTxRet
== DB_NEED_REWRITE
)
3112 if (dbw
->Rewrite("\x04pool"))
3114 setInternalKeyPool
.clear();
3115 setExternalKeyPool
.clear();
3116 m_pool_key_to_index
.clear();
3117 // Note: can't top-up keypool here, because wallet is locked.
3118 // User will be prompted to unlock wallet the next operation
3119 // that requires a new key.
3123 if (nZapSelectTxRet
!= DB_LOAD_OK
)
3124 return nZapSelectTxRet
;
3132 DBErrors
CWallet::ZapWalletTx(std::vector
<CWalletTx
>& vWtx
)
3134 DBErrors nZapWalletTxRet
= CWalletDB(*dbw
,"cr+").ZapWalletTx(vWtx
);
3135 if (nZapWalletTxRet
== DB_NEED_REWRITE
)
3137 if (dbw
->Rewrite("\x04pool"))
3140 setInternalKeyPool
.clear();
3141 setExternalKeyPool
.clear();
3142 m_pool_key_to_index
.clear();
3143 // Note: can't top-up keypool here, because wallet is locked.
3144 // User will be prompted to unlock wallet the next operation
3145 // that requires a new key.
3149 if (nZapWalletTxRet
!= DB_LOAD_OK
)
3150 return nZapWalletTxRet
;
3156 bool CWallet::SetAddressBook(const CTxDestination
& address
, const std::string
& strName
, const std::string
& strPurpose
)
3158 bool fUpdated
= false;
3160 LOCK(cs_wallet
); // mapAddressBook
3161 std::map
<CTxDestination
, CAddressBookData
>::iterator mi
= mapAddressBook
.find(address
);
3162 fUpdated
= mi
!= mapAddressBook
.end();
3163 mapAddressBook
[address
].name
= strName
;
3164 if (!strPurpose
.empty()) /* update purpose only if requested */
3165 mapAddressBook
[address
].purpose
= strPurpose
;
3167 NotifyAddressBookChanged(this, address
, strName
, ::IsMine(*this, address
) != ISMINE_NO
,
3168 strPurpose
, (fUpdated
? CT_UPDATED
: CT_NEW
) );
3169 if (!strPurpose
.empty() && !CWalletDB(*dbw
).WritePurpose(EncodeDestination(address
), strPurpose
))
3171 return CWalletDB(*dbw
).WriteName(EncodeDestination(address
), strName
);
3174 bool CWallet::DelAddressBook(const CTxDestination
& address
)
3177 LOCK(cs_wallet
); // mapAddressBook
3179 // Delete destdata tuples associated with address
3180 std::string strAddress
= EncodeDestination(address
);
3181 for (const std::pair
<std::string
, std::string
> &item
: mapAddressBook
[address
].destdata
)
3183 CWalletDB(*dbw
).EraseDestData(strAddress
, item
.first
);
3185 mapAddressBook
.erase(address
);
3188 NotifyAddressBookChanged(this, address
, "", ::IsMine(*this, address
) != ISMINE_NO
, "", CT_DELETED
);
3190 CWalletDB(*dbw
).ErasePurpose(EncodeDestination(address
));
3191 return CWalletDB(*dbw
).EraseName(EncodeDestination(address
));
3194 const std::string
& CWallet::GetAccountName(const CScript
& scriptPubKey
) const
3196 CTxDestination address
;
3197 if (ExtractDestination(scriptPubKey
, address
) && !scriptPubKey
.IsUnspendable()) {
3198 auto mi
= mapAddressBook
.find(address
);
3199 if (mi
!= mapAddressBook
.end()) {
3200 return mi
->second
.name
;
3203 // A scriptPubKey that doesn't have an entry in the address book is
3204 // associated with the default account ("").
3205 const static std::string DEFAULT_ACCOUNT_NAME
;
3206 return DEFAULT_ACCOUNT_NAME
;
3210 * Mark old keypool keys as used,
3211 * and generate all new keys
3213 bool CWallet::NewKeyPool()
3217 CWalletDB
walletdb(*dbw
);
3219 for (int64_t nIndex
: setInternalKeyPool
) {
3220 walletdb
.ErasePool(nIndex
);
3222 setInternalKeyPool
.clear();
3224 for (int64_t nIndex
: setExternalKeyPool
) {
3225 walletdb
.ErasePool(nIndex
);
3227 setExternalKeyPool
.clear();
3229 m_pool_key_to_index
.clear();
3231 if (!TopUpKeyPool()) {
3234 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3239 size_t CWallet::KeypoolCountExternalKeys()
3241 AssertLockHeld(cs_wallet
); // setExternalKeyPool
3242 return setExternalKeyPool
.size();
3245 void CWallet::LoadKeyPool(int64_t nIndex
, const CKeyPool
&keypool
)
3247 AssertLockHeld(cs_wallet
);
3248 if (keypool
.fInternal
) {
3249 setInternalKeyPool
.insert(nIndex
);
3251 setExternalKeyPool
.insert(nIndex
);
3253 m_max_keypool_index
= std::max(m_max_keypool_index
, nIndex
);
3254 m_pool_key_to_index
[keypool
.vchPubKey
.GetID()] = nIndex
;
3256 // If no metadata exists yet, create a default with the pool key's
3257 // creation time. Note that this may be overwritten by actually
3258 // stored metadata for that key later, which is fine.
3259 CKeyID keyid
= keypool
.vchPubKey
.GetID();
3260 if (mapKeyMetadata
.count(keyid
) == 0)
3261 mapKeyMetadata
[keyid
] = CKeyMetadata(keypool
.nTime
);
3264 bool CWallet::TopUpKeyPool(unsigned int kpSize
)
3273 unsigned int nTargetSize
;
3275 nTargetSize
= kpSize
;
3277 nTargetSize
= std::max(gArgs
.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE
), (int64_t) 0);
3279 // count amount of available keys (internal, external)
3280 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3281 int64_t missingExternal
= std::max(std::max((int64_t) nTargetSize
, (int64_t) 1) - (int64_t)setExternalKeyPool
.size(), (int64_t) 0);
3282 int64_t missingInternal
= std::max(std::max((int64_t) nTargetSize
, (int64_t) 1) - (int64_t)setInternalKeyPool
.size(), (int64_t) 0);
3284 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT
))
3286 // don't create extra internal keys
3287 missingInternal
= 0;
3289 bool internal
= false;
3290 CWalletDB
walletdb(*dbw
);
3291 for (int64_t i
= missingInternal
+ missingExternal
; i
--;)
3293 if (i
< missingInternal
) {
3297 assert(m_max_keypool_index
< std::numeric_limits
<int64_t>::max()); // How in the hell did you use so many keys?
3298 int64_t index
= ++m_max_keypool_index
;
3300 CPubKey
pubkey(GenerateNewKey(walletdb
, internal
));
3301 if (!walletdb
.WritePool(index
, CKeyPool(pubkey
, internal
))) {
3302 throw std::runtime_error(std::string(__func__
) + ": writing generated key failed");
3306 setInternalKeyPool
.insert(index
);
3308 setExternalKeyPool
.insert(index
);
3310 m_pool_key_to_index
[pubkey
.GetID()] = index
;
3312 if (missingInternal
+ missingExternal
> 0) {
3313 LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal
+ missingExternal
, missingInternal
, setInternalKeyPool
.size() + setExternalKeyPool
.size(), setInternalKeyPool
.size());
3319 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex
, CKeyPool
& keypool
, bool fRequestedInternal
)
3322 keypool
.vchPubKey
= CPubKey();
3329 bool fReturningInternal
= IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT
) && fRequestedInternal
;
3330 std::set
<int64_t>& setKeyPool
= fReturningInternal
? setInternalKeyPool
: setExternalKeyPool
;
3332 // Get the oldest key
3333 if(setKeyPool
.empty())
3336 CWalletDB
walletdb(*dbw
);
3338 auto it
= setKeyPool
.begin();
3340 setKeyPool
.erase(it
);
3341 if (!walletdb
.ReadPool(nIndex
, keypool
)) {
3342 throw std::runtime_error(std::string(__func__
) + ": read failed");
3344 if (!HaveKey(keypool
.vchPubKey
.GetID())) {
3345 throw std::runtime_error(std::string(__func__
) + ": unknown key in key pool");
3347 if (keypool
.fInternal
!= fReturningInternal
) {
3348 throw std::runtime_error(std::string(__func__
) + ": keypool entry misclassified");
3351 assert(keypool
.vchPubKey
.IsValid());
3352 m_pool_key_to_index
.erase(keypool
.vchPubKey
.GetID());
3353 LogPrintf("keypool reserve %d\n", nIndex
);
3357 void CWallet::KeepKey(int64_t nIndex
)
3359 // Remove from key pool
3360 CWalletDB
walletdb(*dbw
);
3361 walletdb
.ErasePool(nIndex
);
3362 LogPrintf("keypool keep %d\n", nIndex
);
3365 void CWallet::ReturnKey(int64_t nIndex
, bool fInternal
, const CPubKey
& pubkey
)
3367 // Return to key pool
3371 setInternalKeyPool
.insert(nIndex
);
3373 setExternalKeyPool
.insert(nIndex
);
3375 m_pool_key_to_index
[pubkey
.GetID()] = nIndex
;
3377 LogPrintf("keypool return %d\n", nIndex
);
3380 bool CWallet::GetKeyFromPool(CPubKey
& result
, bool internal
)
3386 ReserveKeyFromKeyPool(nIndex
, keypool
, internal
);
3389 if (IsLocked()) return false;
3390 CWalletDB
walletdb(*dbw
);
3391 result
= GenerateNewKey(walletdb
, internal
);
3395 result
= keypool
.vchPubKey
;
3400 static int64_t GetOldestKeyTimeInPool(const std::set
<int64_t>& setKeyPool
, CWalletDB
& walletdb
) {
3401 if (setKeyPool
.empty()) {
3406 int64_t nIndex
= *(setKeyPool
.begin());
3407 if (!walletdb
.ReadPool(nIndex
, keypool
)) {
3408 throw std::runtime_error(std::string(__func__
) + ": read oldest key in keypool failed");
3410 assert(keypool
.vchPubKey
.IsValid());
3411 return keypool
.nTime
;
3414 int64_t CWallet::GetOldestKeyPoolTime()
3418 CWalletDB
walletdb(*dbw
);
3420 // load oldest key from keypool, get time and return
3421 int64_t oldestKey
= GetOldestKeyTimeInPool(setExternalKeyPool
, walletdb
);
3422 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT
)) {
3423 oldestKey
= std::max(GetOldestKeyTimeInPool(setInternalKeyPool
, walletdb
), oldestKey
);
3429 std::map
<CTxDestination
, CAmount
> CWallet::GetAddressBalances()
3431 std::map
<CTxDestination
, CAmount
> balances
;
3435 for (const auto& walletEntry
: mapWallet
)
3437 const CWalletTx
*pcoin
= &walletEntry
.second
;
3439 if (!pcoin
->IsTrusted())
3442 if (pcoin
->IsCoinBase() && pcoin
->GetBlocksToMaturity() > 0)
3445 int nDepth
= pcoin
->GetDepthInMainChain();
3446 if (nDepth
< (pcoin
->IsFromMe(ISMINE_ALL
) ? 0 : 1))
3449 for (unsigned int i
= 0; i
< pcoin
->tx
->vout
.size(); i
++)
3451 CTxDestination addr
;
3452 if (!IsMine(pcoin
->tx
->vout
[i
]))
3454 if(!ExtractDestination(pcoin
->tx
->vout
[i
].scriptPubKey
, addr
))
3457 CAmount n
= IsSpent(walletEntry
.first
, i
) ? 0 : pcoin
->tx
->vout
[i
].nValue
;
3459 if (!balances
.count(addr
))
3461 balances
[addr
] += n
;
3469 std::set
< std::set
<CTxDestination
> > CWallet::GetAddressGroupings()
3471 AssertLockHeld(cs_wallet
); // mapWallet
3472 std::set
< std::set
<CTxDestination
> > groupings
;
3473 std::set
<CTxDestination
> grouping
;
3475 for (const auto& walletEntry
: mapWallet
)
3477 const CWalletTx
*pcoin
= &walletEntry
.second
;
3479 if (pcoin
->tx
->vin
.size() > 0)
3481 bool any_mine
= false;
3482 // group all input addresses with each other
3483 for (CTxIn txin
: pcoin
->tx
->vin
)
3485 CTxDestination address
;
3486 if(!IsMine(txin
)) /* If this input isn't mine, ignore it */
3488 if(!ExtractDestination(mapWallet
[txin
.prevout
.hash
].tx
->vout
[txin
.prevout
.n
].scriptPubKey
, address
))
3490 grouping
.insert(address
);
3494 // group change with input addresses
3497 for (CTxOut txout
: pcoin
->tx
->vout
)
3498 if (IsChange(txout
))
3500 CTxDestination txoutAddr
;
3501 if(!ExtractDestination(txout
.scriptPubKey
, txoutAddr
))
3503 grouping
.insert(txoutAddr
);
3506 if (grouping
.size() > 0)
3508 groupings
.insert(grouping
);
3513 // group lone addrs by themselves
3514 for (const auto& txout
: pcoin
->tx
->vout
)
3517 CTxDestination address
;
3518 if(!ExtractDestination(txout
.scriptPubKey
, address
))
3520 grouping
.insert(address
);
3521 groupings
.insert(grouping
);
3526 std::set
< std::set
<CTxDestination
>* > uniqueGroupings
; // a set of pointers to groups of addresses
3527 std::map
< CTxDestination
, std::set
<CTxDestination
>* > setmap
; // map addresses to the unique group containing it
3528 for (std::set
<CTxDestination
> _grouping
: groupings
)
3530 // make a set of all the groups hit by this new group
3531 std::set
< std::set
<CTxDestination
>* > hits
;
3532 std::map
< CTxDestination
, std::set
<CTxDestination
>* >::iterator it
;
3533 for (CTxDestination address
: _grouping
)
3534 if ((it
= setmap
.find(address
)) != setmap
.end())
3535 hits
.insert((*it
).second
);
3537 // merge all hit groups into a new single group and delete old groups
3538 std::set
<CTxDestination
>* merged
= new std::set
<CTxDestination
>(_grouping
);
3539 for (std::set
<CTxDestination
>* hit
: hits
)
3541 merged
->insert(hit
->begin(), hit
->end());
3542 uniqueGroupings
.erase(hit
);
3545 uniqueGroupings
.insert(merged
);
3548 for (CTxDestination element
: *merged
)
3549 setmap
[element
] = merged
;
3552 std::set
< std::set
<CTxDestination
> > ret
;
3553 for (std::set
<CTxDestination
>* uniqueGrouping
: uniqueGroupings
)
3555 ret
.insert(*uniqueGrouping
);
3556 delete uniqueGrouping
;
3562 std::set
<CTxDestination
> CWallet::GetAccountAddresses(const std::string
& strAccount
) const
3565 std::set
<CTxDestination
> result
;
3566 for (const std::pair
<CTxDestination
, CAddressBookData
>& item
: mapAddressBook
)
3568 const CTxDestination
& address
= item
.first
;
3569 const std::string
& strName
= item
.second
.name
;
3570 if (strName
== strAccount
)
3571 result
.insert(address
);
3576 bool CReserveKey::GetReservedKey(CPubKey
& pubkey
, bool internal
)
3581 pwallet
->ReserveKeyFromKeyPool(nIndex
, keypool
, internal
);
3583 vchPubKey
= keypool
.vchPubKey
;
3587 fInternal
= keypool
.fInternal
;
3589 assert(vchPubKey
.IsValid());
3594 void CReserveKey::KeepKey()
3597 pwallet
->KeepKey(nIndex
);
3599 vchPubKey
= CPubKey();
3602 void CReserveKey::ReturnKey()
3605 pwallet
->ReturnKey(nIndex
, fInternal
, vchPubKey
);
3608 vchPubKey
= CPubKey();
3611 void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id
)
3613 AssertLockHeld(cs_wallet
);
3614 bool internal
= setInternalKeyPool
.count(keypool_id
);
3615 if (!internal
) assert(setExternalKeyPool
.count(keypool_id
));
3616 std::set
<int64_t> *setKeyPool
= internal
? &setInternalKeyPool
: &setExternalKeyPool
;
3617 auto it
= setKeyPool
->begin();
3619 CWalletDB
walletdb(*dbw
);
3620 while (it
!= std::end(*setKeyPool
)) {
3621 const int64_t& index
= *(it
);
3622 if (index
> keypool_id
) break; // set*KeyPool is ordered
3625 if (walletdb
.ReadPool(index
, keypool
)) { //TODO: This should be unnecessary
3626 m_pool_key_to_index
.erase(keypool
.vchPubKey
.GetID());
3628 walletdb
.ErasePool(index
);
3629 LogPrintf("keypool index %d removed\n", index
);
3630 it
= setKeyPool
->erase(it
);
3634 void CWallet::GetScriptForMining(std::shared_ptr
<CReserveScript
> &script
)
3636 std::shared_ptr
<CReserveKey
> rKey
= std::make_shared
<CReserveKey
>(this);
3638 if (!rKey
->GetReservedKey(pubkey
))
3642 script
->reserveScript
= CScript() << ToByteVector(pubkey
) << OP_CHECKSIG
;
3645 void CWallet::LockCoin(const COutPoint
& output
)
3647 AssertLockHeld(cs_wallet
); // setLockedCoins
3648 setLockedCoins
.insert(output
);
3651 void CWallet::UnlockCoin(const COutPoint
& output
)
3653 AssertLockHeld(cs_wallet
); // setLockedCoins
3654 setLockedCoins
.erase(output
);
3657 void CWallet::UnlockAllCoins()
3659 AssertLockHeld(cs_wallet
); // setLockedCoins
3660 setLockedCoins
.clear();
3663 bool CWallet::IsLockedCoin(uint256 hash
, unsigned int n
) const
3665 AssertLockHeld(cs_wallet
); // setLockedCoins
3666 COutPoint
outpt(hash
, n
);
3668 return (setLockedCoins
.count(outpt
) > 0);
3671 void CWallet::ListLockedCoins(std::vector
<COutPoint
>& vOutpts
) const
3673 AssertLockHeld(cs_wallet
); // setLockedCoins
3674 for (std::set
<COutPoint
>::iterator it
= setLockedCoins
.begin();
3675 it
!= setLockedCoins
.end(); it
++) {
3676 COutPoint outpt
= (*it
);
3677 vOutpts
.push_back(outpt
);
3681 /** @} */ // end of Actions
3683 void CWallet::GetKeyBirthTimes(std::map
<CTxDestination
, int64_t> &mapKeyBirth
) const {
3684 AssertLockHeld(cs_wallet
); // mapKeyMetadata
3685 mapKeyBirth
.clear();
3687 // get birth times for keys with metadata
3688 for (const auto& entry
: mapKeyMetadata
) {
3689 if (entry
.second
.nCreateTime
) {
3690 mapKeyBirth
[entry
.first
] = entry
.second
.nCreateTime
;
3694 // map in which we'll infer heights of other keys
3695 CBlockIndex
*pindexMax
= chainActive
[std::max(0, chainActive
.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3696 std::map
<CKeyID
, CBlockIndex
*> mapKeyFirstBlock
;
3697 for (const CKeyID
&keyid
: GetKeys()) {
3698 if (mapKeyBirth
.count(keyid
) == 0)
3699 mapKeyFirstBlock
[keyid
] = pindexMax
;
3702 // if there are no such keys, we're done
3703 if (mapKeyFirstBlock
.empty())
3706 // find first block that affects those keys, if there are any left
3707 std::vector
<CKeyID
> vAffected
;
3708 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); it
++) {
3709 // iterate over all wallet transactions...
3710 const CWalletTx
&wtx
= (*it
).second
;
3711 BlockMap::const_iterator blit
= mapBlockIndex
.find(wtx
.hashBlock
);
3712 if (blit
!= mapBlockIndex
.end() && chainActive
.Contains(blit
->second
)) {
3713 // ... which are already in a block
3714 int nHeight
= blit
->second
->nHeight
;
3715 for (const CTxOut
&txout
: wtx
.tx
->vout
) {
3716 // iterate over all their outputs
3717 CAffectedKeysVisitor(*this, vAffected
).Process(txout
.scriptPubKey
);
3718 for (const CKeyID
&keyid
: vAffected
) {
3719 // ... and all their affected keys
3720 std::map
<CKeyID
, CBlockIndex
*>::iterator rit
= mapKeyFirstBlock
.find(keyid
);
3721 if (rit
!= mapKeyFirstBlock
.end() && nHeight
< rit
->second
->nHeight
)
3722 rit
->second
= blit
->second
;
3729 // Extract block timestamps for those keys
3730 for (std::map
<CKeyID
, CBlockIndex
*>::const_iterator it
= mapKeyFirstBlock
.begin(); it
!= mapKeyFirstBlock
.end(); it
++)
3731 mapKeyBirth
[it
->first
] = it
->second
->GetBlockTime() - TIMESTAMP_WINDOW
; // block times can be 2h off
3735 * Compute smart timestamp for a transaction being added to the wallet.
3738 * - If sending a transaction, assign its timestamp to the current time.
3739 * - If receiving a transaction outside a block, assign its timestamp to the
3741 * - If receiving a block with a future timestamp, assign all its (not already
3742 * known) transactions' timestamps to the current time.
3743 * - If receiving a block with a past timestamp, before the most recent known
3744 * transaction (that we care about), assign all its (not already known)
3745 * transactions' timestamps to the same timestamp as that most-recent-known
3747 * - If receiving a block with a past timestamp, but after the most recent known
3748 * transaction, assign all its (not already known) transactions' timestamps to
3751 * For more information see CWalletTx::nTimeSmart,
3752 * https://bitcointalk.org/?topic=54527, or
3753 * https://github.com/bitcoin/bitcoin/pull/1393.
3755 unsigned int CWallet::ComputeTimeSmart(const CWalletTx
& wtx
) const
3757 unsigned int nTimeSmart
= wtx
.nTimeReceived
;
3758 if (!wtx
.hashUnset()) {
3759 if (mapBlockIndex
.count(wtx
.hashBlock
)) {
3760 int64_t latestNow
= wtx
.nTimeReceived
;
3761 int64_t latestEntry
= 0;
3763 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3764 int64_t latestTolerated
= latestNow
+ 300;
3765 const TxItems
& txOrdered
= wtxOrdered
;
3766 for (auto it
= txOrdered
.rbegin(); it
!= txOrdered
.rend(); ++it
) {
3767 CWalletTx
* const pwtx
= it
->second
.first
;
3771 CAccountingEntry
* const pacentry
= it
->second
.second
;
3774 nSmartTime
= pwtx
->nTimeSmart
;
3776 nSmartTime
= pwtx
->nTimeReceived
;
3779 nSmartTime
= pacentry
->nTime
;
3781 if (nSmartTime
<= latestTolerated
) {
3782 latestEntry
= nSmartTime
;
3783 if (nSmartTime
> latestNow
) {
3784 latestNow
= nSmartTime
;
3790 int64_t blocktime
= mapBlockIndex
[wtx
.hashBlock
]->GetBlockTime();
3791 nTimeSmart
= std::max(latestEntry
, std::min(blocktime
, latestNow
));
3793 LogPrintf("%s: found %s in block %s not in index\n", __func__
, wtx
.GetHash().ToString(), wtx
.hashBlock
.ToString());
3799 bool CWallet::AddDestData(const CTxDestination
&dest
, const std::string
&key
, const std::string
&value
)
3801 if (boost::get
<CNoDestination
>(&dest
))
3804 mapAddressBook
[dest
].destdata
.insert(std::make_pair(key
, value
));
3805 return CWalletDB(*dbw
).WriteDestData(EncodeDestination(dest
), key
, value
);
3808 bool CWallet::EraseDestData(const CTxDestination
&dest
, const std::string
&key
)
3810 if (!mapAddressBook
[dest
].destdata
.erase(key
))
3812 return CWalletDB(*dbw
).EraseDestData(EncodeDestination(dest
), key
);
3815 bool CWallet::LoadDestData(const CTxDestination
&dest
, const std::string
&key
, const std::string
&value
)
3817 mapAddressBook
[dest
].destdata
.insert(std::make_pair(key
, value
));
3821 bool CWallet::GetDestData(const CTxDestination
&dest
, const std::string
&key
, std::string
*value
) const
3823 std::map
<CTxDestination
, CAddressBookData
>::const_iterator i
= mapAddressBook
.find(dest
);
3824 if(i
!= mapAddressBook
.end())
3826 CAddressBookData::StringMap::const_iterator j
= i
->second
.destdata
.find(key
);
3827 if(j
!= i
->second
.destdata
.end())
3837 std::vector
<std::string
> CWallet::GetDestValues(const std::string
& prefix
) const
3840 std::vector
<std::string
> values
;
3841 for (const auto& address
: mapAddressBook
) {
3842 for (const auto& data
: address
.second
.destdata
) {
3843 if (!data
.first
.compare(0, prefix
.size(), prefix
)) {
3844 values
.emplace_back(data
.second
);
3851 CWallet
* CWallet::CreateWalletFromFile(const std::string walletFile
)
3853 // needed to restore wallet transaction meta data after -zapwallettxes
3854 std::vector
<CWalletTx
> vWtx
;
3856 if (gArgs
.GetBoolArg("-zapwallettxes", false)) {
3857 uiInterface
.InitMessage(_("Zapping all transactions from wallet..."));
3859 std::unique_ptr
<CWalletDBWrapper
> dbw(new CWalletDBWrapper(&bitdb
, walletFile
));
3860 std::unique_ptr
<CWallet
> tempWallet
= MakeUnique
<CWallet
>(std::move(dbw
));
3861 DBErrors nZapWalletRet
= tempWallet
->ZapWalletTx(vWtx
);
3862 if (nZapWalletRet
!= DB_LOAD_OK
) {
3863 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile
));
3868 uiInterface
.InitMessage(_("Loading wallet..."));
3870 int64_t nStart
= GetTimeMillis();
3871 bool fFirstRun
= true;
3872 std::unique_ptr
<CWalletDBWrapper
> dbw(new CWalletDBWrapper(&bitdb
, walletFile
));
3873 CWallet
*walletInstance
= new CWallet(std::move(dbw
));
3874 DBErrors nLoadWalletRet
= walletInstance
->LoadWallet(fFirstRun
);
3875 if (nLoadWalletRet
!= DB_LOAD_OK
)
3877 if (nLoadWalletRet
== DB_CORRUPT
) {
3878 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile
));
3881 else if (nLoadWalletRet
== DB_NONCRITICAL_ERROR
)
3883 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3884 " or address book entries might be missing or incorrect."),
3887 else if (nLoadWalletRet
== DB_TOO_NEW
) {
3888 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile
, _(PACKAGE_NAME
)));
3891 else if (nLoadWalletRet
== DB_NEED_REWRITE
)
3893 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME
)));
3897 InitError(strprintf(_("Error loading %s"), walletFile
));
3902 if (gArgs
.GetBoolArg("-upgradewallet", fFirstRun
))
3904 int nMaxVersion
= gArgs
.GetArg("-upgradewallet", 0);
3905 if (nMaxVersion
== 0) // the -upgradewallet without argument case
3907 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST
);
3908 nMaxVersion
= CLIENT_VERSION
;
3909 walletInstance
->SetMinVersion(FEATURE_LATEST
); // permanently upgrade the wallet immediately
3912 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion
);
3913 if (nMaxVersion
< walletInstance
->GetVersion())
3915 InitError(_("Cannot downgrade wallet"));
3918 walletInstance
->SetMaxVersion(nMaxVersion
);
3923 // ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
3924 if (!gArgs
.GetBoolArg("-usehd", true)) {
3925 InitError(strprintf(_("Error creating %s: You can't create non-HD wallets with this version."), walletFile
));
3928 walletInstance
->SetMinVersion(FEATURE_NO_DEFAULT_KEY
);
3930 // generate a new master key
3931 CPubKey masterPubKey
= walletInstance
->GenerateNewHDMasterKey();
3932 if (!walletInstance
->SetHDMasterKey(masterPubKey
))
3933 throw std::runtime_error(std::string(__func__
) + ": Storing master key failed");
3935 // Top up the keypool
3936 if (!walletInstance
->TopUpKeyPool()) {
3937 InitError(_("Unable to generate initial keys") += "\n");
3941 walletInstance
->SetBestChain(chainActive
.GetLocator());
3943 else if (gArgs
.IsArgSet("-usehd")) {
3944 bool useHD
= gArgs
.GetBoolArg("-usehd", true);
3945 if (walletInstance
->IsHDEnabled() && !useHD
) {
3946 InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile
));
3949 if (!walletInstance
->IsHDEnabled() && useHD
) {
3950 InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile
));
3955 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart
);
3957 // Try to top up keypool. No-op if the wallet is locked.
3958 walletInstance
->TopUpKeyPool();
3960 CBlockIndex
*pindexRescan
= chainActive
.Genesis();
3961 if (!gArgs
.GetBoolArg("-rescan", false))
3963 CWalletDB
walletdb(*walletInstance
->dbw
);
3964 CBlockLocator locator
;
3965 if (walletdb
.ReadBestBlock(locator
))
3966 pindexRescan
= FindForkInGlobalIndex(chainActive
, locator
);
3969 walletInstance
->m_last_block_processed
= chainActive
.Tip();
3970 RegisterValidationInterface(walletInstance
);
3972 if (chainActive
.Tip() && chainActive
.Tip() != pindexRescan
)
3974 //We can't rescan beyond non-pruned blocks, stop and throw an error
3975 //this might happen if a user uses an old wallet within a pruned node
3976 // or if he ran -disablewallet for a longer time, then decided to re-enable
3979 CBlockIndex
*block
= chainActive
.Tip();
3980 while (block
&& block
->pprev
&& (block
->pprev
->nStatus
& BLOCK_HAVE_DATA
) && block
->pprev
->nTx
> 0 && pindexRescan
!= block
)
3981 block
= block
->pprev
;
3983 if (pindexRescan
!= block
) {
3984 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3989 uiInterface
.InitMessage(_("Rescanning..."));
3990 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive
.Height() - pindexRescan
->nHeight
, pindexRescan
->nHeight
);
3992 // No need to read and scan block if block was created before
3993 // our wallet birthday (as adjusted for block time variability)
3994 while (pindexRescan
&& walletInstance
->nTimeFirstKey
&& (pindexRescan
->GetBlockTime() < (walletInstance
->nTimeFirstKey
- TIMESTAMP_WINDOW
))) {
3995 pindexRescan
= chainActive
.Next(pindexRescan
);
3998 nStart
= GetTimeMillis();
3999 walletInstance
->ScanForWalletTransactions(pindexRescan
, nullptr, true);
4000 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart
);
4001 walletInstance
->SetBestChain(chainActive
.GetLocator());
4002 walletInstance
->dbw
->IncrementUpdateCounter();
4004 // Restore wallet transaction metadata after -zapwallettxes=1
4005 if (gArgs
.GetBoolArg("-zapwallettxes", false) && gArgs
.GetArg("-zapwallettxes", "1") != "2")
4007 CWalletDB
walletdb(*walletInstance
->dbw
);
4009 for (const CWalletTx
& wtxOld
: vWtx
)
4011 uint256 hash
= wtxOld
.GetHash();
4012 std::map
<uint256
, CWalletTx
>::iterator mi
= walletInstance
->mapWallet
.find(hash
);
4013 if (mi
!= walletInstance
->mapWallet
.end())
4015 const CWalletTx
* copyFrom
= &wtxOld
;
4016 CWalletTx
* copyTo
= &mi
->second
;
4017 copyTo
->mapValue
= copyFrom
->mapValue
;
4018 copyTo
->vOrderForm
= copyFrom
->vOrderForm
;
4019 copyTo
->nTimeReceived
= copyFrom
->nTimeReceived
;
4020 copyTo
->nTimeSmart
= copyFrom
->nTimeSmart
;
4021 copyTo
->fFromMe
= copyFrom
->fFromMe
;
4022 copyTo
->strFromAccount
= copyFrom
->strFromAccount
;
4023 copyTo
->nOrderPos
= copyFrom
->nOrderPos
;
4024 walletdb
.WriteTx(*copyTo
);
4029 walletInstance
->SetBroadcastTransactions(gArgs
.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST
));
4032 LOCK(walletInstance
->cs_wallet
);
4033 LogPrintf("setKeyPool.size() = %u\n", walletInstance
->GetKeyPoolSize());
4034 LogPrintf("mapWallet.size() = %u\n", walletInstance
->mapWallet
.size());
4035 LogPrintf("mapAddressBook.size() = %u\n", walletInstance
->mapAddressBook
.size());
4038 return walletInstance
;
4041 std::atomic
<bool> CWallet::fFlushScheduled(false);
4043 void CWallet::postInitProcess(CScheduler
& scheduler
)
4045 // Add wallet transactions that aren't already in a block to mempool
4046 // Do this here as mempool requires genesis block to be loaded
4047 ReacceptWalletTransactions();
4049 // Run a thread to flush wallet periodically
4050 if (!CWallet::fFlushScheduled
.exchange(true)) {
4051 scheduler
.scheduleEvery(MaybeCompactWalletDB
, 500);
4055 bool CWallet::BackupWallet(const std::string
& strDest
)
4057 return dbw
->Backup(strDest
);
4060 CKeyPool::CKeyPool()
4066 CKeyPool::CKeyPool(const CPubKey
& vchPubKeyIn
, bool internalIn
)
4069 vchPubKey
= vchPubKeyIn
;
4070 fInternal
= internalIn
;
4073 CWalletKey::CWalletKey(int64_t nExpires
)
4075 nTimeCreated
= (nExpires
? GetTime() : 0);
4076 nTimeExpires
= nExpires
;
4079 void CMerkleTx::SetMerkleBranch(const CBlockIndex
* pindex
, int posInBlock
)
4081 // Update the tx's hashBlock
4082 hashBlock
= pindex
->GetBlockHash();
4084 // set the position of the transaction in the block
4085 nIndex
= posInBlock
;
4088 int CMerkleTx::GetDepthInMainChain(const CBlockIndex
* &pindexRet
) const
4093 AssertLockHeld(cs_main
);
4095 // Find the block it claims to be in
4096 BlockMap::iterator mi
= mapBlockIndex
.find(hashBlock
);
4097 if (mi
== mapBlockIndex
.end())
4099 CBlockIndex
* pindex
= (*mi
).second
;
4100 if (!pindex
|| !chainActive
.Contains(pindex
))
4104 return ((nIndex
== -1) ? (-1) : 1) * (chainActive
.Height() - pindex
->nHeight
+ 1);
4107 int CMerkleTx::GetBlocksToMaturity() const
4111 return std::max(0, (COINBASE_MATURITY
+1) - GetDepthInMainChain());
4115 bool CWalletTx::AcceptToMemoryPool(const CAmount
& nAbsurdFee
, CValidationState
& state
)
4117 // We must set fInMempool here - while it will be re-set to true by the
4118 // entered-mempool callback, if we did not there would be a race where a
4119 // user could call sendmoney in a loop and hit spurious out of funds errors
4120 // because we think that the transaction they just generated's change is
4121 // unavailable as we're not yet aware its in mempool.
4122 bool ret
= ::AcceptToMemoryPool(mempool
, state
, tx
, nullptr /* pfMissingInputs */,
4123 nullptr /* plTxnReplaced */, false /* bypass_limits */, nAbsurdFee
);