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"
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"
37 #include <boost/algorithm/string/replace.hpp>
38 #include <boost/thread.hpp>
40 std::vector
<CWalletRef
> vpwallets
;
41 /** Transaction fee set by the user */
42 CFeeRate
payTxFee(DEFAULT_TRANSACTION_FEE
);
43 unsigned int nTxConfirmTarget
= DEFAULT_TX_CONFIRM_TARGET
;
44 bool bSpendZeroConfChange
= DEFAULT_SPEND_ZEROCONF_CHANGE
;
45 bool fWalletRbf
= DEFAULT_WALLET_RBF
;
47 const char * DEFAULT_WALLET_DAT
= "wallet.dat";
48 const uint32_t BIP32_HARDENED_KEY_LIMIT
= 0x80000000;
51 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
52 * Override with -mintxfee
54 CFeeRate
CWallet::minTxFee
= CFeeRate(DEFAULT_TRANSACTION_MINFEE
);
56 * If fee estimation does not have enough data to provide estimates, use this fee instead.
57 * Has no effect if not using fee estimation
58 * Override with -fallbackfee
60 CFeeRate
CWallet::fallbackFee
= CFeeRate(DEFAULT_FALLBACK_FEE
);
62 CFeeRate
CWallet::m_discard_rate
= CFeeRate(DEFAULT_DISCARD_FEE
);
64 const uint256
CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
66 /** @defgroup mapWallet
71 struct CompareValueOnly
73 bool operator()(const CInputCoin
& t1
,
74 const CInputCoin
& t2
) const
76 return t1
.txout
.nValue
< t2
.txout
.nValue
;
80 std::string
COutput::ToString() const
82 return strprintf("COutput(%s, %d, %d) [%s]", tx
->GetHash().ToString(), i
, nDepth
, FormatMoney(tx
->tx
->vout
[i
].nValue
));
85 class CAffectedKeysVisitor
: public boost::static_visitor
<void> {
87 const CKeyStore
&keystore
;
88 std::vector
<CKeyID
> &vKeys
;
91 CAffectedKeysVisitor(const CKeyStore
&keystoreIn
, std::vector
<CKeyID
> &vKeysIn
) : keystore(keystoreIn
), vKeys(vKeysIn
) {}
93 void Process(const CScript
&script
) {
95 std::vector
<CTxDestination
> vDest
;
97 if (ExtractDestinations(script
, type
, vDest
, nRequired
)) {
98 for (const CTxDestination
&dest
: vDest
)
99 boost::apply_visitor(*this, dest
);
103 void operator()(const CKeyID
&keyId
) {
104 if (keystore
.HaveKey(keyId
))
105 vKeys
.push_back(keyId
);
108 void operator()(const CScriptID
&scriptId
) {
110 if (keystore
.GetCScript(scriptId
, script
))
114 void operator()(const WitnessV0ScriptHash
& scriptID
)
117 CRIPEMD160().Write(scriptID
.begin(), 32).Finalize(id
.begin());
119 if (keystore
.GetCScript(id
, script
)) {
124 void operator()(const WitnessV0KeyHash
& keyid
)
127 if (keystore
.HaveKey(id
)) {
133 void operator()(const X
&none
) {}
136 const CWalletTx
* CWallet::GetWalletTx(const uint256
& hash
) const
139 std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.find(hash
);
140 if (it
== mapWallet
.end())
142 return &(it
->second
);
145 CPubKey
CWallet::GenerateNewKey(CWalletDB
&walletdb
, bool internal
)
147 AssertLockHeld(cs_wallet
); // mapKeyMetadata
148 bool fCompressed
= CanSupportFeature(FEATURE_COMPRPUBKEY
); // default to compressed public keys if we want 0.6.0 wallets
152 // Create new metadata
153 int64_t nCreationTime
= GetTime();
154 CKeyMetadata
metadata(nCreationTime
);
156 // use HD key derivation if HD was enabled during wallet creation
158 DeriveNewChildKey(walletdb
, metadata
, secret
, (CanSupportFeature(FEATURE_HD_SPLIT
) ? internal
: false));
160 secret
.MakeNewKey(fCompressed
);
163 // Compressed public keys were introduced in version 0.6.0
165 SetMinVersion(FEATURE_COMPRPUBKEY
);
168 CPubKey pubkey
= secret
.GetPubKey();
169 assert(secret
.VerifyPubKey(pubkey
));
171 mapKeyMetadata
[pubkey
.GetID()] = metadata
;
172 UpdateTimeFirstKey(nCreationTime
);
174 if (!AddKeyPubKeyWithDB(walletdb
, secret
, pubkey
)) {
175 throw std::runtime_error(std::string(__func__
) + ": AddKey failed");
180 void CWallet::DeriveNewChildKey(CWalletDB
&walletdb
, CKeyMetadata
& metadata
, CKey
& secret
, bool internal
)
182 // for now we use a fixed keypath scheme of m/0'/0'/k
183 CKey key
; //master key seed (256bit)
184 CExtKey masterKey
; //hd master key
185 CExtKey accountKey
; //key at m/0'
186 CExtKey chainChildKey
; //key at m/0'/0' (external) or m/0'/1' (internal)
187 CExtKey childKey
; //key at m/0'/0'/<n>'
189 // try to get the master key
190 if (!GetKey(hdChain
.masterKeyID
, key
))
191 throw std::runtime_error(std::string(__func__
) + ": Master key not found");
193 masterKey
.SetMaster(key
.begin(), key
.size());
196 // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
197 masterKey
.Derive(accountKey
, BIP32_HARDENED_KEY_LIMIT
);
199 // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
200 assert(internal
? CanSupportFeature(FEATURE_HD_SPLIT
) : true);
201 accountKey
.Derive(chainChildKey
, BIP32_HARDENED_KEY_LIMIT
+(internal
? 1 : 0));
203 // derive child key at next index, skip keys already known to the wallet
205 // always derive hardened keys
206 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
207 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
209 chainChildKey
.Derive(childKey
, hdChain
.nInternalChainCounter
| BIP32_HARDENED_KEY_LIMIT
);
210 metadata
.hdKeypath
= "m/0'/1'/" + std::to_string(hdChain
.nInternalChainCounter
) + "'";
211 hdChain
.nInternalChainCounter
++;
214 chainChildKey
.Derive(childKey
, hdChain
.nExternalChainCounter
| BIP32_HARDENED_KEY_LIMIT
);
215 metadata
.hdKeypath
= "m/0'/0'/" + std::to_string(hdChain
.nExternalChainCounter
) + "'";
216 hdChain
.nExternalChainCounter
++;
218 } while (HaveKey(childKey
.key
.GetPubKey().GetID()));
219 secret
= childKey
.key
;
220 metadata
.hdMasterKeyID
= hdChain
.masterKeyID
;
221 // update the chain model in the database
222 if (!walletdb
.WriteHDChain(hdChain
))
223 throw std::runtime_error(std::string(__func__
) + ": Writing HD chain model failed");
226 bool CWallet::AddKeyPubKeyWithDB(CWalletDB
&walletdb
, const CKey
& secret
, const CPubKey
&pubkey
)
228 AssertLockHeld(cs_wallet
); // mapKeyMetadata
230 // CCryptoKeyStore has no concept of wallet databases, but calls AddCryptedKey
231 // which is overridden below. To avoid flushes, the database handle is
232 // tunneled through to it.
233 bool needsDB
= !pwalletdbEncryption
;
235 pwalletdbEncryption
= &walletdb
;
237 if (!CCryptoKeyStore::AddKeyPubKey(secret
, pubkey
)) {
238 if (needsDB
) pwalletdbEncryption
= nullptr;
241 if (needsDB
) pwalletdbEncryption
= nullptr;
243 // check if we need to remove from watch-only
245 script
= GetScriptForDestination(pubkey
.GetID());
246 if (HaveWatchOnly(script
)) {
247 RemoveWatchOnly(script
);
249 script
= GetScriptForRawPubKey(pubkey
);
250 if (HaveWatchOnly(script
)) {
251 RemoveWatchOnly(script
);
255 return walletdb
.WriteKey(pubkey
,
257 mapKeyMetadata
[pubkey
.GetID()]);
262 bool CWallet::AddKeyPubKey(const CKey
& secret
, const CPubKey
&pubkey
)
264 CWalletDB
walletdb(*dbw
);
265 return CWallet::AddKeyPubKeyWithDB(walletdb
, secret
, pubkey
);
268 bool CWallet::AddCryptedKey(const CPubKey
&vchPubKey
,
269 const std::vector
<unsigned char> &vchCryptedSecret
)
271 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey
, vchCryptedSecret
))
275 if (pwalletdbEncryption
)
276 return pwalletdbEncryption
->WriteCryptedKey(vchPubKey
,
278 mapKeyMetadata
[vchPubKey
.GetID()]);
280 return CWalletDB(*dbw
).WriteCryptedKey(vchPubKey
,
282 mapKeyMetadata
[vchPubKey
.GetID()]);
286 bool CWallet::LoadKeyMetadata(const CTxDestination
& keyID
, const CKeyMetadata
&meta
)
288 AssertLockHeld(cs_wallet
); // mapKeyMetadata
289 UpdateTimeFirstKey(meta
.nCreateTime
);
290 mapKeyMetadata
[keyID
] = meta
;
294 bool CWallet::LoadCryptedKey(const CPubKey
&vchPubKey
, const std::vector
<unsigned char> &vchCryptedSecret
)
296 return CCryptoKeyStore::AddCryptedKey(vchPubKey
, vchCryptedSecret
);
300 * Update wallet first key creation time. This should be called whenever keys
301 * are added to the wallet, with the oldest key creation time.
303 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime
)
305 AssertLockHeld(cs_wallet
);
306 if (nCreateTime
<= 1) {
307 // Cannot determine birthday information, so set the wallet birthday to
308 // the beginning of time.
310 } else if (!nTimeFirstKey
|| nCreateTime
< nTimeFirstKey
) {
311 nTimeFirstKey
= nCreateTime
;
315 bool CWallet::AddCScript(const CScript
& redeemScript
)
317 if (!CCryptoKeyStore::AddCScript(redeemScript
))
319 return CWalletDB(*dbw
).WriteCScript(Hash160(redeemScript
), redeemScript
);
322 bool CWallet::LoadCScript(const CScript
& redeemScript
)
324 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
325 * that never can be redeemed. However, old wallets may still contain
326 * these. Do not add them to the wallet and warn. */
327 if (redeemScript
.size() > MAX_SCRIPT_ELEMENT_SIZE
)
329 std::string strAddr
= EncodeDestination(CScriptID(redeemScript
));
330 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",
331 __func__
, redeemScript
.size(), MAX_SCRIPT_ELEMENT_SIZE
, strAddr
);
335 return CCryptoKeyStore::AddCScript(redeemScript
);
338 bool CWallet::AddWatchOnly(const CScript
& dest
)
340 if (!CCryptoKeyStore::AddWatchOnly(dest
))
342 const CKeyMetadata
& meta
= mapKeyMetadata
[CScriptID(dest
)];
343 UpdateTimeFirstKey(meta
.nCreateTime
);
344 NotifyWatchonlyChanged(true);
345 return CWalletDB(*dbw
).WriteWatchOnly(dest
, meta
);
348 bool CWallet::AddWatchOnly(const CScript
& dest
, int64_t nCreateTime
)
350 mapKeyMetadata
[CScriptID(dest
)].nCreateTime
= nCreateTime
;
351 return AddWatchOnly(dest
);
354 bool CWallet::RemoveWatchOnly(const CScript
&dest
)
356 AssertLockHeld(cs_wallet
);
357 if (!CCryptoKeyStore::RemoveWatchOnly(dest
))
359 if (!HaveWatchOnly())
360 NotifyWatchonlyChanged(false);
361 if (!CWalletDB(*dbw
).EraseWatchOnly(dest
))
367 bool CWallet::LoadWatchOnly(const CScript
&dest
)
369 return CCryptoKeyStore::AddWatchOnly(dest
);
372 bool CWallet::Unlock(const SecureString
& strWalletPassphrase
)
375 CKeyingMaterial _vMasterKey
;
379 for (const MasterKeyMap::value_type
& pMasterKey
: mapMasterKeys
)
381 if(!crypter
.SetKeyFromPassphrase(strWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
))
383 if (!crypter
.Decrypt(pMasterKey
.second
.vchCryptedKey
, _vMasterKey
))
384 continue; // try another master key
385 if (CCryptoKeyStore::Unlock(_vMasterKey
))
392 bool CWallet::ChangeWalletPassphrase(const SecureString
& strOldWalletPassphrase
, const SecureString
& strNewWalletPassphrase
)
394 bool fWasLocked
= IsLocked();
401 CKeyingMaterial _vMasterKey
;
402 for (MasterKeyMap::value_type
& pMasterKey
: mapMasterKeys
)
404 if(!crypter
.SetKeyFromPassphrase(strOldWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
))
406 if (!crypter
.Decrypt(pMasterKey
.second
.vchCryptedKey
, _vMasterKey
))
408 if (CCryptoKeyStore::Unlock(_vMasterKey
))
410 int64_t nStartTime
= GetTimeMillis();
411 crypter
.SetKeyFromPassphrase(strNewWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
);
412 pMasterKey
.second
.nDeriveIterations
= pMasterKey
.second
.nDeriveIterations
* (100 / ((double)(GetTimeMillis() - nStartTime
)));
414 nStartTime
= GetTimeMillis();
415 crypter
.SetKeyFromPassphrase(strNewWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
);
416 pMasterKey
.second
.nDeriveIterations
= (pMasterKey
.second
.nDeriveIterations
+ pMasterKey
.second
.nDeriveIterations
* 100 / ((double)(GetTimeMillis() - nStartTime
))) / 2;
418 if (pMasterKey
.second
.nDeriveIterations
< 25000)
419 pMasterKey
.second
.nDeriveIterations
= 25000;
421 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey
.second
.nDeriveIterations
);
423 if (!crypter
.SetKeyFromPassphrase(strNewWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
))
425 if (!crypter
.Encrypt(_vMasterKey
, pMasterKey
.second
.vchCryptedKey
))
427 CWalletDB(*dbw
).WriteMasterKey(pMasterKey
.first
, pMasterKey
.second
);
438 void CWallet::SetBestChain(const CBlockLocator
& loc
)
440 CWalletDB
walletdb(*dbw
);
441 walletdb
.WriteBestBlock(loc
);
444 bool CWallet::SetMinVersion(enum WalletFeature nVersion
, CWalletDB
* pwalletdbIn
, bool fExplicit
)
446 LOCK(cs_wallet
); // nWalletVersion
447 if (nWalletVersion
>= nVersion
)
450 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
451 if (fExplicit
&& nVersion
> nWalletMaxVersion
)
452 nVersion
= FEATURE_LATEST
;
454 nWalletVersion
= nVersion
;
456 if (nVersion
> nWalletMaxVersion
)
457 nWalletMaxVersion
= nVersion
;
460 CWalletDB
* pwalletdb
= pwalletdbIn
? pwalletdbIn
: new CWalletDB(*dbw
);
461 if (nWalletVersion
> 40000)
462 pwalletdb
->WriteMinVersion(nWalletVersion
);
470 bool CWallet::SetMaxVersion(int nVersion
)
472 LOCK(cs_wallet
); // nWalletVersion, nWalletMaxVersion
473 // cannot downgrade below current version
474 if (nWalletVersion
> nVersion
)
477 nWalletMaxVersion
= nVersion
;
482 std::set
<uint256
> CWallet::GetConflicts(const uint256
& txid
) const
484 std::set
<uint256
> result
;
485 AssertLockHeld(cs_wallet
);
487 std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.find(txid
);
488 if (it
== mapWallet
.end())
490 const CWalletTx
& wtx
= it
->second
;
492 std::pair
<TxSpends::const_iterator
, TxSpends::const_iterator
> range
;
494 for (const CTxIn
& txin
: wtx
.tx
->vin
)
496 if (mapTxSpends
.count(txin
.prevout
) <= 1)
497 continue; // No conflict if zero or one spends
498 range
= mapTxSpends
.equal_range(txin
.prevout
);
499 for (TxSpends::const_iterator _it
= range
.first
; _it
!= range
.second
; ++_it
)
500 result
.insert(_it
->second
);
505 bool CWallet::HasWalletSpend(const uint256
& txid
) const
507 AssertLockHeld(cs_wallet
);
508 auto iter
= mapTxSpends
.lower_bound(COutPoint(txid
, 0));
509 return (iter
!= mapTxSpends
.end() && iter
->first
.hash
== txid
);
512 void CWallet::Flush(bool shutdown
)
514 dbw
->Flush(shutdown
);
517 void CWallet::SyncMetaData(std::pair
<TxSpends::iterator
, TxSpends::iterator
> range
)
519 // We want all the wallet transactions in range to have the same metadata as
520 // the oldest (smallest nOrderPos).
521 // So: find smallest nOrderPos:
523 int nMinOrderPos
= std::numeric_limits
<int>::max();
524 const CWalletTx
* copyFrom
= nullptr;
525 for (TxSpends::iterator it
= range
.first
; it
!= range
.second
; ++it
)
527 const uint256
& hash
= it
->second
;
528 int n
= mapWallet
[hash
].nOrderPos
;
529 if (n
< nMinOrderPos
)
532 copyFrom
= &mapWallet
[hash
];
535 // Now copy data from copyFrom to rest:
536 for (TxSpends::iterator it
= range
.first
; it
!= range
.second
; ++it
)
538 const uint256
& hash
= it
->second
;
539 CWalletTx
* copyTo
= &mapWallet
[hash
];
540 if (copyFrom
== copyTo
) continue;
541 assert(copyFrom
&& "Oldest wallet transaction in range assumed to have been found.");
542 if (!copyFrom
->IsEquivalentTo(*copyTo
)) continue;
543 copyTo
->mapValue
= copyFrom
->mapValue
;
544 copyTo
->vOrderForm
= copyFrom
->vOrderForm
;
545 // fTimeReceivedIsTxTime not copied on purpose
546 // nTimeReceived not copied on purpose
547 copyTo
->nTimeSmart
= copyFrom
->nTimeSmart
;
548 copyTo
->fFromMe
= copyFrom
->fFromMe
;
549 copyTo
->strFromAccount
= copyFrom
->strFromAccount
;
550 // nOrderPos not copied on purpose
551 // cached members not copied on purpose
556 * Outpoint is spent if any non-conflicted transaction
559 bool CWallet::IsSpent(const uint256
& hash
, unsigned int n
) const
561 const COutPoint
outpoint(hash
, n
);
562 std::pair
<TxSpends::const_iterator
, TxSpends::const_iterator
> range
;
563 range
= mapTxSpends
.equal_range(outpoint
);
565 for (TxSpends::const_iterator it
= range
.first
; it
!= range
.second
; ++it
)
567 const uint256
& wtxid
= it
->second
;
568 std::map
<uint256
, CWalletTx
>::const_iterator mit
= mapWallet
.find(wtxid
);
569 if (mit
!= mapWallet
.end()) {
570 int depth
= mit
->second
.GetDepthInMainChain();
571 if (depth
> 0 || (depth
== 0 && !mit
->second
.isAbandoned()))
572 return true; // Spent
578 void CWallet::AddToSpends(const COutPoint
& outpoint
, const uint256
& wtxid
)
580 mapTxSpends
.insert(std::make_pair(outpoint
, wtxid
));
582 std::pair
<TxSpends::iterator
, TxSpends::iterator
> range
;
583 range
= mapTxSpends
.equal_range(outpoint
);
588 void CWallet::AddToSpends(const uint256
& wtxid
)
590 auto it
= mapWallet
.find(wtxid
);
591 assert(it
!= mapWallet
.end());
592 CWalletTx
& thisTx
= it
->second
;
593 if (thisTx
.IsCoinBase()) // Coinbases don't spend anything!
596 for (const CTxIn
& txin
: thisTx
.tx
->vin
)
597 AddToSpends(txin
.prevout
, wtxid
);
600 bool CWallet::EncryptWallet(const SecureString
& strWalletPassphrase
)
605 CKeyingMaterial _vMasterKey
;
607 _vMasterKey
.resize(WALLET_CRYPTO_KEY_SIZE
);
608 GetStrongRandBytes(&_vMasterKey
[0], WALLET_CRYPTO_KEY_SIZE
);
610 CMasterKey kMasterKey
;
612 kMasterKey
.vchSalt
.resize(WALLET_CRYPTO_SALT_SIZE
);
613 GetStrongRandBytes(&kMasterKey
.vchSalt
[0], WALLET_CRYPTO_SALT_SIZE
);
616 int64_t nStartTime
= GetTimeMillis();
617 crypter
.SetKeyFromPassphrase(strWalletPassphrase
, kMasterKey
.vchSalt
, 25000, kMasterKey
.nDerivationMethod
);
618 kMasterKey
.nDeriveIterations
= 2500000 / ((double)(GetTimeMillis() - nStartTime
));
620 nStartTime
= GetTimeMillis();
621 crypter
.SetKeyFromPassphrase(strWalletPassphrase
, kMasterKey
.vchSalt
, kMasterKey
.nDeriveIterations
, kMasterKey
.nDerivationMethod
);
622 kMasterKey
.nDeriveIterations
= (kMasterKey
.nDeriveIterations
+ kMasterKey
.nDeriveIterations
* 100 / ((double)(GetTimeMillis() - nStartTime
))) / 2;
624 if (kMasterKey
.nDeriveIterations
< 25000)
625 kMasterKey
.nDeriveIterations
= 25000;
627 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey
.nDeriveIterations
);
629 if (!crypter
.SetKeyFromPassphrase(strWalletPassphrase
, kMasterKey
.vchSalt
, kMasterKey
.nDeriveIterations
, kMasterKey
.nDerivationMethod
))
631 if (!crypter
.Encrypt(_vMasterKey
, kMasterKey
.vchCryptedKey
))
636 mapMasterKeys
[++nMasterKeyMaxID
] = kMasterKey
;
637 assert(!pwalletdbEncryption
);
638 pwalletdbEncryption
= new CWalletDB(*dbw
);
639 if (!pwalletdbEncryption
->TxnBegin()) {
640 delete pwalletdbEncryption
;
641 pwalletdbEncryption
= nullptr;
644 pwalletdbEncryption
->WriteMasterKey(nMasterKeyMaxID
, kMasterKey
);
646 if (!EncryptKeys(_vMasterKey
))
648 pwalletdbEncryption
->TxnAbort();
649 delete pwalletdbEncryption
;
650 // We now probably have half of our keys encrypted in memory, and half not...
651 // die and let the user reload the unencrypted wallet.
655 // Encryption was introduced in version 0.4.0
656 SetMinVersion(FEATURE_WALLETCRYPT
, pwalletdbEncryption
, true);
658 if (!pwalletdbEncryption
->TxnCommit()) {
659 delete pwalletdbEncryption
;
660 // We now have keys encrypted in memory, but not on disk...
661 // die to avoid confusion and let the user reload the unencrypted wallet.
665 delete pwalletdbEncryption
;
666 pwalletdbEncryption
= nullptr;
669 Unlock(strWalletPassphrase
);
671 // if we are using HD, replace the HD master key (seed) with a new one
673 if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
681 // Need to completely rewrite the wallet file; if we don't, bdb might keep
682 // bits of the unencrypted private key in slack space in the database file.
686 NotifyStatusChanged(this);
691 DBErrors
CWallet::ReorderTransactions()
694 CWalletDB
walletdb(*dbw
);
696 // Old wallets didn't have any defined order for transactions
697 // Probably a bad idea to change the output of this
699 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
700 typedef std::pair
<CWalletTx
*, CAccountingEntry
*> TxPair
;
701 typedef std::multimap
<int64_t, TxPair
> TxItems
;
704 for (std::map
<uint256
, CWalletTx
>::iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
706 CWalletTx
* wtx
= &((*it
).second
);
707 txByTime
.insert(std::make_pair(wtx
->nTimeReceived
, TxPair(wtx
, nullptr)));
709 std::list
<CAccountingEntry
> acentries
;
710 walletdb
.ListAccountCreditDebit("", acentries
);
711 for (CAccountingEntry
& entry
: acentries
)
713 txByTime
.insert(std::make_pair(entry
.nTime
, TxPair(nullptr, &entry
)));
717 std::vector
<int64_t> nOrderPosOffsets
;
718 for (TxItems::iterator it
= txByTime
.begin(); it
!= txByTime
.end(); ++it
)
720 CWalletTx
*const pwtx
= (*it
).second
.first
;
721 CAccountingEntry
*const pacentry
= (*it
).second
.second
;
722 int64_t& nOrderPos
= (pwtx
!= nullptr) ? pwtx
->nOrderPos
: pacentry
->nOrderPos
;
726 nOrderPos
= nOrderPosNext
++;
727 nOrderPosOffsets
.push_back(nOrderPos
);
731 if (!walletdb
.WriteTx(*pwtx
))
735 if (!walletdb
.WriteAccountingEntry(pacentry
->nEntryNo
, *pacentry
))
740 int64_t nOrderPosOff
= 0;
741 for (const int64_t& nOffsetStart
: nOrderPosOffsets
)
743 if (nOrderPos
>= nOffsetStart
)
746 nOrderPos
+= nOrderPosOff
;
747 nOrderPosNext
= std::max(nOrderPosNext
, nOrderPos
+ 1);
752 // Since we're changing the order, write it back
755 if (!walletdb
.WriteTx(*pwtx
))
759 if (!walletdb
.WriteAccountingEntry(pacentry
->nEntryNo
, *pacentry
))
763 walletdb
.WriteOrderPosNext(nOrderPosNext
);
768 int64_t CWallet::IncOrderPosNext(CWalletDB
*pwalletdb
)
770 AssertLockHeld(cs_wallet
); // nOrderPosNext
771 int64_t nRet
= nOrderPosNext
++;
773 pwalletdb
->WriteOrderPosNext(nOrderPosNext
);
775 CWalletDB(*dbw
).WriteOrderPosNext(nOrderPosNext
);
780 bool CWallet::AccountMove(std::string strFrom
, std::string strTo
, CAmount nAmount
, std::string strComment
)
782 CWalletDB
walletdb(*dbw
);
783 if (!walletdb
.TxnBegin())
786 int64_t nNow
= GetAdjustedTime();
789 CAccountingEntry debit
;
790 debit
.nOrderPos
= IncOrderPosNext(&walletdb
);
791 debit
.strAccount
= strFrom
;
792 debit
.nCreditDebit
= -nAmount
;
794 debit
.strOtherAccount
= strTo
;
795 debit
.strComment
= strComment
;
796 AddAccountingEntry(debit
, &walletdb
);
799 CAccountingEntry credit
;
800 credit
.nOrderPos
= IncOrderPosNext(&walletdb
);
801 credit
.strAccount
= strTo
;
802 credit
.nCreditDebit
= nAmount
;
804 credit
.strOtherAccount
= strFrom
;
805 credit
.strComment
= strComment
;
806 AddAccountingEntry(credit
, &walletdb
);
808 if (!walletdb
.TxnCommit())
814 bool CWallet::GetAccountPubkey(CPubKey
&pubKey
, std::string strAccount
, bool bForceNew
)
816 CWalletDB
walletdb(*dbw
);
819 walletdb
.ReadAccount(strAccount
, account
);
822 if (!account
.vchPubKey
.IsValid())
825 // Check if the current key has been used
826 CScript scriptPubKey
= GetScriptForDestination(account
.vchPubKey
.GetID());
827 for (std::map
<uint256
, CWalletTx
>::iterator it
= mapWallet
.begin();
828 it
!= mapWallet
.end() && account
.vchPubKey
.IsValid();
830 for (const CTxOut
& txout
: (*it
).second
.tx
->vout
)
831 if (txout
.scriptPubKey
== scriptPubKey
) {
838 // Generate a new key
840 if (!GetKeyFromPool(account
.vchPubKey
, false))
843 SetAddressBook(account
.vchPubKey
.GetID(), strAccount
, "receive");
844 walletdb
.WriteAccount(strAccount
, account
);
847 pubKey
= account
.vchPubKey
;
852 void CWallet::MarkDirty()
856 for (std::pair
<const uint256
, CWalletTx
>& item
: mapWallet
)
857 item
.second
.MarkDirty();
861 bool CWallet::MarkReplaced(const uint256
& originalHash
, const uint256
& newHash
)
865 auto mi
= mapWallet
.find(originalHash
);
867 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
868 assert(mi
!= mapWallet
.end());
870 CWalletTx
& wtx
= (*mi
).second
;
872 // Ensure for now that we're not overwriting data
873 assert(wtx
.mapValue
.count("replaced_by_txid") == 0);
875 wtx
.mapValue
["replaced_by_txid"] = newHash
.ToString();
877 CWalletDB
walletdb(*dbw
, "r+");
880 if (!walletdb
.WriteTx(wtx
)) {
881 LogPrintf("%s: Updating walletdb tx %s failed", __func__
, wtx
.GetHash().ToString());
885 NotifyTransactionChanged(this, originalHash
, CT_UPDATED
);
890 bool CWallet::AddToWallet(const CWalletTx
& wtxIn
, bool fFlushOnClose
)
894 CWalletDB
walletdb(*dbw
, "r+", fFlushOnClose
);
896 uint256 hash
= wtxIn
.GetHash();
898 // Inserts only if not already there, returns tx inserted or tx found
899 std::pair
<std::map
<uint256
, CWalletTx
>::iterator
, bool> ret
= mapWallet
.insert(std::make_pair(hash
, wtxIn
));
900 CWalletTx
& wtx
= (*ret
.first
).second
;
901 wtx
.BindWallet(this);
902 bool fInsertedNew
= ret
.second
;
905 wtx
.nTimeReceived
= GetAdjustedTime();
906 wtx
.nOrderPos
= IncOrderPosNext(&walletdb
);
907 wtxOrdered
.insert(std::make_pair(wtx
.nOrderPos
, TxPair(&wtx
, nullptr)));
908 wtx
.nTimeSmart
= ComputeTimeSmart(wtx
);
912 bool fUpdated
= false;
916 if (!wtxIn
.hashUnset() && wtxIn
.hashBlock
!= wtx
.hashBlock
)
918 wtx
.hashBlock
= wtxIn
.hashBlock
;
921 // If no longer abandoned, update
922 if (wtxIn
.hashBlock
.IsNull() && wtx
.isAbandoned())
924 wtx
.hashBlock
= wtxIn
.hashBlock
;
927 if (wtxIn
.nIndex
!= -1 && (wtxIn
.nIndex
!= wtx
.nIndex
))
929 wtx
.nIndex
= wtxIn
.nIndex
;
932 if (wtxIn
.fFromMe
&& wtxIn
.fFromMe
!= wtx
.fFromMe
)
934 wtx
.fFromMe
= wtxIn
.fFromMe
;
937 // If we have a witness-stripped version of this transaction, and we
938 // see a new version with a witness, then we must be upgrading a pre-segwit
939 // wallet. Store the new version of the transaction with the witness,
940 // as the stripped-version must be invalid.
941 // TODO: Store all versions of the transaction, instead of just one.
942 if (wtxIn
.tx
->HasWitness() && !wtx
.tx
->HasWitness()) {
949 LogPrintf("AddToWallet %s %s%s\n", wtxIn
.GetHash().ToString(), (fInsertedNew
? "new" : ""), (fUpdated
? "update" : ""));
952 if (fInsertedNew
|| fUpdated
)
953 if (!walletdb
.WriteTx(wtx
))
956 // Break debit/credit balance caches:
959 // Notify UI of new or updated transaction
960 NotifyTransactionChanged(this, hash
, fInsertedNew
? CT_NEW
: CT_UPDATED
);
962 // notify an external script when a wallet transaction comes in or is updated
963 std::string strCmd
= gArgs
.GetArg("-walletnotify", "");
965 if ( !strCmd
.empty())
967 boost::replace_all(strCmd
, "%s", wtxIn
.GetHash().GetHex());
968 boost::thread
t(runCommand
, strCmd
); // thread runs free
974 bool CWallet::LoadToWallet(const CWalletTx
& wtxIn
)
976 uint256 hash
= wtxIn
.GetHash();
978 mapWallet
[hash
] = wtxIn
;
979 CWalletTx
& wtx
= mapWallet
[hash
];
980 wtx
.BindWallet(this);
981 wtxOrdered
.insert(std::make_pair(wtx
.nOrderPos
, TxPair(&wtx
, nullptr)));
983 for (const CTxIn
& txin
: wtx
.tx
->vin
) {
984 auto it
= mapWallet
.find(txin
.prevout
.hash
);
985 if (it
!= mapWallet
.end()) {
986 CWalletTx
& prevtx
= it
->second
;
987 if (prevtx
.nIndex
== -1 && !prevtx
.hashUnset()) {
988 MarkConflicted(prevtx
.hashBlock
, wtx
.GetHash());
997 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
998 * be set when the transaction was known to be included in a block. When
999 * pIndex == nullptr, then wallet state is not updated in AddToWallet, but
1000 * notifications happen and cached balances are marked dirty.
1002 * If fUpdate is true, existing transactions will be updated.
1003 * TODO: One exception to this is that the abandoned state is cleared under the
1004 * assumption that any further notification of a transaction that was considered
1005 * abandoned is an indication that it is not safe to be considered abandoned.
1006 * Abandoned state should probably be more carefully tracked via different
1007 * posInBlock signals or by checking mempool presence when necessary.
1009 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef
& ptx
, const CBlockIndex
* pIndex
, int posInBlock
, bool fUpdate
)
1011 const CTransaction
& tx
= *ptx
;
1013 AssertLockHeld(cs_wallet
);
1015 if (pIndex
!= nullptr) {
1016 for (const CTxIn
& txin
: tx
.vin
) {
1017 std::pair
<TxSpends::const_iterator
, TxSpends::const_iterator
> range
= mapTxSpends
.equal_range(txin
.prevout
);
1018 while (range
.first
!= range
.second
) {
1019 if (range
.first
->second
!= tx
.GetHash()) {
1020 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
);
1021 MarkConflicted(pIndex
->GetBlockHash(), range
.first
->second
);
1028 bool fExisted
= mapWallet
.count(tx
.GetHash()) != 0;
1029 if (fExisted
&& !fUpdate
) return false;
1030 if (fExisted
|| IsMine(tx
) || IsFromMe(tx
))
1032 /* Check if any keys in the wallet keypool that were supposed to be unused
1033 * have appeared in a new transaction. If so, remove those keys from the keypool.
1034 * This can happen when restoring an old wallet backup that does not contain
1035 * the mostly recently created transactions from newer versions of the wallet.
1038 // loop though all outputs
1039 for (const CTxOut
& txout
: tx
.vout
) {
1040 // extract addresses and check if they match with an unused keypool key
1041 std::vector
<CKeyID
> vAffected
;
1042 CAffectedKeysVisitor(*this, vAffected
).Process(txout
.scriptPubKey
);
1043 for (const CKeyID
&keyid
: vAffected
) {
1044 std::map
<CKeyID
, int64_t>::const_iterator mi
= m_pool_key_to_index
.find(keyid
);
1045 if (mi
!= m_pool_key_to_index
.end()) {
1046 LogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__
);
1047 MarkReserveKeysAsUsed(mi
->second
);
1049 if (!TopUpKeyPool()) {
1050 LogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__
);
1056 CWalletTx
wtx(this, ptx
);
1058 // Get merkle branch if transaction was found in a block
1059 if (pIndex
!= nullptr)
1060 wtx
.SetMerkleBranch(pIndex
, posInBlock
);
1062 return AddToWallet(wtx
, false);
1068 bool CWallet::TransactionCanBeAbandoned(const uint256
& hashTx
) const
1070 LOCK2(cs_main
, cs_wallet
);
1071 const CWalletTx
* wtx
= GetWalletTx(hashTx
);
1072 return wtx
&& !wtx
->isAbandoned() && wtx
->GetDepthInMainChain() <= 0 && !wtx
->InMempool();
1075 bool CWallet::AbandonTransaction(const uint256
& hashTx
)
1077 LOCK2(cs_main
, cs_wallet
);
1079 CWalletDB
walletdb(*dbw
, "r+");
1081 std::set
<uint256
> todo
;
1082 std::set
<uint256
> done
;
1084 // Can't mark abandoned if confirmed or in mempool
1085 auto it
= mapWallet
.find(hashTx
);
1086 assert(it
!= mapWallet
.end());
1087 CWalletTx
& origtx
= it
->second
;
1088 if (origtx
.GetDepthInMainChain() > 0 || origtx
.InMempool()) {
1092 todo
.insert(hashTx
);
1094 while (!todo
.empty()) {
1095 uint256 now
= *todo
.begin();
1098 auto it
= mapWallet
.find(now
);
1099 assert(it
!= mapWallet
.end());
1100 CWalletTx
& wtx
= it
->second
;
1101 int currentconfirm
= wtx
.GetDepthInMainChain();
1102 // If the orig tx was not in block, none of its spends can be
1103 assert(currentconfirm
<= 0);
1104 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1105 if (currentconfirm
== 0 && !wtx
.isAbandoned()) {
1106 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1107 assert(!wtx
.InMempool());
1111 walletdb
.WriteTx(wtx
);
1112 NotifyTransactionChanged(this, wtx
.GetHash(), CT_UPDATED
);
1113 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1114 TxSpends::const_iterator iter
= mapTxSpends
.lower_bound(COutPoint(hashTx
, 0));
1115 while (iter
!= mapTxSpends
.end() && iter
->first
.hash
== now
) {
1116 if (!done
.count(iter
->second
)) {
1117 todo
.insert(iter
->second
);
1121 // If a transaction changes 'conflicted' state, that changes the balance
1122 // available of the outputs it spends. So force those to be recomputed
1123 for (const CTxIn
& txin
: wtx
.tx
->vin
)
1125 auto it
= mapWallet
.find(txin
.prevout
.hash
);
1126 if (it
!= mapWallet
.end()) {
1127 it
->second
.MarkDirty();
1136 void CWallet::MarkConflicted(const uint256
& hashBlock
, const uint256
& hashTx
)
1138 LOCK2(cs_main
, cs_wallet
);
1140 int conflictconfirms
= 0;
1141 if (mapBlockIndex
.count(hashBlock
)) {
1142 CBlockIndex
* pindex
= mapBlockIndex
[hashBlock
];
1143 if (chainActive
.Contains(pindex
)) {
1144 conflictconfirms
= -(chainActive
.Height() - pindex
->nHeight
+ 1);
1147 // If number of conflict confirms cannot be determined, this means
1148 // that the block is still unknown or not yet part of the main chain,
1149 // for example when loading the wallet during a reindex. Do nothing in that
1151 if (conflictconfirms
>= 0)
1154 // Do not flush the wallet here for performance reasons
1155 CWalletDB
walletdb(*dbw
, "r+", false);
1157 std::set
<uint256
> todo
;
1158 std::set
<uint256
> done
;
1160 todo
.insert(hashTx
);
1162 while (!todo
.empty()) {
1163 uint256 now
= *todo
.begin();
1166 auto it
= mapWallet
.find(now
);
1167 assert(it
!= mapWallet
.end());
1168 CWalletTx
& wtx
= it
->second
;
1169 int currentconfirm
= wtx
.GetDepthInMainChain();
1170 if (conflictconfirms
< currentconfirm
) {
1171 // Block is 'more conflicted' than current confirm; update.
1172 // Mark transaction as conflicted with this block.
1174 wtx
.hashBlock
= hashBlock
;
1176 walletdb
.WriteTx(wtx
);
1177 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1178 TxSpends::const_iterator iter
= mapTxSpends
.lower_bound(COutPoint(now
, 0));
1179 while (iter
!= mapTxSpends
.end() && iter
->first
.hash
== now
) {
1180 if (!done
.count(iter
->second
)) {
1181 todo
.insert(iter
->second
);
1185 // If a transaction changes 'conflicted' state, that changes the balance
1186 // available of the outputs it spends. So force those to be recomputed
1187 for (const CTxIn
& txin
: wtx
.tx
->vin
) {
1188 auto it
= mapWallet
.find(txin
.prevout
.hash
);
1189 if (it
!= mapWallet
.end()) {
1190 it
->second
.MarkDirty();
1197 void CWallet::SyncTransaction(const CTransactionRef
& ptx
, const CBlockIndex
*pindex
, int posInBlock
) {
1198 const CTransaction
& tx
= *ptx
;
1200 if (!AddToWalletIfInvolvingMe(ptx
, pindex
, posInBlock
, true))
1201 return; // Not one of ours
1203 // If a transaction changes 'conflicted' state, that changes the balance
1204 // available of the outputs it spends. So force those to be
1205 // recomputed, also:
1206 for (const CTxIn
& txin
: tx
.vin
) {
1207 auto it
= mapWallet
.find(txin
.prevout
.hash
);
1208 if (it
!= mapWallet
.end()) {
1209 it
->second
.MarkDirty();
1214 void CWallet::TransactionAddedToMempool(const CTransactionRef
& ptx
) {
1215 LOCK2(cs_main
, cs_wallet
);
1216 SyncTransaction(ptx
);
1219 void CWallet::BlockConnected(const std::shared_ptr
<const CBlock
>& pblock
, const CBlockIndex
*pindex
, const std::vector
<CTransactionRef
>& vtxConflicted
) {
1220 LOCK2(cs_main
, cs_wallet
);
1221 // TODO: Temporarily ensure that mempool removals are notified before
1222 // connected transactions. This shouldn't matter, but the abandoned
1223 // state of transactions in our wallet is currently cleared when we
1224 // receive another notification and there is a race condition where
1225 // notification of a connected conflict might cause an outside process
1226 // to abandon a transaction and then have it inadvertently cleared by
1227 // the notification that the conflicted transaction was evicted.
1229 for (const CTransactionRef
& ptx
: vtxConflicted
) {
1230 SyncTransaction(ptx
);
1232 for (size_t i
= 0; i
< pblock
->vtx
.size(); i
++) {
1233 SyncTransaction(pblock
->vtx
[i
], pindex
, i
);
1237 void CWallet::BlockDisconnected(const std::shared_ptr
<const CBlock
>& pblock
) {
1238 LOCK2(cs_main
, cs_wallet
);
1240 for (const CTransactionRef
& ptx
: pblock
->vtx
) {
1241 SyncTransaction(ptx
);
1247 isminetype
CWallet::IsMine(const CTxIn
&txin
) const
1251 std::map
<uint256
, CWalletTx
>::const_iterator mi
= mapWallet
.find(txin
.prevout
.hash
);
1252 if (mi
!= mapWallet
.end())
1254 const CWalletTx
& prev
= (*mi
).second
;
1255 if (txin
.prevout
.n
< prev
.tx
->vout
.size())
1256 return IsMine(prev
.tx
->vout
[txin
.prevout
.n
]);
1262 // Note that this function doesn't distinguish between a 0-valued input,
1263 // and a not-"is mine" (according to the filter) input.
1264 CAmount
CWallet::GetDebit(const CTxIn
&txin
, const isminefilter
& filter
) const
1268 std::map
<uint256
, CWalletTx
>::const_iterator mi
= mapWallet
.find(txin
.prevout
.hash
);
1269 if (mi
!= mapWallet
.end())
1271 const CWalletTx
& prev
= (*mi
).second
;
1272 if (txin
.prevout
.n
< prev
.tx
->vout
.size())
1273 if (IsMine(prev
.tx
->vout
[txin
.prevout
.n
]) & filter
)
1274 return prev
.tx
->vout
[txin
.prevout
.n
].nValue
;
1280 isminetype
CWallet::IsMine(const CTxOut
& txout
) const
1282 return ::IsMine(*this, txout
.scriptPubKey
);
1285 CAmount
CWallet::GetCredit(const CTxOut
& txout
, const isminefilter
& filter
) const
1287 if (!MoneyRange(txout
.nValue
))
1288 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1289 return ((IsMine(txout
) & filter
) ? txout
.nValue
: 0);
1292 bool CWallet::IsChange(const CTxOut
& txout
) const
1294 // TODO: fix handling of 'change' outputs. The assumption is that any
1295 // payment to a script that is ours, but is not in the address book
1296 // is change. That assumption is likely to break when we implement multisignature
1297 // wallets that return change back into a multi-signature-protected address;
1298 // a better way of identifying which outputs are 'the send' and which are
1299 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1300 // which output, if any, was change).
1301 if (::IsMine(*this, txout
.scriptPubKey
))
1303 CTxDestination address
;
1304 if (!ExtractDestination(txout
.scriptPubKey
, address
))
1308 if (!mapAddressBook
.count(address
))
1314 CAmount
CWallet::GetChange(const CTxOut
& txout
) const
1316 if (!MoneyRange(txout
.nValue
))
1317 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1318 return (IsChange(txout
) ? txout
.nValue
: 0);
1321 bool CWallet::IsMine(const CTransaction
& tx
) const
1323 for (const CTxOut
& txout
: tx
.vout
)
1329 bool CWallet::IsFromMe(const CTransaction
& tx
) const
1331 return (GetDebit(tx
, ISMINE_ALL
) > 0);
1334 CAmount
CWallet::GetDebit(const CTransaction
& tx
, const isminefilter
& filter
) const
1337 for (const CTxIn
& txin
: tx
.vin
)
1339 nDebit
+= GetDebit(txin
, filter
);
1340 if (!MoneyRange(nDebit
))
1341 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1346 bool CWallet::IsAllFromMe(const CTransaction
& tx
, const isminefilter
& filter
) const
1350 for (const CTxIn
& txin
: tx
.vin
)
1352 auto mi
= mapWallet
.find(txin
.prevout
.hash
);
1353 if (mi
== mapWallet
.end())
1354 return false; // any unknown inputs can't be from us
1356 const CWalletTx
& prev
= (*mi
).second
;
1358 if (txin
.prevout
.n
>= prev
.tx
->vout
.size())
1359 return false; // invalid input!
1361 if (!(IsMine(prev
.tx
->vout
[txin
.prevout
.n
]) & filter
))
1367 CAmount
CWallet::GetCredit(const CTransaction
& tx
, const isminefilter
& filter
) const
1369 CAmount nCredit
= 0;
1370 for (const CTxOut
& txout
: tx
.vout
)
1372 nCredit
+= GetCredit(txout
, filter
);
1373 if (!MoneyRange(nCredit
))
1374 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1379 CAmount
CWallet::GetChange(const CTransaction
& tx
) const
1381 CAmount nChange
= 0;
1382 for (const CTxOut
& txout
: tx
.vout
)
1384 nChange
+= GetChange(txout
);
1385 if (!MoneyRange(nChange
))
1386 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1391 CPubKey
CWallet::GenerateNewHDMasterKey()
1394 key
.MakeNewKey(true);
1396 int64_t nCreationTime
= GetTime();
1397 CKeyMetadata
metadata(nCreationTime
);
1399 // calculate the pubkey
1400 CPubKey pubkey
= key
.GetPubKey();
1401 assert(key
.VerifyPubKey(pubkey
));
1403 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1404 metadata
.hdKeypath
= "m";
1405 metadata
.hdMasterKeyID
= pubkey
.GetID();
1410 // mem store the metadata
1411 mapKeyMetadata
[pubkey
.GetID()] = metadata
;
1413 // write the key&metadata to the database
1414 if (!AddKeyPubKey(key
, pubkey
))
1415 throw std::runtime_error(std::string(__func__
) + ": AddKeyPubKey failed");
1421 bool CWallet::SetHDMasterKey(const CPubKey
& pubkey
)
1424 // store the keyid (hash160) together with
1425 // the child index counter in the database
1426 // as a hdchain object
1427 CHDChain newHdChain
;
1428 newHdChain
.nVersion
= CanSupportFeature(FEATURE_HD_SPLIT
) ? CHDChain::VERSION_HD_CHAIN_SPLIT
: CHDChain::VERSION_HD_BASE
;
1429 newHdChain
.masterKeyID
= pubkey
.GetID();
1430 SetHDChain(newHdChain
, false);
1435 bool CWallet::SetHDChain(const CHDChain
& chain
, bool memonly
)
1438 if (!memonly
&& !CWalletDB(*dbw
).WriteHDChain(chain
))
1439 throw std::runtime_error(std::string(__func__
) + ": writing chain failed");
1445 bool CWallet::IsHDEnabled() const
1447 return !hdChain
.masterKeyID
.IsNull();
1450 int64_t CWalletTx::GetTxTime() const
1452 int64_t n
= nTimeSmart
;
1453 return n
? n
: nTimeReceived
;
1456 int CWalletTx::GetRequestCount() const
1458 // Returns -1 if it wasn't being tracked
1461 LOCK(pwallet
->cs_wallet
);
1467 std::map
<uint256
, int>::const_iterator mi
= pwallet
->mapRequestCount
.find(hashBlock
);
1468 if (mi
!= pwallet
->mapRequestCount
.end())
1469 nRequests
= (*mi
).second
;
1474 // Did anyone request this transaction?
1475 std::map
<uint256
, int>::const_iterator mi
= pwallet
->mapRequestCount
.find(GetHash());
1476 if (mi
!= pwallet
->mapRequestCount
.end())
1478 nRequests
= (*mi
).second
;
1480 // How about the block it's in?
1481 if (nRequests
== 0 && !hashUnset())
1483 std::map
<uint256
, int>::const_iterator _mi
= pwallet
->mapRequestCount
.find(hashBlock
);
1484 if (_mi
!= pwallet
->mapRequestCount
.end())
1485 nRequests
= (*_mi
).second
;
1487 nRequests
= 1; // If it's in someone else's block it must have got out
1495 void CWalletTx::GetAmounts(std::list
<COutputEntry
>& listReceived
,
1496 std::list
<COutputEntry
>& listSent
, CAmount
& nFee
, std::string
& strSentAccount
, const isminefilter
& filter
) const
1499 listReceived
.clear();
1501 strSentAccount
= strFromAccount
;
1504 CAmount nDebit
= GetDebit(filter
);
1505 if (nDebit
> 0) // debit>0 means we signed/sent this transaction
1507 CAmount nValueOut
= tx
->GetValueOut();
1508 nFee
= nDebit
- nValueOut
;
1512 for (unsigned int i
= 0; i
< tx
->vout
.size(); ++i
)
1514 const CTxOut
& txout
= tx
->vout
[i
];
1515 isminetype fIsMine
= pwallet
->IsMine(txout
);
1516 // Only need to handle txouts if AT LEAST one of these is true:
1517 // 1) they debit from us (sent)
1518 // 2) the output is to us (received)
1521 // Don't report 'change' txouts
1522 if (pwallet
->IsChange(txout
))
1525 else if (!(fIsMine
& filter
))
1528 // In either case, we need to get the destination address
1529 CTxDestination address
;
1531 if (!ExtractDestination(txout
.scriptPubKey
, address
) && !txout
.scriptPubKey
.IsUnspendable())
1533 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1534 this->GetHash().ToString());
1535 address
= CNoDestination();
1538 COutputEntry output
= {address
, txout
.nValue
, (int)i
};
1540 // If we are debited by the transaction, add the output as a "sent" entry
1542 listSent
.push_back(output
);
1544 // If we are receiving the output, add it as a "received" entry
1545 if (fIsMine
& filter
)
1546 listReceived
.push_back(output
);
1552 * Scan active chain for relevant transactions after importing keys. This should
1553 * be called whenever new keys are added to the wallet, with the oldest key
1556 * @return Earliest timestamp that could be successfully scanned from. Timestamp
1557 * returned will be higher than startTime if relevant blocks could not be read.
1559 int64_t CWallet::RescanFromTime(int64_t startTime
, bool update
)
1561 AssertLockHeld(cs_main
);
1562 AssertLockHeld(cs_wallet
);
1564 // Find starting block. May be null if nCreateTime is greater than the
1565 // highest blockchain timestamp, in which case there is nothing that needs
1567 CBlockIndex
* const startBlock
= chainActive
.FindEarliestAtLeast(startTime
- TIMESTAMP_WINDOW
);
1568 LogPrintf("%s: Rescanning last %i blocks\n", __func__
, startBlock
? chainActive
.Height() - startBlock
->nHeight
+ 1 : 0);
1571 const CBlockIndex
* const failedBlock
= ScanForWalletTransactions(startBlock
, update
);
1573 return failedBlock
->GetBlockTimeMax() + TIMESTAMP_WINDOW
+ 1;
1580 * Scan the block chain (starting in pindexStart) for transactions
1581 * from or to us. If fUpdate is true, found transactions that already
1582 * exist in the wallet will be updated.
1584 * Returns null if scan was successful. Otherwise, if a complete rescan was not
1585 * possible (due to pruning or corruption), returns pointer to the most recent
1586 * block that could not be scanned.
1588 CBlockIndex
* CWallet::ScanForWalletTransactions(CBlockIndex
* pindexStart
, bool fUpdate
)
1590 int64_t nNow
= GetTime();
1591 const CChainParams
& chainParams
= Params();
1593 CBlockIndex
* pindex
= pindexStart
;
1594 CBlockIndex
* ret
= nullptr;
1596 LOCK2(cs_main
, cs_wallet
);
1597 fAbortRescan
= false;
1598 fScanningWallet
= true;
1600 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1601 double dProgressStart
= GuessVerificationProgress(chainParams
.TxData(), pindex
);
1602 double dProgressTip
= GuessVerificationProgress(chainParams
.TxData(), chainActive
.Tip());
1603 while (pindex
&& !fAbortRescan
)
1605 if (pindex
->nHeight
% 100 == 0 && dProgressTip
- dProgressStart
> 0.0)
1606 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams
.TxData(), pindex
) - dProgressStart
) / (dProgressTip
- dProgressStart
) * 100))));
1607 if (GetTime() >= nNow
+ 60) {
1609 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex
->nHeight
, GuessVerificationProgress(chainParams
.TxData(), pindex
));
1613 if (ReadBlockFromDisk(block
, pindex
, Params().GetConsensus())) {
1614 for (size_t posInBlock
= 0; posInBlock
< block
.vtx
.size(); ++posInBlock
) {
1615 AddToWalletIfInvolvingMe(block
.vtx
[posInBlock
], pindex
, posInBlock
, fUpdate
);
1620 pindex
= chainActive
.Next(pindex
);
1622 if (pindex
&& fAbortRescan
) {
1623 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex
->nHeight
, GuessVerificationProgress(chainParams
.TxData(), pindex
));
1625 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1627 fScanningWallet
= false;
1632 void CWallet::ReacceptWalletTransactions()
1634 // If transactions aren't being broadcasted, don't let them into local mempool either
1635 if (!fBroadcastTransactions
)
1637 LOCK2(cs_main
, cs_wallet
);
1638 std::map
<int64_t, CWalletTx
*> mapSorted
;
1640 // Sort pending wallet transactions based on their initial wallet insertion order
1641 for (std::pair
<const uint256
, CWalletTx
>& item
: mapWallet
)
1643 const uint256
& wtxid
= item
.first
;
1644 CWalletTx
& wtx
= item
.second
;
1645 assert(wtx
.GetHash() == wtxid
);
1647 int nDepth
= wtx
.GetDepthInMainChain();
1649 if (!wtx
.IsCoinBase() && (nDepth
== 0 && !wtx
.isAbandoned())) {
1650 mapSorted
.insert(std::make_pair(wtx
.nOrderPos
, &wtx
));
1654 // Try to add wallet transactions to memory pool
1655 for (std::pair
<const int64_t, CWalletTx
*>& item
: mapSorted
)
1657 CWalletTx
& wtx
= *(item
.second
);
1660 CValidationState state
;
1661 wtx
.AcceptToMemoryPool(maxTxFee
, state
);
1665 bool CWalletTx::RelayWalletTransaction(CConnman
* connman
)
1667 assert(pwallet
->GetBroadcastTransactions());
1668 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1670 CValidationState state
;
1671 /* GetDepthInMainChain already catches known conflicts. */
1672 if (InMempool() || AcceptToMemoryPool(maxTxFee
, state
)) {
1673 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1675 CInv
inv(MSG_TX
, GetHash());
1676 connman
->ForEachNode([&inv
](CNode
* pnode
)
1678 pnode
->PushInventory(inv
);
1687 std::set
<uint256
> CWalletTx::GetConflicts() const
1689 std::set
<uint256
> result
;
1690 if (pwallet
!= nullptr)
1692 uint256 myHash
= GetHash();
1693 result
= pwallet
->GetConflicts(myHash
);
1694 result
.erase(myHash
);
1699 CAmount
CWalletTx::GetDebit(const isminefilter
& filter
) const
1701 if (tx
->vin
.empty())
1705 if(filter
& ISMINE_SPENDABLE
)
1708 debit
+= nDebitCached
;
1711 nDebitCached
= pwallet
->GetDebit(*this, ISMINE_SPENDABLE
);
1712 fDebitCached
= true;
1713 debit
+= nDebitCached
;
1716 if(filter
& ISMINE_WATCH_ONLY
)
1718 if(fWatchDebitCached
)
1719 debit
+= nWatchDebitCached
;
1722 nWatchDebitCached
= pwallet
->GetDebit(*this, ISMINE_WATCH_ONLY
);
1723 fWatchDebitCached
= true;
1724 debit
+= nWatchDebitCached
;
1730 CAmount
CWalletTx::GetCredit(const isminefilter
& filter
) const
1732 // Must wait until coinbase is safely deep enough in the chain before valuing it
1733 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1737 if (filter
& ISMINE_SPENDABLE
)
1739 // GetBalance can assume transactions in mapWallet won't change
1741 credit
+= nCreditCached
;
1744 nCreditCached
= pwallet
->GetCredit(*this, ISMINE_SPENDABLE
);
1745 fCreditCached
= true;
1746 credit
+= nCreditCached
;
1749 if (filter
& ISMINE_WATCH_ONLY
)
1751 if (fWatchCreditCached
)
1752 credit
+= nWatchCreditCached
;
1755 nWatchCreditCached
= pwallet
->GetCredit(*this, ISMINE_WATCH_ONLY
);
1756 fWatchCreditCached
= true;
1757 credit
+= nWatchCreditCached
;
1763 CAmount
CWalletTx::GetImmatureCredit(bool fUseCache
) const
1765 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1767 if (fUseCache
&& fImmatureCreditCached
)
1768 return nImmatureCreditCached
;
1769 nImmatureCreditCached
= pwallet
->GetCredit(*this, ISMINE_SPENDABLE
);
1770 fImmatureCreditCached
= true;
1771 return nImmatureCreditCached
;
1777 CAmount
CWalletTx::GetAvailableCredit(bool fUseCache
) const
1779 if (pwallet
== nullptr)
1782 // Must wait until coinbase is safely deep enough in the chain before valuing it
1783 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1786 if (fUseCache
&& fAvailableCreditCached
)
1787 return nAvailableCreditCached
;
1789 CAmount nCredit
= 0;
1790 uint256 hashTx
= GetHash();
1791 for (unsigned int i
= 0; i
< tx
->vout
.size(); i
++)
1793 if (!pwallet
->IsSpent(hashTx
, i
))
1795 const CTxOut
&txout
= tx
->vout
[i
];
1796 nCredit
+= pwallet
->GetCredit(txout
, ISMINE_SPENDABLE
);
1797 if (!MoneyRange(nCredit
))
1798 throw std::runtime_error(std::string(__func__
) + " : value out of range");
1802 nAvailableCreditCached
= nCredit
;
1803 fAvailableCreditCached
= true;
1807 CAmount
CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache
) const
1809 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1811 if (fUseCache
&& fImmatureWatchCreditCached
)
1812 return nImmatureWatchCreditCached
;
1813 nImmatureWatchCreditCached
= pwallet
->GetCredit(*this, ISMINE_WATCH_ONLY
);
1814 fImmatureWatchCreditCached
= true;
1815 return nImmatureWatchCreditCached
;
1821 CAmount
CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache
) const
1823 if (pwallet
== nullptr)
1826 // Must wait until coinbase is safely deep enough in the chain before valuing it
1827 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1830 if (fUseCache
&& fAvailableWatchCreditCached
)
1831 return nAvailableWatchCreditCached
;
1833 CAmount nCredit
= 0;
1834 for (unsigned int i
= 0; i
< tx
->vout
.size(); i
++)
1836 if (!pwallet
->IsSpent(GetHash(), i
))
1838 const CTxOut
&txout
= tx
->vout
[i
];
1839 nCredit
+= pwallet
->GetCredit(txout
, ISMINE_WATCH_ONLY
);
1840 if (!MoneyRange(nCredit
))
1841 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1845 nAvailableWatchCreditCached
= nCredit
;
1846 fAvailableWatchCreditCached
= true;
1850 CAmount
CWalletTx::GetChange() const
1853 return nChangeCached
;
1854 nChangeCached
= pwallet
->GetChange(*this);
1855 fChangeCached
= true;
1856 return nChangeCached
;
1859 bool CWalletTx::InMempool() const
1862 return mempool
.exists(GetHash());
1865 bool CWalletTx::IsTrusted() const
1867 // Quick answer in most cases
1868 if (!CheckFinalTx(*this))
1870 int nDepth
= GetDepthInMainChain();
1875 if (!bSpendZeroConfChange
|| !IsFromMe(ISMINE_ALL
)) // using wtx's cached debit
1878 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1882 // Trusted if all inputs are from us and are in the mempool:
1883 for (const CTxIn
& txin
: tx
->vin
)
1885 // Transactions not sent by us: not trusted
1886 const CWalletTx
* parent
= pwallet
->GetWalletTx(txin
.prevout
.hash
);
1887 if (parent
== nullptr)
1889 const CTxOut
& parentOut
= parent
->tx
->vout
[txin
.prevout
.n
];
1890 if (pwallet
->IsMine(parentOut
) != ISMINE_SPENDABLE
)
1896 bool CWalletTx::IsEquivalentTo(const CWalletTx
& _tx
) const
1898 CMutableTransaction tx1
= *this->tx
;
1899 CMutableTransaction tx2
= *_tx
.tx
;
1900 for (auto& txin
: tx1
.vin
) txin
.scriptSig
= CScript();
1901 for (auto& txin
: tx2
.vin
) txin
.scriptSig
= CScript();
1902 return CTransaction(tx1
) == CTransaction(tx2
);
1905 std::vector
<uint256
> CWallet::ResendWalletTransactionsBefore(int64_t nTime
, CConnman
* connman
)
1907 std::vector
<uint256
> result
;
1911 // Sort them in chronological order
1912 std::multimap
<unsigned int, CWalletTx
*> mapSorted
;
1913 for (std::pair
<const uint256
, CWalletTx
>& item
: mapWallet
)
1915 CWalletTx
& wtx
= item
.second
;
1916 // Don't rebroadcast if newer than nTime:
1917 if (wtx
.nTimeReceived
> nTime
)
1919 mapSorted
.insert(std::make_pair(wtx
.nTimeReceived
, &wtx
));
1921 for (std::pair
<const unsigned int, CWalletTx
*>& item
: mapSorted
)
1923 CWalletTx
& wtx
= *item
.second
;
1924 if (wtx
.RelayWalletTransaction(connman
))
1925 result
.push_back(wtx
.GetHash());
1930 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime
, CConnman
* connman
)
1932 // Do this infrequently and randomly to avoid giving away
1933 // that these are our transactions.
1934 if (GetTime() < nNextResend
|| !fBroadcastTransactions
)
1936 bool fFirst
= (nNextResend
== 0);
1937 nNextResend
= GetTime() + GetRand(30 * 60);
1941 // Only do it if there's been a new block since last time
1942 if (nBestBlockTime
< nLastResend
)
1944 nLastResend
= GetTime();
1946 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1948 std::vector
<uint256
> relayed
= ResendWalletTransactionsBefore(nBestBlockTime
-5*60, connman
);
1949 if (!relayed
.empty())
1950 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__
, relayed
.size());
1953 /** @} */ // end of mapWallet
1958 /** @defgroup Actions
1964 CAmount
CWallet::GetBalance() const
1968 LOCK2(cs_main
, cs_wallet
);
1969 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
1971 const CWalletTx
* pcoin
= &(*it
).second
;
1972 if (pcoin
->IsTrusted())
1973 nTotal
+= pcoin
->GetAvailableCredit();
1980 CAmount
CWallet::GetUnconfirmedBalance() const
1984 LOCK2(cs_main
, cs_wallet
);
1985 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
1987 const CWalletTx
* pcoin
= &(*it
).second
;
1988 if (!pcoin
->IsTrusted() && pcoin
->GetDepthInMainChain() == 0 && pcoin
->InMempool())
1989 nTotal
+= pcoin
->GetAvailableCredit();
1995 CAmount
CWallet::GetImmatureBalance() const
1999 LOCK2(cs_main
, cs_wallet
);
2000 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
2002 const CWalletTx
* pcoin
= &(*it
).second
;
2003 nTotal
+= pcoin
->GetImmatureCredit();
2009 CAmount
CWallet::GetWatchOnlyBalance() const
2013 LOCK2(cs_main
, cs_wallet
);
2014 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
2016 const CWalletTx
* pcoin
= &(*it
).second
;
2017 if (pcoin
->IsTrusted())
2018 nTotal
+= pcoin
->GetAvailableWatchOnlyCredit();
2025 CAmount
CWallet::GetUnconfirmedWatchOnlyBalance() const
2029 LOCK2(cs_main
, cs_wallet
);
2030 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
2032 const CWalletTx
* pcoin
= &(*it
).second
;
2033 if (!pcoin
->IsTrusted() && pcoin
->GetDepthInMainChain() == 0 && pcoin
->InMempool())
2034 nTotal
+= pcoin
->GetAvailableWatchOnlyCredit();
2040 CAmount
CWallet::GetImmatureWatchOnlyBalance() 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 nTotal
+= pcoin
->GetImmatureWatchOnlyCredit();
2054 // Calculate total balance in a different way from GetBalance. The biggest
2055 // difference is that GetBalance sums up all unspent TxOuts paying to the
2056 // wallet, while this sums up both spent and unspent TxOuts paying to the
2057 // wallet, and then subtracts the values of TxIns spending from the wallet. This
2058 // also has fewer restrictions on which unconfirmed transactions are considered
2060 CAmount
CWallet::GetLegacyBalance(const isminefilter
& filter
, int minDepth
, const std::string
* account
) const
2062 LOCK2(cs_main
, cs_wallet
);
2064 CAmount balance
= 0;
2065 for (const auto& entry
: mapWallet
) {
2066 const CWalletTx
& wtx
= entry
.second
;
2067 const int depth
= wtx
.GetDepthInMainChain();
2068 if (depth
< 0 || !CheckFinalTx(*wtx
.tx
) || wtx
.GetBlocksToMaturity() > 0) {
2072 // Loop through tx outputs and add incoming payments. For outgoing txs,
2073 // treat change outputs specially, as part of the amount debited.
2074 CAmount debit
= wtx
.GetDebit(filter
);
2075 const bool outgoing
= debit
> 0;
2076 for (const CTxOut
& out
: wtx
.tx
->vout
) {
2077 if (outgoing
&& IsChange(out
)) {
2078 debit
-= out
.nValue
;
2079 } else if (IsMine(out
) & filter
&& depth
>= minDepth
&& (!account
|| *account
== GetAccountName(out
.scriptPubKey
))) {
2080 balance
+= out
.nValue
;
2084 // For outgoing txs, subtract amount debited.
2085 if (outgoing
&& (!account
|| *account
== wtx
.strFromAccount
)) {
2091 balance
+= CWalletDB(*dbw
).GetAccountCreditDebit(*account
);
2097 CAmount
CWallet::GetAvailableBalance(const CCoinControl
* coinControl
) const
2099 LOCK2(cs_main
, cs_wallet
);
2101 CAmount balance
= 0;
2102 std::vector
<COutput
> vCoins
;
2103 AvailableCoins(vCoins
, true, coinControl
);
2104 for (const COutput
& out
: vCoins
) {
2105 if (out
.fSpendable
) {
2106 balance
+= out
.tx
->tx
->vout
[out
.i
].nValue
;
2112 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
2117 LOCK2(cs_main
, cs_wallet
);
2121 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
2123 const uint256
& wtxid
= it
->first
;
2124 const CWalletTx
* pcoin
= &(*it
).second
;
2126 if (!CheckFinalTx(*pcoin
))
2129 if (pcoin
->IsCoinBase() && pcoin
->GetBlocksToMaturity() > 0)
2132 int nDepth
= pcoin
->GetDepthInMainChain();
2136 // We should not consider coins which aren't at least in our mempool
2137 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2138 if (nDepth
== 0 && !pcoin
->InMempool())
2141 bool safeTx
= pcoin
->IsTrusted();
2143 // We should not consider coins from transactions that are replacing
2144 // other transactions.
2146 // Example: There is a transaction A which is replaced by bumpfee
2147 // transaction B. In this case, we want to prevent creation of
2148 // a transaction B' which spends an output of B.
2150 // Reason: If transaction A were initially confirmed, transactions B
2151 // and B' would no longer be valid, so the user would have to create
2152 // a new transaction C to replace B'. However, in the case of a
2153 // one-block reorg, transactions B' and C might BOTH be accepted,
2154 // when the user only wanted one of them. Specifically, there could
2155 // be a 1-block reorg away from the chain where transactions A and C
2156 // were accepted to another chain where B, B', and C were all
2158 if (nDepth
== 0 && pcoin
->mapValue
.count("replaces_txid")) {
2162 // Similarly, we should not consider coins from transactions that
2163 // have been replaced. In the example above, we would want to prevent
2164 // creation of a transaction A' spending an output of A, because if
2165 // transaction B were initially confirmed, conflicting with A and
2166 // A', we wouldn't want to the user to create a transaction D
2167 // intending to replace A', but potentially resulting in a scenario
2168 // where A, A', and D could all be accepted (instead of just B and
2169 // D, or just A and A' like the user would want).
2170 if (nDepth
== 0 && pcoin
->mapValue
.count("replaced_by_txid")) {
2174 if (fOnlySafe
&& !safeTx
) {
2178 if (nDepth
< nMinDepth
|| nDepth
> nMaxDepth
)
2181 for (unsigned int i
= 0; i
< pcoin
->tx
->vout
.size(); i
++) {
2182 if (pcoin
->tx
->vout
[i
].nValue
< nMinimumAmount
|| pcoin
->tx
->vout
[i
].nValue
> nMaximumAmount
)
2185 if (coinControl
&& coinControl
->HasSelected() && !coinControl
->fAllowOtherInputs
&& !coinControl
->IsSelected(COutPoint((*it
).first
, i
)))
2188 if (IsLockedCoin((*it
).first
, i
))
2191 if (IsSpent(wtxid
, i
))
2194 isminetype mine
= IsMine(pcoin
->tx
->vout
[i
]);
2196 if (mine
== ISMINE_NO
) {
2200 bool fSpendableIn
= ((mine
& ISMINE_SPENDABLE
) != ISMINE_NO
) || (coinControl
&& coinControl
->fAllowWatchOnly
&& (mine
& ISMINE_WATCH_SOLVABLE
) != ISMINE_NO
);
2201 bool fSolvableIn
= (mine
& (ISMINE_SPENDABLE
| ISMINE_WATCH_SOLVABLE
)) != ISMINE_NO
;
2203 vCoins
.push_back(COutput(pcoin
, i
, nDepth
, fSpendableIn
, fSolvableIn
, safeTx
));
2205 // Checks the sum amount of all UTXO's.
2206 if (nMinimumSumAmount
!= MAX_MONEY
) {
2207 nTotal
+= pcoin
->tx
->vout
[i
].nValue
;
2209 if (nTotal
>= nMinimumSumAmount
) {
2214 // Checks the maximum number of UTXO's.
2215 if (nMaximumCount
> 0 && vCoins
.size() >= nMaximumCount
) {
2223 std::map
<CTxDestination
, std::vector
<COutput
>> CWallet::ListCoins() const
2225 // TODO: Add AssertLockHeld(cs_wallet) here.
2227 // Because the return value from this function contains pointers to
2228 // CWalletTx objects, callers to this function really should acquire the
2229 // cs_wallet lock before calling it. However, the current caller doesn't
2230 // acquire this lock yet. There was an attempt to add the missing lock in
2231 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2232 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2233 // avoid adding some extra complexity to the Qt code.
2235 std::map
<CTxDestination
, std::vector
<COutput
>> result
;
2237 std::vector
<COutput
> availableCoins
;
2238 AvailableCoins(availableCoins
);
2240 LOCK2(cs_main
, cs_wallet
);
2241 for (auto& coin
: availableCoins
) {
2242 CTxDestination address
;
2243 if (coin
.fSpendable
&&
2244 ExtractDestination(FindNonChangeParentOutput(*coin
.tx
->tx
, coin
.i
).scriptPubKey
, address
)) {
2245 result
[address
].emplace_back(std::move(coin
));
2249 std::vector
<COutPoint
> lockedCoins
;
2250 ListLockedCoins(lockedCoins
);
2251 for (const auto& output
: lockedCoins
) {
2252 auto it
= mapWallet
.find(output
.hash
);
2253 if (it
!= mapWallet
.end()) {
2254 int depth
= it
->second
.GetDepthInMainChain();
2255 if (depth
>= 0 && output
.n
< it
->second
.tx
->vout
.size() &&
2256 IsMine(it
->second
.tx
->vout
[output
.n
]) == ISMINE_SPENDABLE
) {
2257 CTxDestination address
;
2258 if (ExtractDestination(FindNonChangeParentOutput(*it
->second
.tx
, output
.n
).scriptPubKey
, address
)) {
2259 result
[address
].emplace_back(
2260 &it
->second
, output
.n
, depth
, true /* spendable */, true /* solvable */, false /* safe */);
2269 const CTxOut
& CWallet::FindNonChangeParentOutput(const CTransaction
& tx
, int output
) const
2271 const CTransaction
* ptx
= &tx
;
2273 while (IsChange(ptx
->vout
[n
]) && ptx
->vin
.size() > 0) {
2274 const COutPoint
& prevout
= ptx
->vin
[0].prevout
;
2275 auto it
= mapWallet
.find(prevout
.hash
);
2276 if (it
== mapWallet
.end() || it
->second
.tx
->vout
.size() <= prevout
.n
||
2277 !IsMine(it
->second
.tx
->vout
[prevout
.n
])) {
2280 ptx
= it
->second
.tx
.get();
2283 return ptx
->vout
[n
];
2286 static void ApproximateBestSubset(const std::vector
<CInputCoin
>& vValue
, const CAmount
& nTotalLower
, const CAmount
& nTargetValue
,
2287 std::vector
<char>& vfBest
, CAmount
& nBest
, int iterations
= 1000)
2289 std::vector
<char> vfIncluded
;
2291 vfBest
.assign(vValue
.size(), true);
2292 nBest
= nTotalLower
;
2294 FastRandomContext insecure_rand
;
2296 for (int nRep
= 0; nRep
< iterations
&& nBest
!= nTargetValue
; nRep
++)
2298 vfIncluded
.assign(vValue
.size(), false);
2300 bool fReachedTarget
= false;
2301 for (int nPass
= 0; nPass
< 2 && !fReachedTarget
; nPass
++)
2303 for (unsigned int i
= 0; i
< vValue
.size(); i
++)
2305 //The solver here uses a randomized algorithm,
2306 //the randomness serves no real security purpose but is just
2307 //needed to prevent degenerate behavior and it is important
2308 //that the rng is fast. We do not use a constant random sequence,
2309 //because there may be some privacy improvement by making
2310 //the selection random.
2311 if (nPass
== 0 ? insecure_rand
.randbool() : !vfIncluded
[i
])
2313 nTotal
+= vValue
[i
].txout
.nValue
;
2314 vfIncluded
[i
] = true;
2315 if (nTotal
>= nTargetValue
)
2317 fReachedTarget
= true;
2321 vfBest
= vfIncluded
;
2323 nTotal
-= vValue
[i
].txout
.nValue
;
2324 vfIncluded
[i
] = false;
2332 bool CWallet::SelectCoinsMinConf(const CAmount
& nTargetValue
, const int nConfMine
, const int nConfTheirs
, const uint64_t nMaxAncestors
, std::vector
<COutput
> vCoins
,
2333 std::set
<CInputCoin
>& setCoinsRet
, CAmount
& nValueRet
) const
2335 setCoinsRet
.clear();
2338 // List of values less than target
2339 boost::optional
<CInputCoin
> coinLowestLarger
;
2340 std::vector
<CInputCoin
> vValue
;
2341 CAmount nTotalLower
= 0;
2343 random_shuffle(vCoins
.begin(), vCoins
.end(), GetRandInt
);
2345 for (const COutput
&output
: vCoins
)
2347 if (!output
.fSpendable
)
2350 const CWalletTx
*pcoin
= output
.tx
;
2352 if (output
.nDepth
< (pcoin
->IsFromMe(ISMINE_ALL
) ? nConfMine
: nConfTheirs
))
2355 if (!mempool
.TransactionWithinChainLimit(pcoin
->GetHash(), nMaxAncestors
))
2360 CInputCoin coin
= CInputCoin(pcoin
, i
);
2362 if (coin
.txout
.nValue
== nTargetValue
)
2364 setCoinsRet
.insert(coin
);
2365 nValueRet
+= coin
.txout
.nValue
;
2368 else if (coin
.txout
.nValue
< nTargetValue
+ MIN_CHANGE
)
2370 vValue
.push_back(coin
);
2371 nTotalLower
+= coin
.txout
.nValue
;
2373 else if (!coinLowestLarger
|| coin
.txout
.nValue
< coinLowestLarger
->txout
.nValue
)
2375 coinLowestLarger
= coin
;
2379 if (nTotalLower
== nTargetValue
)
2381 for (const auto& input
: vValue
)
2383 setCoinsRet
.insert(input
);
2384 nValueRet
+= input
.txout
.nValue
;
2389 if (nTotalLower
< nTargetValue
)
2391 if (!coinLowestLarger
)
2393 setCoinsRet
.insert(coinLowestLarger
.get());
2394 nValueRet
+= coinLowestLarger
->txout
.nValue
;
2398 // Solve subset sum by stochastic approximation
2399 std::sort(vValue
.begin(), vValue
.end(), CompareValueOnly());
2400 std::reverse(vValue
.begin(), vValue
.end());
2401 std::vector
<char> vfBest
;
2404 ApproximateBestSubset(vValue
, nTotalLower
, nTargetValue
, vfBest
, nBest
);
2405 if (nBest
!= nTargetValue
&& nTotalLower
>= nTargetValue
+ MIN_CHANGE
)
2406 ApproximateBestSubset(vValue
, nTotalLower
, nTargetValue
+ MIN_CHANGE
, vfBest
, nBest
);
2408 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2409 // or the next bigger coin is closer), return the bigger coin
2410 if (coinLowestLarger
&&
2411 ((nBest
!= nTargetValue
&& nBest
< nTargetValue
+ MIN_CHANGE
) || coinLowestLarger
->txout
.nValue
<= nBest
))
2413 setCoinsRet
.insert(coinLowestLarger
.get());
2414 nValueRet
+= coinLowestLarger
->txout
.nValue
;
2417 for (unsigned int i
= 0; i
< vValue
.size(); i
++)
2420 setCoinsRet
.insert(vValue
[i
]);
2421 nValueRet
+= vValue
[i
].txout
.nValue
;
2424 if (LogAcceptCategory(BCLog::SELECTCOINS
)) {
2425 LogPrint(BCLog::SELECTCOINS
, "SelectCoins() best subset: ");
2426 for (unsigned int i
= 0; i
< vValue
.size(); i
++) {
2428 LogPrint(BCLog::SELECTCOINS
, "%s ", FormatMoney(vValue
[i
].txout
.nValue
));
2431 LogPrint(BCLog::SELECTCOINS
, "total %s\n", FormatMoney(nBest
));
2438 bool CWallet::SelectCoins(const std::vector
<COutput
>& vAvailableCoins
, const CAmount
& nTargetValue
, std::set
<CInputCoin
>& setCoinsRet
, CAmount
& nValueRet
, const CCoinControl
* coinControl
) const
2440 std::vector
<COutput
> vCoins(vAvailableCoins
);
2442 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2443 if (coinControl
&& coinControl
->HasSelected() && !coinControl
->fAllowOtherInputs
)
2445 for (const COutput
& out
: vCoins
)
2447 if (!out
.fSpendable
)
2449 nValueRet
+= out
.tx
->tx
->vout
[out
.i
].nValue
;
2450 setCoinsRet
.insert(CInputCoin(out
.tx
, out
.i
));
2452 return (nValueRet
>= nTargetValue
);
2455 // calculate value from preset inputs and store them
2456 std::set
<CInputCoin
> setPresetCoins
;
2457 CAmount nValueFromPresetInputs
= 0;
2459 std::vector
<COutPoint
> vPresetInputs
;
2461 coinControl
->ListSelected(vPresetInputs
);
2462 for (const COutPoint
& outpoint
: vPresetInputs
)
2464 std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.find(outpoint
.hash
);
2465 if (it
!= mapWallet
.end())
2467 const CWalletTx
* pcoin
= &it
->second
;
2468 // Clearly invalid input, fail
2469 if (pcoin
->tx
->vout
.size() <= outpoint
.n
)
2471 nValueFromPresetInputs
+= pcoin
->tx
->vout
[outpoint
.n
].nValue
;
2472 setPresetCoins
.insert(CInputCoin(pcoin
, outpoint
.n
));
2474 return false; // TODO: Allow non-wallet inputs
2477 // remove preset inputs from vCoins
2478 for (std::vector
<COutput
>::iterator it
= vCoins
.begin(); it
!= vCoins
.end() && coinControl
&& coinControl
->HasSelected();)
2480 if (setPresetCoins
.count(CInputCoin(it
->tx
, it
->i
)))
2481 it
= vCoins
.erase(it
);
2486 size_t nMaxChainLength
= std::min(gArgs
.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT
), gArgs
.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT
));
2487 bool fRejectLongChains
= gArgs
.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS
);
2489 bool res
= nTargetValue
<= nValueFromPresetInputs
||
2490 SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 1, 6, 0, vCoins
, setCoinsRet
, nValueRet
) ||
2491 SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 1, 1, 0, vCoins
, setCoinsRet
, nValueRet
) ||
2492 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, 2, vCoins
, setCoinsRet
, nValueRet
)) ||
2493 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, std::min((size_t)4, nMaxChainLength
/3), vCoins
, setCoinsRet
, nValueRet
)) ||
2494 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, nMaxChainLength
/2, vCoins
, setCoinsRet
, nValueRet
)) ||
2495 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, nMaxChainLength
, vCoins
, setCoinsRet
, nValueRet
)) ||
2496 (bSpendZeroConfChange
&& !fRejectLongChains
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, std::numeric_limits
<uint64_t>::max(), vCoins
, setCoinsRet
, nValueRet
));
2498 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2499 setCoinsRet
.insert(setPresetCoins
.begin(), setPresetCoins
.end());
2501 // add preset inputs to the total value selected
2502 nValueRet
+= nValueFromPresetInputs
;
2507 bool CWallet::SignTransaction(CMutableTransaction
&tx
)
2509 AssertLockHeld(cs_wallet
); // mapWallet
2512 CTransaction
txNewConst(tx
);
2514 for (const auto& input
: tx
.vin
) {
2515 std::map
<uint256
, CWalletTx
>::const_iterator mi
= mapWallet
.find(input
.prevout
.hash
);
2516 if(mi
== mapWallet
.end() || input
.prevout
.n
>= mi
->second
.tx
->vout
.size()) {
2519 const CScript
& scriptPubKey
= mi
->second
.tx
->vout
[input
.prevout
.n
].scriptPubKey
;
2520 const CAmount
& amount
= mi
->second
.tx
->vout
[input
.prevout
.n
].nValue
;
2521 SignatureData sigdata
;
2522 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst
, nIn
, amount
, SIGHASH_ALL
), scriptPubKey
, sigdata
)) {
2525 UpdateTransaction(tx
, nIn
, sigdata
);
2531 bool CWallet::FundTransaction(CMutableTransaction
& tx
, CAmount
& nFeeRet
, int& nChangePosInOut
, std::string
& strFailReason
, bool lockUnspents
, const std::set
<int>& setSubtractFeeFromOutputs
, CCoinControl coinControl
)
2533 std::vector
<CRecipient
> vecSend
;
2535 // Turn the txout set into a CRecipient vector
2536 for (size_t idx
= 0; idx
< tx
.vout
.size(); idx
++)
2538 const CTxOut
& txOut
= tx
.vout
[idx
];
2539 CRecipient recipient
= {txOut
.scriptPubKey
, txOut
.nValue
, setSubtractFeeFromOutputs
.count(idx
) == 1};
2540 vecSend
.push_back(recipient
);
2543 coinControl
.fAllowOtherInputs
= true;
2545 for (const CTxIn
& txin
: tx
.vin
)
2546 coinControl
.Select(txin
.prevout
);
2548 CReserveKey
reservekey(this);
2550 if (!CreateTransaction(vecSend
, wtx
, reservekey
, nFeeRet
, nChangePosInOut
, strFailReason
, coinControl
, false)) {
2554 if (nChangePosInOut
!= -1) {
2555 tx
.vout
.insert(tx
.vout
.begin() + nChangePosInOut
, wtx
.tx
->vout
[nChangePosInOut
]);
2556 // we don't have the normal Create/Commit cycle, and don't want to risk reusing change,
2557 // so just remove the key from the keypool here.
2558 reservekey
.KeepKey();
2561 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2562 for (unsigned int idx
= 0; idx
< tx
.vout
.size(); idx
++)
2563 tx
.vout
[idx
].nValue
= wtx
.tx
->vout
[idx
].nValue
;
2565 // Add new txins (keeping original txin scriptSig/order)
2566 for (const CTxIn
& txin
: wtx
.tx
->vin
)
2568 if (!coinControl
.IsSelected(txin
.prevout
))
2570 tx
.vin
.push_back(txin
);
2574 LOCK2(cs_main
, cs_wallet
);
2575 LockCoin(txin
.prevout
);
2584 bool CWallet::CreateTransaction(const std::vector
<CRecipient
>& vecSend
, CWalletTx
& wtxNew
, CReserveKey
& reservekey
, CAmount
& nFeeRet
,
2585 int& nChangePosInOut
, std::string
& strFailReason
, const CCoinControl
& coin_control
, bool sign
)
2588 int nChangePosRequest
= nChangePosInOut
;
2589 unsigned int nSubtractFeeFromAmount
= 0;
2590 for (const auto& recipient
: vecSend
)
2592 if (nValue
< 0 || recipient
.nAmount
< 0)
2594 strFailReason
= _("Transaction amounts must not be negative");
2597 nValue
+= recipient
.nAmount
;
2599 if (recipient
.fSubtractFeeFromAmount
)
2600 nSubtractFeeFromAmount
++;
2602 if (vecSend
.empty())
2604 strFailReason
= _("Transaction must have at least one recipient");
2608 wtxNew
.fTimeReceivedIsTxTime
= true;
2609 wtxNew
.BindWallet(this);
2610 CMutableTransaction txNew
;
2612 // Discourage fee sniping.
2614 // For a large miner the value of the transactions in the best block and
2615 // the mempool can exceed the cost of deliberately attempting to mine two
2616 // blocks to orphan the current best block. By setting nLockTime such that
2617 // only the next block can include the transaction, we discourage this
2618 // practice as the height restricted and limited blocksize gives miners
2619 // considering fee sniping fewer options for pulling off this attack.
2621 // A simple way to think about this is from the wallet's point of view we
2622 // always want the blockchain to move forward. By setting nLockTime this
2623 // way we're basically making the statement that we only want this
2624 // transaction to appear in the next block; we don't want to potentially
2625 // encourage reorgs by allowing transactions to appear at lower heights
2626 // than the next block in forks of the best chain.
2628 // Of course, the subsidy is high enough, and transaction volume low
2629 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2630 // now we ensure code won't be written that makes assumptions about
2631 // nLockTime that preclude a fix later.
2632 txNew
.nLockTime
= chainActive
.Height();
2634 // Secondly occasionally randomly pick a nLockTime even further back, so
2635 // that transactions that are delayed after signing for whatever reason,
2636 // e.g. high-latency mix networks and some CoinJoin implementations, have
2638 if (GetRandInt(10) == 0)
2639 txNew
.nLockTime
= std::max(0, (int)txNew
.nLockTime
- GetRandInt(100));
2641 assert(txNew
.nLockTime
<= (unsigned int)chainActive
.Height());
2642 assert(txNew
.nLockTime
< LOCKTIME_THRESHOLD
);
2643 FeeCalculation feeCalc
;
2645 unsigned int nBytes
;
2647 std::set
<CInputCoin
> setCoins
;
2648 LOCK2(cs_main
, cs_wallet
);
2650 std::vector
<COutput
> vAvailableCoins
;
2651 AvailableCoins(vAvailableCoins
, true, &coin_control
);
2653 // Create change script that will be used if we need change
2654 // TODO: pass in scriptChange instead of reservekey so
2655 // change transaction isn't always pay-to-bitcoin-address
2656 CScript scriptChange
;
2658 // coin control: send change to custom address
2659 if (!boost::get
<CNoDestination
>(&coin_control
.destChange
)) {
2660 scriptChange
= GetScriptForDestination(coin_control
.destChange
);
2661 } else { // no coin control: send change to newly generated address
2662 // Note: We use a new key here to keep it from being obvious which side is the change.
2663 // The drawback is that by not reusing a previous key, the change may be lost if a
2664 // backup is restored, if the backup doesn't have the new private key for the change.
2665 // If we reused the old key, it would be possible to add code to look for and
2666 // rediscover unknown transactions that were written with keys of ours to recover
2667 // post-backup change.
2669 // Reserve a new key pair from key pool
2672 ret
= reservekey
.GetReservedKey(vchPubKey
, true);
2675 strFailReason
= _("Keypool ran out, please call keypoolrefill first");
2679 scriptChange
= GetScriptForDestination(vchPubKey
.GetID());
2681 CTxOut
change_prototype_txout(0, scriptChange
);
2682 size_t change_prototype_size
= GetSerializeSize(change_prototype_txout
, SER_DISK
, 0);
2684 CFeeRate discard_rate
= GetDiscardRate(::feeEstimator
);
2686 bool pick_new_inputs
= true;
2687 CAmount nValueIn
= 0;
2688 // Start with no fee and loop until there is enough fee
2691 nChangePosInOut
= nChangePosRequest
;
2694 wtxNew
.fFromMe
= true;
2697 CAmount nValueToSelect
= nValue
;
2698 if (nSubtractFeeFromAmount
== 0)
2699 nValueToSelect
+= nFeeRet
;
2700 // vouts to the payees
2701 for (const auto& recipient
: vecSend
)
2703 CTxOut
txout(recipient
.nAmount
, recipient
.scriptPubKey
);
2705 if (recipient
.fSubtractFeeFromAmount
)
2707 txout
.nValue
-= nFeeRet
/ nSubtractFeeFromAmount
; // Subtract fee equally from each selected recipient
2709 if (fFirst
) // first receiver pays the remainder not divisible by output count
2712 txout
.nValue
-= nFeeRet
% nSubtractFeeFromAmount
;
2716 if (IsDust(txout
, ::dustRelayFee
))
2718 if (recipient
.fSubtractFeeFromAmount
&& nFeeRet
> 0)
2720 if (txout
.nValue
< 0)
2721 strFailReason
= _("The transaction amount is too small to pay the fee");
2723 strFailReason
= _("The transaction amount is too small to send after the fee has been deducted");
2726 strFailReason
= _("Transaction amount too small");
2729 txNew
.vout
.push_back(txout
);
2732 // Choose coins to use
2733 if (pick_new_inputs
) {
2736 if (!SelectCoins(vAvailableCoins
, nValueToSelect
, setCoins
, nValueIn
, &coin_control
))
2738 strFailReason
= _("Insufficient funds");
2743 const CAmount nChange
= nValueIn
- nValueToSelect
;
2747 // Fill a vout to ourself
2748 CTxOut
newTxOut(nChange
, scriptChange
);
2750 // Never create dust outputs; if we would, just
2751 // add the dust to the fee.
2752 if (IsDust(newTxOut
, discard_rate
))
2754 nChangePosInOut
= -1;
2759 if (nChangePosInOut
== -1)
2761 // Insert change txn at random position:
2762 nChangePosInOut
= GetRandInt(txNew
.vout
.size()+1);
2764 else if ((unsigned int)nChangePosInOut
> txNew
.vout
.size())
2766 strFailReason
= _("Change index out of range");
2770 std::vector
<CTxOut
>::iterator position
= txNew
.vout
.begin()+nChangePosInOut
;
2771 txNew
.vout
.insert(position
, newTxOut
);
2774 nChangePosInOut
= -1;
2779 // Note how the sequence number is set to non-maxint so that
2780 // the nLockTime set above actually works.
2782 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2783 // we use the highest possible value in that range (maxint-2)
2784 // to avoid conflicting with other possible uses of nSequence,
2785 // and in the spirit of "smallest possible change from prior
2787 const uint32_t nSequence
= coin_control
.signalRbf
? MAX_BIP125_RBF_SEQUENCE
: (CTxIn::SEQUENCE_FINAL
- 1);
2788 for (const auto& coin
: setCoins
)
2789 txNew
.vin
.push_back(CTxIn(coin
.outpoint
,CScript(),
2792 // Fill in dummy signatures for fee calculation.
2793 if (!DummySignTx(txNew
, setCoins
)) {
2794 strFailReason
= _("Signing transaction failed");
2798 nBytes
= GetVirtualTransactionSize(txNew
);
2800 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2801 for (auto& vin
: txNew
.vin
) {
2802 vin
.scriptSig
= CScript();
2803 vin
.scriptWitness
.SetNull();
2806 nFeeNeeded
= GetMinimumFee(nBytes
, coin_control
, ::mempool
, ::feeEstimator
, &feeCalc
);
2808 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2809 // because we must be at the maximum allowed fee.
2810 if (nFeeNeeded
< ::minRelayTxFee
.GetFee(nBytes
))
2812 strFailReason
= _("Transaction too large for fee policy");
2816 if (nFeeRet
>= nFeeNeeded
) {
2817 // Reduce fee to only the needed amount if possible. This
2818 // prevents potential overpayment in fees if the coins
2819 // selected to meet nFeeNeeded result in a transaction that
2820 // requires less fee than the prior iteration.
2822 // If we have no change and a big enough excess fee, then
2823 // try to construct transaction again only without picking
2824 // new inputs. We now know we only need the smaller fee
2825 // (because of reduced tx size) and so we should add a
2826 // change output. Only try this once.
2827 if (nChangePosInOut
== -1 && nSubtractFeeFromAmount
== 0 && pick_new_inputs
) {
2828 unsigned int tx_size_with_change
= nBytes
+ change_prototype_size
+ 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
2829 CAmount fee_needed_with_change
= GetMinimumFee(tx_size_with_change
, coin_control
, ::mempool
, ::feeEstimator
, nullptr);
2830 CAmount minimum_value_for_change
= GetDustThreshold(change_prototype_txout
, discard_rate
);
2831 if (nFeeRet
>= fee_needed_with_change
+ minimum_value_for_change
) {
2832 pick_new_inputs
= false;
2833 nFeeRet
= fee_needed_with_change
;
2838 // If we have change output already, just increase it
2839 if (nFeeRet
> nFeeNeeded
&& nChangePosInOut
!= -1 && nSubtractFeeFromAmount
== 0) {
2840 CAmount extraFeePaid
= nFeeRet
- nFeeNeeded
;
2841 std::vector
<CTxOut
>::iterator change_position
= txNew
.vout
.begin()+nChangePosInOut
;
2842 change_position
->nValue
+= extraFeePaid
;
2843 nFeeRet
-= extraFeePaid
;
2845 break; // Done, enough fee included.
2847 else if (!pick_new_inputs
) {
2848 // This shouldn't happen, we should have had enough excess
2849 // fee to pay for the new output and still meet nFeeNeeded
2850 // Or we should have just subtracted fee from recipients and
2851 // nFeeNeeded should not have changed
2852 strFailReason
= _("Transaction fee and change calculation failed");
2856 // Try to reduce change to include necessary fee
2857 if (nChangePosInOut
!= -1 && nSubtractFeeFromAmount
== 0) {
2858 CAmount additionalFeeNeeded
= nFeeNeeded
- nFeeRet
;
2859 std::vector
<CTxOut
>::iterator change_position
= txNew
.vout
.begin()+nChangePosInOut
;
2860 // Only reduce change if remaining amount is still a large enough output.
2861 if (change_position
->nValue
>= MIN_FINAL_CHANGE
+ additionalFeeNeeded
) {
2862 change_position
->nValue
-= additionalFeeNeeded
;
2863 nFeeRet
+= additionalFeeNeeded
;
2864 break; // Done, able to increase fee from change
2868 // If subtracting fee from recipients, we now know what fee we
2869 // need to subtract, we have no reason to reselect inputs
2870 if (nSubtractFeeFromAmount
> 0) {
2871 pick_new_inputs
= false;
2874 // Include more fee and try again.
2875 nFeeRet
= nFeeNeeded
;
2880 if (nChangePosInOut
== -1) reservekey
.ReturnKey(); // Return any reserved key if we don't have change
2884 CTransaction
txNewConst(txNew
);
2886 for (const auto& coin
: setCoins
)
2888 const CScript
& scriptPubKey
= coin
.txout
.scriptPubKey
;
2889 SignatureData sigdata
;
2891 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst
, nIn
, coin
.txout
.nValue
, SIGHASH_ALL
), scriptPubKey
, sigdata
))
2893 strFailReason
= _("Signing transaction failed");
2896 UpdateTransaction(txNew
, nIn
, sigdata
);
2903 // Embed the constructed transaction data in wtxNew.
2904 wtxNew
.SetTx(MakeTransactionRef(std::move(txNew
)));
2907 if (GetTransactionWeight(wtxNew
) >= MAX_STANDARD_TX_WEIGHT
)
2909 strFailReason
= _("Transaction too large");
2914 if (gArgs
.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS
)) {
2915 // Lastly, ensure this tx will pass the mempool's chain limits
2917 CTxMemPoolEntry
entry(wtxNew
.tx
, 0, 0, 0, false, 0, lp
);
2918 CTxMemPool::setEntries setAncestors
;
2919 size_t nLimitAncestors
= gArgs
.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT
);
2920 size_t nLimitAncestorSize
= gArgs
.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT
)*1000;
2921 size_t nLimitDescendants
= gArgs
.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT
);
2922 size_t nLimitDescendantSize
= gArgs
.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT
)*1000;
2923 std::string errString
;
2924 if (!mempool
.CalculateMemPoolAncestors(entry
, setAncestors
, nLimitAncestors
, nLimitAncestorSize
, nLimitDescendants
, nLimitDescendantSize
, errString
)) {
2925 strFailReason
= _("Transaction has too long of a mempool chain");
2930 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",
2931 nFeeRet
, nBytes
, nFeeNeeded
, feeCalc
.returnedTarget
, feeCalc
.desiredTarget
, StringForFeeReason(feeCalc
.reason
), feeCalc
.est
.decay
,
2932 feeCalc
.est
.pass
.start
, feeCalc
.est
.pass
.end
,
2933 100 * feeCalc
.est
.pass
.withinTarget
/ (feeCalc
.est
.pass
.totalConfirmed
+ feeCalc
.est
.pass
.inMempool
+ feeCalc
.est
.pass
.leftMempool
),
2934 feeCalc
.est
.pass
.withinTarget
, feeCalc
.est
.pass
.totalConfirmed
, feeCalc
.est
.pass
.inMempool
, feeCalc
.est
.pass
.leftMempool
,
2935 feeCalc
.est
.fail
.start
, feeCalc
.est
.fail
.end
,
2936 100 * feeCalc
.est
.fail
.withinTarget
/ (feeCalc
.est
.fail
.totalConfirmed
+ feeCalc
.est
.fail
.inMempool
+ feeCalc
.est
.fail
.leftMempool
),
2937 feeCalc
.est
.fail
.withinTarget
, feeCalc
.est
.fail
.totalConfirmed
, feeCalc
.est
.fail
.inMempool
, feeCalc
.est
.fail
.leftMempool
);
2942 * Call after CreateTransaction unless you want to abort
2944 bool CWallet::CommitTransaction(CWalletTx
& wtxNew
, CReserveKey
& reservekey
, CConnman
* connman
, CValidationState
& state
)
2947 LOCK2(cs_main
, cs_wallet
);
2948 LogPrintf("CommitTransaction:\n%s", wtxNew
.tx
->ToString());
2950 // Take key pair from key pool so it won't be used again
2951 reservekey
.KeepKey();
2953 // Add tx to wallet, because if it has change it's also ours,
2954 // otherwise just for transaction history.
2955 AddToWallet(wtxNew
);
2957 // Notify that old coins are spent
2958 for (const CTxIn
& txin
: wtxNew
.tx
->vin
)
2960 CWalletTx
&coin
= mapWallet
[txin
.prevout
.hash
];
2961 coin
.BindWallet(this);
2962 NotifyTransactionChanged(this, coin
.GetHash(), CT_UPDATED
);
2966 // Track how many getdata requests our transaction gets
2967 mapRequestCount
[wtxNew
.GetHash()] = 0;
2969 if (fBroadcastTransactions
)
2972 if (!wtxNew
.AcceptToMemoryPool(maxTxFee
, state
)) {
2973 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state
.GetRejectReason());
2974 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2976 wtxNew
.RelayWalletTransaction(connman
);
2983 void CWallet::ListAccountCreditDebit(const std::string
& strAccount
, std::list
<CAccountingEntry
>& entries
) {
2984 CWalletDB
walletdb(*dbw
);
2985 return walletdb
.ListAccountCreditDebit(strAccount
, entries
);
2988 bool CWallet::AddAccountingEntry(const CAccountingEntry
& acentry
)
2990 CWalletDB
walletdb(*dbw
);
2992 return AddAccountingEntry(acentry
, &walletdb
);
2995 bool CWallet::AddAccountingEntry(const CAccountingEntry
& acentry
, CWalletDB
*pwalletdb
)
2997 if (!pwalletdb
->WriteAccountingEntry(++nAccountingEntryNumber
, acentry
)) {
3001 laccentries
.push_back(acentry
);
3002 CAccountingEntry
& entry
= laccentries
.back();
3003 wtxOrdered
.insert(std::make_pair(entry
.nOrderPos
, TxPair(nullptr, &entry
)));
3008 DBErrors
CWallet::LoadWallet(bool& fFirstRunRet
)
3010 LOCK2(cs_main
, cs_wallet
);
3012 fFirstRunRet
= false;
3013 DBErrors nLoadWalletRet
= CWalletDB(*dbw
,"cr+").LoadWallet(this);
3014 if (nLoadWalletRet
== DB_NEED_REWRITE
)
3016 if (dbw
->Rewrite("\x04pool"))
3018 setInternalKeyPool
.clear();
3019 setExternalKeyPool
.clear();
3020 m_pool_key_to_index
.clear();
3021 // Note: can't top-up keypool here, because wallet is locked.
3022 // User will be prompted to unlock wallet the next operation
3023 // that requires a new key.
3027 // This wallet is in its first run if all of these are empty
3028 fFirstRunRet
= mapKeys
.empty() && mapCryptedKeys
.empty() && mapWatchKeys
.empty() && setWatchOnly
.empty() && mapScripts
.empty();
3030 if (nLoadWalletRet
!= DB_LOAD_OK
)
3031 return nLoadWalletRet
;
3033 uiInterface
.LoadWallet(this);
3038 DBErrors
CWallet::ZapSelectTx(std::vector
<uint256
>& vHashIn
, std::vector
<uint256
>& vHashOut
)
3040 AssertLockHeld(cs_wallet
); // mapWallet
3041 DBErrors nZapSelectTxRet
= CWalletDB(*dbw
,"cr+").ZapSelectTx(vHashIn
, vHashOut
);
3042 for (uint256 hash
: vHashOut
)
3043 mapWallet
.erase(hash
);
3045 if (nZapSelectTxRet
== DB_NEED_REWRITE
)
3047 if (dbw
->Rewrite("\x04pool"))
3049 setInternalKeyPool
.clear();
3050 setExternalKeyPool
.clear();
3051 m_pool_key_to_index
.clear();
3052 // Note: can't top-up keypool here, because wallet is locked.
3053 // User will be prompted to unlock wallet the next operation
3054 // that requires a new key.
3058 if (nZapSelectTxRet
!= DB_LOAD_OK
)
3059 return nZapSelectTxRet
;
3067 DBErrors
CWallet::ZapWalletTx(std::vector
<CWalletTx
>& vWtx
)
3069 DBErrors nZapWalletTxRet
= CWalletDB(*dbw
,"cr+").ZapWalletTx(vWtx
);
3070 if (nZapWalletTxRet
== DB_NEED_REWRITE
)
3072 if (dbw
->Rewrite("\x04pool"))
3075 setInternalKeyPool
.clear();
3076 setExternalKeyPool
.clear();
3077 m_pool_key_to_index
.clear();
3078 // Note: can't top-up keypool here, because wallet is locked.
3079 // User will be prompted to unlock wallet the next operation
3080 // that requires a new key.
3084 if (nZapWalletTxRet
!= DB_LOAD_OK
)
3085 return nZapWalletTxRet
;
3091 bool CWallet::SetAddressBook(const CTxDestination
& address
, const std::string
& strName
, const std::string
& strPurpose
)
3093 bool fUpdated
= false;
3095 LOCK(cs_wallet
); // mapAddressBook
3096 std::map
<CTxDestination
, CAddressBookData
>::iterator mi
= mapAddressBook
.find(address
);
3097 fUpdated
= mi
!= mapAddressBook
.end();
3098 mapAddressBook
[address
].name
= strName
;
3099 if (!strPurpose
.empty()) /* update purpose only if requested */
3100 mapAddressBook
[address
].purpose
= strPurpose
;
3102 NotifyAddressBookChanged(this, address
, strName
, ::IsMine(*this, address
) != ISMINE_NO
,
3103 strPurpose
, (fUpdated
? CT_UPDATED
: CT_NEW
) );
3104 if (!strPurpose
.empty() && !CWalletDB(*dbw
).WritePurpose(EncodeDestination(address
), strPurpose
))
3106 return CWalletDB(*dbw
).WriteName(EncodeDestination(address
), strName
);
3109 bool CWallet::DelAddressBook(const CTxDestination
& address
)
3112 LOCK(cs_wallet
); // mapAddressBook
3114 // Delete destdata tuples associated with address
3115 std::string strAddress
= EncodeDestination(address
);
3116 for (const std::pair
<std::string
, std::string
> &item
: mapAddressBook
[address
].destdata
)
3118 CWalletDB(*dbw
).EraseDestData(strAddress
, item
.first
);
3120 mapAddressBook
.erase(address
);
3123 NotifyAddressBookChanged(this, address
, "", ::IsMine(*this, address
) != ISMINE_NO
, "", CT_DELETED
);
3125 CWalletDB(*dbw
).ErasePurpose(EncodeDestination(address
));
3126 return CWalletDB(*dbw
).EraseName(EncodeDestination(address
));
3129 const std::string
& CWallet::GetAccountName(const CScript
& scriptPubKey
) const
3131 CTxDestination address
;
3132 if (ExtractDestination(scriptPubKey
, address
) && !scriptPubKey
.IsUnspendable()) {
3133 auto mi
= mapAddressBook
.find(address
);
3134 if (mi
!= mapAddressBook
.end()) {
3135 return mi
->second
.name
;
3138 // A scriptPubKey that doesn't have an entry in the address book is
3139 // associated with the default account ("").
3140 const static std::string DEFAULT_ACCOUNT_NAME
;
3141 return DEFAULT_ACCOUNT_NAME
;
3145 * Mark old keypool keys as used,
3146 * and generate all new keys
3148 bool CWallet::NewKeyPool()
3152 CWalletDB
walletdb(*dbw
);
3154 for (int64_t nIndex
: setInternalKeyPool
) {
3155 walletdb
.ErasePool(nIndex
);
3157 setInternalKeyPool
.clear();
3159 for (int64_t nIndex
: setExternalKeyPool
) {
3160 walletdb
.ErasePool(nIndex
);
3162 setExternalKeyPool
.clear();
3164 m_pool_key_to_index
.clear();
3166 if (!TopUpKeyPool()) {
3169 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3174 size_t CWallet::KeypoolCountExternalKeys()
3176 AssertLockHeld(cs_wallet
); // setExternalKeyPool
3177 return setExternalKeyPool
.size();
3180 void CWallet::LoadKeyPool(int64_t nIndex
, const CKeyPool
&keypool
)
3182 AssertLockHeld(cs_wallet
);
3183 if (keypool
.fInternal
) {
3184 setInternalKeyPool
.insert(nIndex
);
3186 setExternalKeyPool
.insert(nIndex
);
3188 m_max_keypool_index
= std::max(m_max_keypool_index
, nIndex
);
3189 m_pool_key_to_index
[keypool
.vchPubKey
.GetID()] = nIndex
;
3191 // If no metadata exists yet, create a default with the pool key's
3192 // creation time. Note that this may be overwritten by actually
3193 // stored metadata for that key later, which is fine.
3194 CKeyID keyid
= keypool
.vchPubKey
.GetID();
3195 if (mapKeyMetadata
.count(keyid
) == 0)
3196 mapKeyMetadata
[keyid
] = CKeyMetadata(keypool
.nTime
);
3199 bool CWallet::TopUpKeyPool(unsigned int kpSize
)
3208 unsigned int nTargetSize
;
3210 nTargetSize
= kpSize
;
3212 nTargetSize
= std::max(gArgs
.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE
), (int64_t) 0);
3214 // count amount of available keys (internal, external)
3215 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3216 int64_t missingExternal
= std::max(std::max((int64_t) nTargetSize
, (int64_t) 1) - (int64_t)setExternalKeyPool
.size(), (int64_t) 0);
3217 int64_t missingInternal
= std::max(std::max((int64_t) nTargetSize
, (int64_t) 1) - (int64_t)setInternalKeyPool
.size(), (int64_t) 0);
3219 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT
))
3221 // don't create extra internal keys
3222 missingInternal
= 0;
3224 bool internal
= false;
3225 CWalletDB
walletdb(*dbw
);
3226 for (int64_t i
= missingInternal
+ missingExternal
; i
--;)
3228 if (i
< missingInternal
) {
3232 assert(m_max_keypool_index
< std::numeric_limits
<int64_t>::max()); // How in the hell did you use so many keys?
3233 int64_t index
= ++m_max_keypool_index
;
3235 CPubKey
pubkey(GenerateNewKey(walletdb
, internal
));
3236 if (!walletdb
.WritePool(index
, CKeyPool(pubkey
, internal
))) {
3237 throw std::runtime_error(std::string(__func__
) + ": writing generated key failed");
3241 setInternalKeyPool
.insert(index
);
3243 setExternalKeyPool
.insert(index
);
3245 m_pool_key_to_index
[pubkey
.GetID()] = index
;
3247 if (missingInternal
+ missingExternal
> 0) {
3248 LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal
+ missingExternal
, missingInternal
, setInternalKeyPool
.size() + setExternalKeyPool
.size(), setInternalKeyPool
.size());
3254 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex
, CKeyPool
& keypool
, bool fRequestedInternal
)
3257 keypool
.vchPubKey
= CPubKey();
3264 bool fReturningInternal
= IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT
) && fRequestedInternal
;
3265 std::set
<int64_t>& setKeyPool
= fReturningInternal
? setInternalKeyPool
: setExternalKeyPool
;
3267 // Get the oldest key
3268 if(setKeyPool
.empty())
3271 CWalletDB
walletdb(*dbw
);
3273 auto it
= setKeyPool
.begin();
3275 setKeyPool
.erase(it
);
3276 if (!walletdb
.ReadPool(nIndex
, keypool
)) {
3277 throw std::runtime_error(std::string(__func__
) + ": read failed");
3279 if (!HaveKey(keypool
.vchPubKey
.GetID())) {
3280 throw std::runtime_error(std::string(__func__
) + ": unknown key in key pool");
3282 if (keypool
.fInternal
!= fReturningInternal
) {
3283 throw std::runtime_error(std::string(__func__
) + ": keypool entry misclassified");
3286 assert(keypool
.vchPubKey
.IsValid());
3287 m_pool_key_to_index
.erase(keypool
.vchPubKey
.GetID());
3288 LogPrintf("keypool reserve %d\n", nIndex
);
3292 void CWallet::KeepKey(int64_t nIndex
)
3294 // Remove from key pool
3295 CWalletDB
walletdb(*dbw
);
3296 walletdb
.ErasePool(nIndex
);
3297 LogPrintf("keypool keep %d\n", nIndex
);
3300 void CWallet::ReturnKey(int64_t nIndex
, bool fInternal
, const CPubKey
& pubkey
)
3302 // Return to key pool
3306 setInternalKeyPool
.insert(nIndex
);
3308 setExternalKeyPool
.insert(nIndex
);
3310 m_pool_key_to_index
[pubkey
.GetID()] = nIndex
;
3312 LogPrintf("keypool return %d\n", nIndex
);
3315 bool CWallet::GetKeyFromPool(CPubKey
& result
, bool internal
)
3321 ReserveKeyFromKeyPool(nIndex
, keypool
, internal
);
3324 if (IsLocked()) return false;
3325 CWalletDB
walletdb(*dbw
);
3326 result
= GenerateNewKey(walletdb
, internal
);
3330 result
= keypool
.vchPubKey
;
3335 static int64_t GetOldestKeyTimeInPool(const std::set
<int64_t>& setKeyPool
, CWalletDB
& walletdb
) {
3336 if (setKeyPool
.empty()) {
3341 int64_t nIndex
= *(setKeyPool
.begin());
3342 if (!walletdb
.ReadPool(nIndex
, keypool
)) {
3343 throw std::runtime_error(std::string(__func__
) + ": read oldest key in keypool failed");
3345 assert(keypool
.vchPubKey
.IsValid());
3346 return keypool
.nTime
;
3349 int64_t CWallet::GetOldestKeyPoolTime()
3353 CWalletDB
walletdb(*dbw
);
3355 // load oldest key from keypool, get time and return
3356 int64_t oldestKey
= GetOldestKeyTimeInPool(setExternalKeyPool
, walletdb
);
3357 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT
)) {
3358 oldestKey
= std::max(GetOldestKeyTimeInPool(setInternalKeyPool
, walletdb
), oldestKey
);
3364 std::map
<CTxDestination
, CAmount
> CWallet::GetAddressBalances()
3366 std::map
<CTxDestination
, CAmount
> balances
;
3370 for (const auto& walletEntry
: mapWallet
)
3372 const CWalletTx
*pcoin
= &walletEntry
.second
;
3374 if (!pcoin
->IsTrusted())
3377 if (pcoin
->IsCoinBase() && pcoin
->GetBlocksToMaturity() > 0)
3380 int nDepth
= pcoin
->GetDepthInMainChain();
3381 if (nDepth
< (pcoin
->IsFromMe(ISMINE_ALL
) ? 0 : 1))
3384 for (unsigned int i
= 0; i
< pcoin
->tx
->vout
.size(); i
++)
3386 CTxDestination addr
;
3387 if (!IsMine(pcoin
->tx
->vout
[i
]))
3389 if(!ExtractDestination(pcoin
->tx
->vout
[i
].scriptPubKey
, addr
))
3392 CAmount n
= IsSpent(walletEntry
.first
, i
) ? 0 : pcoin
->tx
->vout
[i
].nValue
;
3394 if (!balances
.count(addr
))
3396 balances
[addr
] += n
;
3404 std::set
< std::set
<CTxDestination
> > CWallet::GetAddressGroupings()
3406 AssertLockHeld(cs_wallet
); // mapWallet
3407 std::set
< std::set
<CTxDestination
> > groupings
;
3408 std::set
<CTxDestination
> grouping
;
3410 for (const auto& walletEntry
: mapWallet
)
3412 const CWalletTx
*pcoin
= &walletEntry
.second
;
3414 if (pcoin
->tx
->vin
.size() > 0)
3416 bool any_mine
= false;
3417 // group all input addresses with each other
3418 for (CTxIn txin
: pcoin
->tx
->vin
)
3420 CTxDestination address
;
3421 if(!IsMine(txin
)) /* If this input isn't mine, ignore it */
3423 if(!ExtractDestination(mapWallet
[txin
.prevout
.hash
].tx
->vout
[txin
.prevout
.n
].scriptPubKey
, address
))
3425 grouping
.insert(address
);
3429 // group change with input addresses
3432 for (CTxOut txout
: pcoin
->tx
->vout
)
3433 if (IsChange(txout
))
3435 CTxDestination txoutAddr
;
3436 if(!ExtractDestination(txout
.scriptPubKey
, txoutAddr
))
3438 grouping
.insert(txoutAddr
);
3441 if (grouping
.size() > 0)
3443 groupings
.insert(grouping
);
3448 // group lone addrs by themselves
3449 for (const auto& txout
: pcoin
->tx
->vout
)
3452 CTxDestination address
;
3453 if(!ExtractDestination(txout
.scriptPubKey
, address
))
3455 grouping
.insert(address
);
3456 groupings
.insert(grouping
);
3461 std::set
< std::set
<CTxDestination
>* > uniqueGroupings
; // a set of pointers to groups of addresses
3462 std::map
< CTxDestination
, std::set
<CTxDestination
>* > setmap
; // map addresses to the unique group containing it
3463 for (std::set
<CTxDestination
> _grouping
: groupings
)
3465 // make a set of all the groups hit by this new group
3466 std::set
< std::set
<CTxDestination
>* > hits
;
3467 std::map
< CTxDestination
, std::set
<CTxDestination
>* >::iterator it
;
3468 for (CTxDestination address
: _grouping
)
3469 if ((it
= setmap
.find(address
)) != setmap
.end())
3470 hits
.insert((*it
).second
);
3472 // merge all hit groups into a new single group and delete old groups
3473 std::set
<CTxDestination
>* merged
= new std::set
<CTxDestination
>(_grouping
);
3474 for (std::set
<CTxDestination
>* hit
: hits
)
3476 merged
->insert(hit
->begin(), hit
->end());
3477 uniqueGroupings
.erase(hit
);
3480 uniqueGroupings
.insert(merged
);
3483 for (CTxDestination element
: *merged
)
3484 setmap
[element
] = merged
;
3487 std::set
< std::set
<CTxDestination
> > ret
;
3488 for (std::set
<CTxDestination
>* uniqueGrouping
: uniqueGroupings
)
3490 ret
.insert(*uniqueGrouping
);
3491 delete uniqueGrouping
;
3497 std::set
<CTxDestination
> CWallet::GetAccountAddresses(const std::string
& strAccount
) const
3500 std::set
<CTxDestination
> result
;
3501 for (const std::pair
<CTxDestination
, CAddressBookData
>& item
: mapAddressBook
)
3503 const CTxDestination
& address
= item
.first
;
3504 const std::string
& strName
= item
.second
.name
;
3505 if (strName
== strAccount
)
3506 result
.insert(address
);
3511 bool CReserveKey::GetReservedKey(CPubKey
& pubkey
, bool internal
)
3516 pwallet
->ReserveKeyFromKeyPool(nIndex
, keypool
, internal
);
3518 vchPubKey
= keypool
.vchPubKey
;
3522 fInternal
= keypool
.fInternal
;
3524 assert(vchPubKey
.IsValid());
3529 void CReserveKey::KeepKey()
3532 pwallet
->KeepKey(nIndex
);
3534 vchPubKey
= CPubKey();
3537 void CReserveKey::ReturnKey()
3540 pwallet
->ReturnKey(nIndex
, fInternal
, vchPubKey
);
3543 vchPubKey
= CPubKey();
3546 void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id
)
3548 AssertLockHeld(cs_wallet
);
3549 bool internal
= setInternalKeyPool
.count(keypool_id
);
3550 if (!internal
) assert(setExternalKeyPool
.count(keypool_id
));
3551 std::set
<int64_t> *setKeyPool
= internal
? &setInternalKeyPool
: &setExternalKeyPool
;
3552 auto it
= setKeyPool
->begin();
3554 CWalletDB
walletdb(*dbw
);
3555 while (it
!= std::end(*setKeyPool
)) {
3556 const int64_t& index
= *(it
);
3557 if (index
> keypool_id
) break; // set*KeyPool is ordered
3560 if (walletdb
.ReadPool(index
, keypool
)) { //TODO: This should be unnecessary
3561 m_pool_key_to_index
.erase(keypool
.vchPubKey
.GetID());
3563 walletdb
.ErasePool(index
);
3564 LogPrintf("keypool index %d removed\n", index
);
3565 it
= setKeyPool
->erase(it
);
3569 void CWallet::GetScriptForMining(std::shared_ptr
<CReserveScript
> &script
)
3571 std::shared_ptr
<CReserveKey
> rKey
= std::make_shared
<CReserveKey
>(this);
3573 if (!rKey
->GetReservedKey(pubkey
))
3577 script
->reserveScript
= CScript() << ToByteVector(pubkey
) << OP_CHECKSIG
;
3580 void CWallet::LockCoin(const COutPoint
& output
)
3582 AssertLockHeld(cs_wallet
); // setLockedCoins
3583 setLockedCoins
.insert(output
);
3586 void CWallet::UnlockCoin(const COutPoint
& output
)
3588 AssertLockHeld(cs_wallet
); // setLockedCoins
3589 setLockedCoins
.erase(output
);
3592 void CWallet::UnlockAllCoins()
3594 AssertLockHeld(cs_wallet
); // setLockedCoins
3595 setLockedCoins
.clear();
3598 bool CWallet::IsLockedCoin(uint256 hash
, unsigned int n
) const
3600 AssertLockHeld(cs_wallet
); // setLockedCoins
3601 COutPoint
outpt(hash
, n
);
3603 return (setLockedCoins
.count(outpt
) > 0);
3606 void CWallet::ListLockedCoins(std::vector
<COutPoint
>& vOutpts
) const
3608 AssertLockHeld(cs_wallet
); // setLockedCoins
3609 for (std::set
<COutPoint
>::iterator it
= setLockedCoins
.begin();
3610 it
!= setLockedCoins
.end(); it
++) {
3611 COutPoint outpt
= (*it
);
3612 vOutpts
.push_back(outpt
);
3616 /** @} */ // end of Actions
3618 void CWallet::GetKeyBirthTimes(std::map
<CTxDestination
, int64_t> &mapKeyBirth
) const {
3619 AssertLockHeld(cs_wallet
); // mapKeyMetadata
3620 mapKeyBirth
.clear();
3622 // get birth times for keys with metadata
3623 for (const auto& entry
: mapKeyMetadata
) {
3624 if (entry
.second
.nCreateTime
) {
3625 mapKeyBirth
[entry
.first
] = entry
.second
.nCreateTime
;
3629 // map in which we'll infer heights of other keys
3630 CBlockIndex
*pindexMax
= chainActive
[std::max(0, chainActive
.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3631 std::map
<CKeyID
, CBlockIndex
*> mapKeyFirstBlock
;
3632 for (const CKeyID
&keyid
: GetKeys()) {
3633 if (mapKeyBirth
.count(keyid
) == 0)
3634 mapKeyFirstBlock
[keyid
] = pindexMax
;
3637 // if there are no such keys, we're done
3638 if (mapKeyFirstBlock
.empty())
3641 // find first block that affects those keys, if there are any left
3642 std::vector
<CKeyID
> vAffected
;
3643 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); it
++) {
3644 // iterate over all wallet transactions...
3645 const CWalletTx
&wtx
= (*it
).second
;
3646 BlockMap::const_iterator blit
= mapBlockIndex
.find(wtx
.hashBlock
);
3647 if (blit
!= mapBlockIndex
.end() && chainActive
.Contains(blit
->second
)) {
3648 // ... which are already in a block
3649 int nHeight
= blit
->second
->nHeight
;
3650 for (const CTxOut
&txout
: wtx
.tx
->vout
) {
3651 // iterate over all their outputs
3652 CAffectedKeysVisitor(*this, vAffected
).Process(txout
.scriptPubKey
);
3653 for (const CKeyID
&keyid
: vAffected
) {
3654 // ... and all their affected keys
3655 std::map
<CKeyID
, CBlockIndex
*>::iterator rit
= mapKeyFirstBlock
.find(keyid
);
3656 if (rit
!= mapKeyFirstBlock
.end() && nHeight
< rit
->second
->nHeight
)
3657 rit
->second
= blit
->second
;
3664 // Extract block timestamps for those keys
3665 for (std::map
<CKeyID
, CBlockIndex
*>::const_iterator it
= mapKeyFirstBlock
.begin(); it
!= mapKeyFirstBlock
.end(); it
++)
3666 mapKeyBirth
[it
->first
] = it
->second
->GetBlockTime() - TIMESTAMP_WINDOW
; // block times can be 2h off
3670 * Compute smart timestamp for a transaction being added to the wallet.
3673 * - If sending a transaction, assign its timestamp to the current time.
3674 * - If receiving a transaction outside a block, assign its timestamp to the
3676 * - If receiving a block with a future timestamp, assign all its (not already
3677 * known) transactions' timestamps to the current time.
3678 * - If receiving a block with a past timestamp, before the most recent known
3679 * transaction (that we care about), assign all its (not already known)
3680 * transactions' timestamps to the same timestamp as that most-recent-known
3682 * - If receiving a block with a past timestamp, but after the most recent known
3683 * transaction, assign all its (not already known) transactions' timestamps to
3686 * For more information see CWalletTx::nTimeSmart,
3687 * https://bitcointalk.org/?topic=54527, or
3688 * https://github.com/bitcoin/bitcoin/pull/1393.
3690 unsigned int CWallet::ComputeTimeSmart(const CWalletTx
& wtx
) const
3692 unsigned int nTimeSmart
= wtx
.nTimeReceived
;
3693 if (!wtx
.hashUnset()) {
3694 if (mapBlockIndex
.count(wtx
.hashBlock
)) {
3695 int64_t latestNow
= wtx
.nTimeReceived
;
3696 int64_t latestEntry
= 0;
3698 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3699 int64_t latestTolerated
= latestNow
+ 300;
3700 const TxItems
& txOrdered
= wtxOrdered
;
3701 for (auto it
= txOrdered
.rbegin(); it
!= txOrdered
.rend(); ++it
) {
3702 CWalletTx
* const pwtx
= it
->second
.first
;
3706 CAccountingEntry
* const pacentry
= it
->second
.second
;
3709 nSmartTime
= pwtx
->nTimeSmart
;
3711 nSmartTime
= pwtx
->nTimeReceived
;
3714 nSmartTime
= pacentry
->nTime
;
3716 if (nSmartTime
<= latestTolerated
) {
3717 latestEntry
= nSmartTime
;
3718 if (nSmartTime
> latestNow
) {
3719 latestNow
= nSmartTime
;
3725 int64_t blocktime
= mapBlockIndex
[wtx
.hashBlock
]->GetBlockTime();
3726 nTimeSmart
= std::max(latestEntry
, std::min(blocktime
, latestNow
));
3728 LogPrintf("%s: found %s in block %s not in index\n", __func__
, wtx
.GetHash().ToString(), wtx
.hashBlock
.ToString());
3734 bool CWallet::AddDestData(const CTxDestination
&dest
, const std::string
&key
, const std::string
&value
)
3736 if (boost::get
<CNoDestination
>(&dest
))
3739 mapAddressBook
[dest
].destdata
.insert(std::make_pair(key
, value
));
3740 return CWalletDB(*dbw
).WriteDestData(EncodeDestination(dest
), key
, value
);
3743 bool CWallet::EraseDestData(const CTxDestination
&dest
, const std::string
&key
)
3745 if (!mapAddressBook
[dest
].destdata
.erase(key
))
3747 return CWalletDB(*dbw
).EraseDestData(EncodeDestination(dest
), key
);
3750 bool CWallet::LoadDestData(const CTxDestination
&dest
, const std::string
&key
, const std::string
&value
)
3752 mapAddressBook
[dest
].destdata
.insert(std::make_pair(key
, value
));
3756 bool CWallet::GetDestData(const CTxDestination
&dest
, const std::string
&key
, std::string
*value
) const
3758 std::map
<CTxDestination
, CAddressBookData
>::const_iterator i
= mapAddressBook
.find(dest
);
3759 if(i
!= mapAddressBook
.end())
3761 CAddressBookData::StringMap::const_iterator j
= i
->second
.destdata
.find(key
);
3762 if(j
!= i
->second
.destdata
.end())
3772 std::vector
<std::string
> CWallet::GetDestValues(const std::string
& prefix
) const
3775 std::vector
<std::string
> values
;
3776 for (const auto& address
: mapAddressBook
) {
3777 for (const auto& data
: address
.second
.destdata
) {
3778 if (!data
.first
.compare(0, prefix
.size(), prefix
)) {
3779 values
.emplace_back(data
.second
);
3786 CWallet
* CWallet::CreateWalletFromFile(const std::string walletFile
)
3788 // needed to restore wallet transaction meta data after -zapwallettxes
3789 std::vector
<CWalletTx
> vWtx
;
3791 if (gArgs
.GetBoolArg("-zapwallettxes", false)) {
3792 uiInterface
.InitMessage(_("Zapping all transactions from wallet..."));
3794 std::unique_ptr
<CWalletDBWrapper
> dbw(new CWalletDBWrapper(&bitdb
, walletFile
));
3795 std::unique_ptr
<CWallet
> tempWallet(new CWallet(std::move(dbw
)));
3796 DBErrors nZapWalletRet
= tempWallet
->ZapWalletTx(vWtx
);
3797 if (nZapWalletRet
!= DB_LOAD_OK
) {
3798 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile
));
3803 uiInterface
.InitMessage(_("Loading wallet..."));
3805 int64_t nStart
= GetTimeMillis();
3806 bool fFirstRun
= true;
3807 std::unique_ptr
<CWalletDBWrapper
> dbw(new CWalletDBWrapper(&bitdb
, walletFile
));
3808 CWallet
*walletInstance
= new CWallet(std::move(dbw
));
3809 DBErrors nLoadWalletRet
= walletInstance
->LoadWallet(fFirstRun
);
3810 if (nLoadWalletRet
!= DB_LOAD_OK
)
3812 if (nLoadWalletRet
== DB_CORRUPT
) {
3813 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile
));
3816 else if (nLoadWalletRet
== DB_NONCRITICAL_ERROR
)
3818 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3819 " or address book entries might be missing or incorrect."),
3822 else if (nLoadWalletRet
== DB_TOO_NEW
) {
3823 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile
, _(PACKAGE_NAME
)));
3826 else if (nLoadWalletRet
== DB_NEED_REWRITE
)
3828 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME
)));
3832 InitError(strprintf(_("Error loading %s"), walletFile
));
3837 if (gArgs
.GetBoolArg("-upgradewallet", fFirstRun
))
3839 int nMaxVersion
= gArgs
.GetArg("-upgradewallet", 0);
3840 if (nMaxVersion
== 0) // the -upgradewallet without argument case
3842 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST
);
3843 nMaxVersion
= CLIENT_VERSION
;
3844 walletInstance
->SetMinVersion(FEATURE_LATEST
); // permanently upgrade the wallet immediately
3847 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion
);
3848 if (nMaxVersion
< walletInstance
->GetVersion())
3850 InitError(_("Cannot downgrade wallet"));
3853 walletInstance
->SetMaxVersion(nMaxVersion
);
3858 // ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
3859 if (!gArgs
.GetBoolArg("-usehd", true)) {
3860 InitError(strprintf(_("Error creating %s: You can't create non-HD wallets with this version."), walletFile
));
3863 walletInstance
->SetMinVersion(FEATURE_NO_DEFAULT_KEY
);
3865 // generate a new master key
3866 CPubKey masterPubKey
= walletInstance
->GenerateNewHDMasterKey();
3867 if (!walletInstance
->SetHDMasterKey(masterPubKey
))
3868 throw std::runtime_error(std::string(__func__
) + ": Storing master key failed");
3870 // Top up the keypool
3871 if (!walletInstance
->TopUpKeyPool()) {
3872 InitError(_("Unable to generate initial keys") += "\n");
3876 walletInstance
->SetBestChain(chainActive
.GetLocator());
3878 else if (gArgs
.IsArgSet("-usehd")) {
3879 bool useHD
= gArgs
.GetBoolArg("-usehd", true);
3880 if (walletInstance
->IsHDEnabled() && !useHD
) {
3881 InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile
));
3884 if (!walletInstance
->IsHDEnabled() && useHD
) {
3885 InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile
));
3890 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart
);
3892 RegisterValidationInterface(walletInstance
);
3894 // Try to top up keypool. No-op if the wallet is locked.
3895 walletInstance
->TopUpKeyPool();
3897 CBlockIndex
*pindexRescan
= chainActive
.Genesis();
3898 if (!gArgs
.GetBoolArg("-rescan", false))
3900 CWalletDB
walletdb(*walletInstance
->dbw
);
3901 CBlockLocator locator
;
3902 if (walletdb
.ReadBestBlock(locator
))
3903 pindexRescan
= FindForkInGlobalIndex(chainActive
, locator
);
3905 if (chainActive
.Tip() && chainActive
.Tip() != pindexRescan
)
3907 //We can't rescan beyond non-pruned blocks, stop and throw an error
3908 //this might happen if a user uses an old wallet within a pruned node
3909 // or if he ran -disablewallet for a longer time, then decided to re-enable
3912 CBlockIndex
*block
= chainActive
.Tip();
3913 while (block
&& block
->pprev
&& (block
->pprev
->nStatus
& BLOCK_HAVE_DATA
) && block
->pprev
->nTx
> 0 && pindexRescan
!= block
)
3914 block
= block
->pprev
;
3916 if (pindexRescan
!= block
) {
3917 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3922 uiInterface
.InitMessage(_("Rescanning..."));
3923 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive
.Height() - pindexRescan
->nHeight
, pindexRescan
->nHeight
);
3925 // No need to read and scan block if block was created before
3926 // our wallet birthday (as adjusted for block time variability)
3927 while (pindexRescan
&& walletInstance
->nTimeFirstKey
&& (pindexRescan
->GetBlockTime() < (walletInstance
->nTimeFirstKey
- TIMESTAMP_WINDOW
))) {
3928 pindexRescan
= chainActive
.Next(pindexRescan
);
3931 nStart
= GetTimeMillis();
3932 walletInstance
->ScanForWalletTransactions(pindexRescan
, true);
3933 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart
);
3934 walletInstance
->SetBestChain(chainActive
.GetLocator());
3935 walletInstance
->dbw
->IncrementUpdateCounter();
3937 // Restore wallet transaction metadata after -zapwallettxes=1
3938 if (gArgs
.GetBoolArg("-zapwallettxes", false) && gArgs
.GetArg("-zapwallettxes", "1") != "2")
3940 CWalletDB
walletdb(*walletInstance
->dbw
);
3942 for (const CWalletTx
& wtxOld
: vWtx
)
3944 uint256 hash
= wtxOld
.GetHash();
3945 std::map
<uint256
, CWalletTx
>::iterator mi
= walletInstance
->mapWallet
.find(hash
);
3946 if (mi
!= walletInstance
->mapWallet
.end())
3948 const CWalletTx
* copyFrom
= &wtxOld
;
3949 CWalletTx
* copyTo
= &mi
->second
;
3950 copyTo
->mapValue
= copyFrom
->mapValue
;
3951 copyTo
->vOrderForm
= copyFrom
->vOrderForm
;
3952 copyTo
->nTimeReceived
= copyFrom
->nTimeReceived
;
3953 copyTo
->nTimeSmart
= copyFrom
->nTimeSmart
;
3954 copyTo
->fFromMe
= copyFrom
->fFromMe
;
3955 copyTo
->strFromAccount
= copyFrom
->strFromAccount
;
3956 copyTo
->nOrderPos
= copyFrom
->nOrderPos
;
3957 walletdb
.WriteTx(*copyTo
);
3962 walletInstance
->SetBroadcastTransactions(gArgs
.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST
));
3965 LOCK(walletInstance
->cs_wallet
);
3966 LogPrintf("setKeyPool.size() = %u\n", walletInstance
->GetKeyPoolSize());
3967 LogPrintf("mapWallet.size() = %u\n", walletInstance
->mapWallet
.size());
3968 LogPrintf("mapAddressBook.size() = %u\n", walletInstance
->mapAddressBook
.size());
3971 return walletInstance
;
3974 std::atomic
<bool> CWallet::fFlushScheduled(false);
3976 void CWallet::postInitProcess(CScheduler
& scheduler
)
3978 // Add wallet transactions that aren't already in a block to mempool
3979 // Do this here as mempool requires genesis block to be loaded
3980 ReacceptWalletTransactions();
3982 // Run a thread to flush wallet periodically
3983 if (!CWallet::fFlushScheduled
.exchange(true)) {
3984 scheduler
.scheduleEvery(MaybeCompactWalletDB
, 500);
3988 bool CWallet::BackupWallet(const std::string
& strDest
)
3990 return dbw
->Backup(strDest
);
3993 CKeyPool::CKeyPool()
3999 CKeyPool::CKeyPool(const CPubKey
& vchPubKeyIn
, bool internalIn
)
4002 vchPubKey
= vchPubKeyIn
;
4003 fInternal
= internalIn
;
4006 CWalletKey::CWalletKey(int64_t nExpires
)
4008 nTimeCreated
= (nExpires
? GetTime() : 0);
4009 nTimeExpires
= nExpires
;
4012 void CMerkleTx::SetMerkleBranch(const CBlockIndex
* pindex
, int posInBlock
)
4014 // Update the tx's hashBlock
4015 hashBlock
= pindex
->GetBlockHash();
4017 // set the position of the transaction in the block
4018 nIndex
= posInBlock
;
4021 int CMerkleTx::GetDepthInMainChain(const CBlockIndex
* &pindexRet
) const
4026 AssertLockHeld(cs_main
);
4028 // Find the block it claims to be in
4029 BlockMap::iterator mi
= mapBlockIndex
.find(hashBlock
);
4030 if (mi
== mapBlockIndex
.end())
4032 CBlockIndex
* pindex
= (*mi
).second
;
4033 if (!pindex
|| !chainActive
.Contains(pindex
))
4037 return ((nIndex
== -1) ? (-1) : 1) * (chainActive
.Height() - pindex
->nHeight
+ 1);
4040 int CMerkleTx::GetBlocksToMaturity() const
4044 return std::max(0, (COINBASE_MATURITY
+1) - GetDepthInMainChain());
4048 bool CMerkleTx::AcceptToMemoryPool(const CAmount
& nAbsurdFee
, CValidationState
& state
)
4050 return ::AcceptToMemoryPool(mempool
, state
, tx
, nullptr /* pfMissingInputs */,
4051 nullptr /* plTxnReplaced */, false /* bypass_limits */, nAbsurdFee
);