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 CNoDestination
&none
) {}
117 const CWalletTx
* CWallet::GetWalletTx(const uint256
& hash
) const
120 std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.find(hash
);
121 if (it
== mapWallet
.end())
123 return &(it
->second
);
126 CPubKey
CWallet::GenerateNewKey(CWalletDB
&walletdb
, bool internal
)
128 AssertLockHeld(cs_wallet
); // mapKeyMetadata
129 bool fCompressed
= CanSupportFeature(FEATURE_COMPRPUBKEY
); // default to compressed public keys if we want 0.6.0 wallets
133 // Create new metadata
134 int64_t nCreationTime
= GetTime();
135 CKeyMetadata
metadata(nCreationTime
);
137 // use HD key derivation if HD was enabled during wallet creation
139 DeriveNewChildKey(walletdb
, metadata
, secret
, (CanSupportFeature(FEATURE_HD_SPLIT
) ? internal
: false));
141 secret
.MakeNewKey(fCompressed
);
144 // Compressed public keys were introduced in version 0.6.0
146 SetMinVersion(FEATURE_COMPRPUBKEY
);
149 CPubKey pubkey
= secret
.GetPubKey();
150 assert(secret
.VerifyPubKey(pubkey
));
152 mapKeyMetadata
[pubkey
.GetID()] = metadata
;
153 UpdateTimeFirstKey(nCreationTime
);
155 if (!AddKeyPubKeyWithDB(walletdb
, secret
, pubkey
)) {
156 throw std::runtime_error(std::string(__func__
) + ": AddKey failed");
161 void CWallet::DeriveNewChildKey(CWalletDB
&walletdb
, CKeyMetadata
& metadata
, CKey
& secret
, bool internal
)
163 // for now we use a fixed keypath scheme of m/0'/0'/k
164 CKey key
; //master key seed (256bit)
165 CExtKey masterKey
; //hd master key
166 CExtKey accountKey
; //key at m/0'
167 CExtKey chainChildKey
; //key at m/0'/0' (external) or m/0'/1' (internal)
168 CExtKey childKey
; //key at m/0'/0'/<n>'
170 // try to get the master key
171 if (!GetKey(hdChain
.masterKeyID
, key
))
172 throw std::runtime_error(std::string(__func__
) + ": Master key not found");
174 masterKey
.SetMaster(key
.begin(), key
.size());
177 // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
178 masterKey
.Derive(accountKey
, BIP32_HARDENED_KEY_LIMIT
);
180 // derive m/0'/0' (external chain) OR m/0'/1' (internal chain)
181 assert(internal
? CanSupportFeature(FEATURE_HD_SPLIT
) : true);
182 accountKey
.Derive(chainChildKey
, BIP32_HARDENED_KEY_LIMIT
+(internal
? 1 : 0));
184 // derive child key at next index, skip keys already known to the wallet
186 // always derive hardened keys
187 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
188 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
190 chainChildKey
.Derive(childKey
, hdChain
.nInternalChainCounter
| BIP32_HARDENED_KEY_LIMIT
);
191 metadata
.hdKeypath
= "m/0'/1'/" + std::to_string(hdChain
.nInternalChainCounter
) + "'";
192 hdChain
.nInternalChainCounter
++;
195 chainChildKey
.Derive(childKey
, hdChain
.nExternalChainCounter
| BIP32_HARDENED_KEY_LIMIT
);
196 metadata
.hdKeypath
= "m/0'/0'/" + std::to_string(hdChain
.nExternalChainCounter
) + "'";
197 hdChain
.nExternalChainCounter
++;
199 } while (HaveKey(childKey
.key
.GetPubKey().GetID()));
200 secret
= childKey
.key
;
201 metadata
.hdMasterKeyID
= hdChain
.masterKeyID
;
202 // update the chain model in the database
203 if (!walletdb
.WriteHDChain(hdChain
))
204 throw std::runtime_error(std::string(__func__
) + ": Writing HD chain model failed");
207 bool CWallet::AddKeyPubKeyWithDB(CWalletDB
&walletdb
, const CKey
& secret
, const CPubKey
&pubkey
)
209 AssertLockHeld(cs_wallet
); // mapKeyMetadata
211 // CCryptoKeyStore has no concept of wallet databases, but calls AddCryptedKey
212 // which is overridden below. To avoid flushes, the database handle is
213 // tunneled through to it.
214 bool needsDB
= !pwalletdbEncryption
;
216 pwalletdbEncryption
= &walletdb
;
218 if (!CCryptoKeyStore::AddKeyPubKey(secret
, pubkey
)) {
219 if (needsDB
) pwalletdbEncryption
= nullptr;
222 if (needsDB
) pwalletdbEncryption
= nullptr;
224 // check if we need to remove from watch-only
226 script
= GetScriptForDestination(pubkey
.GetID());
227 if (HaveWatchOnly(script
)) {
228 RemoveWatchOnly(script
);
230 script
= GetScriptForRawPubKey(pubkey
);
231 if (HaveWatchOnly(script
)) {
232 RemoveWatchOnly(script
);
236 return walletdb
.WriteKey(pubkey
,
238 mapKeyMetadata
[pubkey
.GetID()]);
243 bool CWallet::AddKeyPubKey(const CKey
& secret
, const CPubKey
&pubkey
)
245 CWalletDB
walletdb(*dbw
);
246 return CWallet::AddKeyPubKeyWithDB(walletdb
, secret
, pubkey
);
249 bool CWallet::AddCryptedKey(const CPubKey
&vchPubKey
,
250 const std::vector
<unsigned char> &vchCryptedSecret
)
252 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey
, vchCryptedSecret
))
256 if (pwalletdbEncryption
)
257 return pwalletdbEncryption
->WriteCryptedKey(vchPubKey
,
259 mapKeyMetadata
[vchPubKey
.GetID()]);
261 return CWalletDB(*dbw
).WriteCryptedKey(vchPubKey
,
263 mapKeyMetadata
[vchPubKey
.GetID()]);
267 bool CWallet::LoadKeyMetadata(const CTxDestination
& keyID
, const CKeyMetadata
&meta
)
269 AssertLockHeld(cs_wallet
); // mapKeyMetadata
270 UpdateTimeFirstKey(meta
.nCreateTime
);
271 mapKeyMetadata
[keyID
] = meta
;
275 bool CWallet::LoadCryptedKey(const CPubKey
&vchPubKey
, const std::vector
<unsigned char> &vchCryptedSecret
)
277 return CCryptoKeyStore::AddCryptedKey(vchPubKey
, vchCryptedSecret
);
281 * Update wallet first key creation time. This should be called whenever keys
282 * are added to the wallet, with the oldest key creation time.
284 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime
)
286 AssertLockHeld(cs_wallet
);
287 if (nCreateTime
<= 1) {
288 // Cannot determine birthday information, so set the wallet birthday to
289 // the beginning of time.
291 } else if (!nTimeFirstKey
|| nCreateTime
< nTimeFirstKey
) {
292 nTimeFirstKey
= nCreateTime
;
296 bool CWallet::AddCScript(const CScript
& redeemScript
)
298 if (!CCryptoKeyStore::AddCScript(redeemScript
))
300 return CWalletDB(*dbw
).WriteCScript(Hash160(redeemScript
), redeemScript
);
303 bool CWallet::LoadCScript(const CScript
& redeemScript
)
305 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
306 * that never can be redeemed. However, old wallets may still contain
307 * these. Do not add them to the wallet and warn. */
308 if (redeemScript
.size() > MAX_SCRIPT_ELEMENT_SIZE
)
310 std::string strAddr
= EncodeDestination(CScriptID(redeemScript
));
311 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",
312 __func__
, redeemScript
.size(), MAX_SCRIPT_ELEMENT_SIZE
, strAddr
);
316 return CCryptoKeyStore::AddCScript(redeemScript
);
319 bool CWallet::AddWatchOnly(const CScript
& dest
)
321 if (!CCryptoKeyStore::AddWatchOnly(dest
))
323 const CKeyMetadata
& meta
= mapKeyMetadata
[CScriptID(dest
)];
324 UpdateTimeFirstKey(meta
.nCreateTime
);
325 NotifyWatchonlyChanged(true);
326 return CWalletDB(*dbw
).WriteWatchOnly(dest
, meta
);
329 bool CWallet::AddWatchOnly(const CScript
& dest
, int64_t nCreateTime
)
331 mapKeyMetadata
[CScriptID(dest
)].nCreateTime
= nCreateTime
;
332 return AddWatchOnly(dest
);
335 bool CWallet::RemoveWatchOnly(const CScript
&dest
)
337 AssertLockHeld(cs_wallet
);
338 if (!CCryptoKeyStore::RemoveWatchOnly(dest
))
340 if (!HaveWatchOnly())
341 NotifyWatchonlyChanged(false);
342 if (!CWalletDB(*dbw
).EraseWatchOnly(dest
))
348 bool CWallet::LoadWatchOnly(const CScript
&dest
)
350 return CCryptoKeyStore::AddWatchOnly(dest
);
353 bool CWallet::Unlock(const SecureString
& strWalletPassphrase
)
356 CKeyingMaterial _vMasterKey
;
360 for (const MasterKeyMap::value_type
& pMasterKey
: mapMasterKeys
)
362 if(!crypter
.SetKeyFromPassphrase(strWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
))
364 if (!crypter
.Decrypt(pMasterKey
.second
.vchCryptedKey
, _vMasterKey
))
365 continue; // try another master key
366 if (CCryptoKeyStore::Unlock(_vMasterKey
))
373 bool CWallet::ChangeWalletPassphrase(const SecureString
& strOldWalletPassphrase
, const SecureString
& strNewWalletPassphrase
)
375 bool fWasLocked
= IsLocked();
382 CKeyingMaterial _vMasterKey
;
383 for (MasterKeyMap::value_type
& pMasterKey
: mapMasterKeys
)
385 if(!crypter
.SetKeyFromPassphrase(strOldWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
))
387 if (!crypter
.Decrypt(pMasterKey
.second
.vchCryptedKey
, _vMasterKey
))
389 if (CCryptoKeyStore::Unlock(_vMasterKey
))
391 int64_t nStartTime
= GetTimeMillis();
392 crypter
.SetKeyFromPassphrase(strNewWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
);
393 pMasterKey
.second
.nDeriveIterations
= pMasterKey
.second
.nDeriveIterations
* (100 / ((double)(GetTimeMillis() - nStartTime
)));
395 nStartTime
= GetTimeMillis();
396 crypter
.SetKeyFromPassphrase(strNewWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
);
397 pMasterKey
.second
.nDeriveIterations
= (pMasterKey
.second
.nDeriveIterations
+ pMasterKey
.second
.nDeriveIterations
* 100 / ((double)(GetTimeMillis() - nStartTime
))) / 2;
399 if (pMasterKey
.second
.nDeriveIterations
< 25000)
400 pMasterKey
.second
.nDeriveIterations
= 25000;
402 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey
.second
.nDeriveIterations
);
404 if (!crypter
.SetKeyFromPassphrase(strNewWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
))
406 if (!crypter
.Encrypt(_vMasterKey
, pMasterKey
.second
.vchCryptedKey
))
408 CWalletDB(*dbw
).WriteMasterKey(pMasterKey
.first
, pMasterKey
.second
);
419 void CWallet::SetBestChain(const CBlockLocator
& loc
)
421 CWalletDB
walletdb(*dbw
);
422 walletdb
.WriteBestBlock(loc
);
425 bool CWallet::SetMinVersion(enum WalletFeature nVersion
, CWalletDB
* pwalletdbIn
, bool fExplicit
)
427 LOCK(cs_wallet
); // nWalletVersion
428 if (nWalletVersion
>= nVersion
)
431 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
432 if (fExplicit
&& nVersion
> nWalletMaxVersion
)
433 nVersion
= FEATURE_LATEST
;
435 nWalletVersion
= nVersion
;
437 if (nVersion
> nWalletMaxVersion
)
438 nWalletMaxVersion
= nVersion
;
441 CWalletDB
* pwalletdb
= pwalletdbIn
? pwalletdbIn
: new CWalletDB(*dbw
);
442 if (nWalletVersion
> 40000)
443 pwalletdb
->WriteMinVersion(nWalletVersion
);
451 bool CWallet::SetMaxVersion(int nVersion
)
453 LOCK(cs_wallet
); // nWalletVersion, nWalletMaxVersion
454 // cannot downgrade below current version
455 if (nWalletVersion
> nVersion
)
458 nWalletMaxVersion
= nVersion
;
463 std::set
<uint256
> CWallet::GetConflicts(const uint256
& txid
) const
465 std::set
<uint256
> result
;
466 AssertLockHeld(cs_wallet
);
468 std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.find(txid
);
469 if (it
== mapWallet
.end())
471 const CWalletTx
& wtx
= it
->second
;
473 std::pair
<TxSpends::const_iterator
, TxSpends::const_iterator
> range
;
475 for (const CTxIn
& txin
: wtx
.tx
->vin
)
477 if (mapTxSpends
.count(txin
.prevout
) <= 1)
478 continue; // No conflict if zero or one spends
479 range
= mapTxSpends
.equal_range(txin
.prevout
);
480 for (TxSpends::const_iterator _it
= range
.first
; _it
!= range
.second
; ++_it
)
481 result
.insert(_it
->second
);
486 bool CWallet::HasWalletSpend(const uint256
& txid
) const
488 AssertLockHeld(cs_wallet
);
489 auto iter
= mapTxSpends
.lower_bound(COutPoint(txid
, 0));
490 return (iter
!= mapTxSpends
.end() && iter
->first
.hash
== txid
);
493 void CWallet::Flush(bool shutdown
)
495 dbw
->Flush(shutdown
);
498 void CWallet::SyncMetaData(std::pair
<TxSpends::iterator
, TxSpends::iterator
> range
)
500 // We want all the wallet transactions in range to have the same metadata as
501 // the oldest (smallest nOrderPos).
502 // So: find smallest nOrderPos:
504 int nMinOrderPos
= std::numeric_limits
<int>::max();
505 const CWalletTx
* copyFrom
= nullptr;
506 for (TxSpends::iterator it
= range
.first
; it
!= range
.second
; ++it
)
508 const uint256
& hash
= it
->second
;
509 int n
= mapWallet
[hash
].nOrderPos
;
510 if (n
< nMinOrderPos
)
513 copyFrom
= &mapWallet
[hash
];
516 // Now copy data from copyFrom to rest:
517 for (TxSpends::iterator it
= range
.first
; it
!= range
.second
; ++it
)
519 const uint256
& hash
= it
->second
;
520 CWalletTx
* copyTo
= &mapWallet
[hash
];
521 if (copyFrom
== copyTo
) continue;
522 if (!copyFrom
->IsEquivalentTo(*copyTo
)) continue;
523 copyTo
->mapValue
= copyFrom
->mapValue
;
524 copyTo
->vOrderForm
= copyFrom
->vOrderForm
;
525 // fTimeReceivedIsTxTime not copied on purpose
526 // nTimeReceived not copied on purpose
527 copyTo
->nTimeSmart
= copyFrom
->nTimeSmart
;
528 copyTo
->fFromMe
= copyFrom
->fFromMe
;
529 copyTo
->strFromAccount
= copyFrom
->strFromAccount
;
530 // nOrderPos not copied on purpose
531 // cached members not copied on purpose
536 * Outpoint is spent if any non-conflicted transaction
539 bool CWallet::IsSpent(const uint256
& hash
, unsigned int n
) const
541 const COutPoint
outpoint(hash
, n
);
542 std::pair
<TxSpends::const_iterator
, TxSpends::const_iterator
> range
;
543 range
= mapTxSpends
.equal_range(outpoint
);
545 for (TxSpends::const_iterator it
= range
.first
; it
!= range
.second
; ++it
)
547 const uint256
& wtxid
= it
->second
;
548 std::map
<uint256
, CWalletTx
>::const_iterator mit
= mapWallet
.find(wtxid
);
549 if (mit
!= mapWallet
.end()) {
550 int depth
= mit
->second
.GetDepthInMainChain();
551 if (depth
> 0 || (depth
== 0 && !mit
->second
.isAbandoned()))
552 return true; // Spent
558 void CWallet::AddToSpends(const COutPoint
& outpoint
, const uint256
& wtxid
)
560 mapTxSpends
.insert(std::make_pair(outpoint
, wtxid
));
562 std::pair
<TxSpends::iterator
, TxSpends::iterator
> range
;
563 range
= mapTxSpends
.equal_range(outpoint
);
568 void CWallet::AddToSpends(const uint256
& wtxid
)
570 auto it
= mapWallet
.find(wtxid
);
571 assert(it
!= mapWallet
.end());
572 CWalletTx
& thisTx
= it
->second
;
573 if (thisTx
.IsCoinBase()) // Coinbases don't spend anything!
576 for (const CTxIn
& txin
: thisTx
.tx
->vin
)
577 AddToSpends(txin
.prevout
, wtxid
);
580 bool CWallet::EncryptWallet(const SecureString
& strWalletPassphrase
)
585 CKeyingMaterial _vMasterKey
;
587 _vMasterKey
.resize(WALLET_CRYPTO_KEY_SIZE
);
588 GetStrongRandBytes(&_vMasterKey
[0], WALLET_CRYPTO_KEY_SIZE
);
590 CMasterKey kMasterKey
;
592 kMasterKey
.vchSalt
.resize(WALLET_CRYPTO_SALT_SIZE
);
593 GetStrongRandBytes(&kMasterKey
.vchSalt
[0], WALLET_CRYPTO_SALT_SIZE
);
596 int64_t nStartTime
= GetTimeMillis();
597 crypter
.SetKeyFromPassphrase(strWalletPassphrase
, kMasterKey
.vchSalt
, 25000, kMasterKey
.nDerivationMethod
);
598 kMasterKey
.nDeriveIterations
= 2500000 / ((double)(GetTimeMillis() - nStartTime
));
600 nStartTime
= GetTimeMillis();
601 crypter
.SetKeyFromPassphrase(strWalletPassphrase
, kMasterKey
.vchSalt
, kMasterKey
.nDeriveIterations
, kMasterKey
.nDerivationMethod
);
602 kMasterKey
.nDeriveIterations
= (kMasterKey
.nDeriveIterations
+ kMasterKey
.nDeriveIterations
* 100 / ((double)(GetTimeMillis() - nStartTime
))) / 2;
604 if (kMasterKey
.nDeriveIterations
< 25000)
605 kMasterKey
.nDeriveIterations
= 25000;
607 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey
.nDeriveIterations
);
609 if (!crypter
.SetKeyFromPassphrase(strWalletPassphrase
, kMasterKey
.vchSalt
, kMasterKey
.nDeriveIterations
, kMasterKey
.nDerivationMethod
))
611 if (!crypter
.Encrypt(_vMasterKey
, kMasterKey
.vchCryptedKey
))
616 mapMasterKeys
[++nMasterKeyMaxID
] = kMasterKey
;
617 assert(!pwalletdbEncryption
);
618 pwalletdbEncryption
= new CWalletDB(*dbw
);
619 if (!pwalletdbEncryption
->TxnBegin()) {
620 delete pwalletdbEncryption
;
621 pwalletdbEncryption
= nullptr;
624 pwalletdbEncryption
->WriteMasterKey(nMasterKeyMaxID
, kMasterKey
);
626 if (!EncryptKeys(_vMasterKey
))
628 pwalletdbEncryption
->TxnAbort();
629 delete pwalletdbEncryption
;
630 // We now probably have half of our keys encrypted in memory, and half not...
631 // die and let the user reload the unencrypted wallet.
635 // Encryption was introduced in version 0.4.0
636 SetMinVersion(FEATURE_WALLETCRYPT
, pwalletdbEncryption
, true);
638 if (!pwalletdbEncryption
->TxnCommit()) {
639 delete pwalletdbEncryption
;
640 // We now have keys encrypted in memory, but not on disk...
641 // die to avoid confusion and let the user reload the unencrypted wallet.
645 delete pwalletdbEncryption
;
646 pwalletdbEncryption
= nullptr;
649 Unlock(strWalletPassphrase
);
651 // if we are using HD, replace the HD master key (seed) with a new one
653 if (!SetHDMasterKey(GenerateNewHDMasterKey())) {
661 // Need to completely rewrite the wallet file; if we don't, bdb might keep
662 // bits of the unencrypted private key in slack space in the database file.
666 NotifyStatusChanged(this);
671 DBErrors
CWallet::ReorderTransactions()
674 CWalletDB
walletdb(*dbw
);
676 // Old wallets didn't have any defined order for transactions
677 // Probably a bad idea to change the output of this
679 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
680 typedef std::pair
<CWalletTx
*, CAccountingEntry
*> TxPair
;
681 typedef std::multimap
<int64_t, TxPair
> TxItems
;
684 for (std::map
<uint256
, CWalletTx
>::iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
686 CWalletTx
* wtx
= &((*it
).second
);
687 txByTime
.insert(std::make_pair(wtx
->nTimeReceived
, TxPair(wtx
, nullptr)));
689 std::list
<CAccountingEntry
> acentries
;
690 walletdb
.ListAccountCreditDebit("", acentries
);
691 for (CAccountingEntry
& entry
: acentries
)
693 txByTime
.insert(std::make_pair(entry
.nTime
, TxPair(nullptr, &entry
)));
697 std::vector
<int64_t> nOrderPosOffsets
;
698 for (TxItems::iterator it
= txByTime
.begin(); it
!= txByTime
.end(); ++it
)
700 CWalletTx
*const pwtx
= (*it
).second
.first
;
701 CAccountingEntry
*const pacentry
= (*it
).second
.second
;
702 int64_t& nOrderPos
= (pwtx
!= nullptr) ? pwtx
->nOrderPos
: pacentry
->nOrderPos
;
706 nOrderPos
= nOrderPosNext
++;
707 nOrderPosOffsets
.push_back(nOrderPos
);
711 if (!walletdb
.WriteTx(*pwtx
))
715 if (!walletdb
.WriteAccountingEntry(pacentry
->nEntryNo
, *pacentry
))
720 int64_t nOrderPosOff
= 0;
721 for (const int64_t& nOffsetStart
: nOrderPosOffsets
)
723 if (nOrderPos
>= nOffsetStart
)
726 nOrderPos
+= nOrderPosOff
;
727 nOrderPosNext
= std::max(nOrderPosNext
, nOrderPos
+ 1);
732 // Since we're changing the order, write it back
735 if (!walletdb
.WriteTx(*pwtx
))
739 if (!walletdb
.WriteAccountingEntry(pacentry
->nEntryNo
, *pacentry
))
743 walletdb
.WriteOrderPosNext(nOrderPosNext
);
748 int64_t CWallet::IncOrderPosNext(CWalletDB
*pwalletdb
)
750 AssertLockHeld(cs_wallet
); // nOrderPosNext
751 int64_t nRet
= nOrderPosNext
++;
753 pwalletdb
->WriteOrderPosNext(nOrderPosNext
);
755 CWalletDB(*dbw
).WriteOrderPosNext(nOrderPosNext
);
760 bool CWallet::AccountMove(std::string strFrom
, std::string strTo
, CAmount nAmount
, std::string strComment
)
762 CWalletDB
walletdb(*dbw
);
763 if (!walletdb
.TxnBegin())
766 int64_t nNow
= GetAdjustedTime();
769 CAccountingEntry debit
;
770 debit
.nOrderPos
= IncOrderPosNext(&walletdb
);
771 debit
.strAccount
= strFrom
;
772 debit
.nCreditDebit
= -nAmount
;
774 debit
.strOtherAccount
= strTo
;
775 debit
.strComment
= strComment
;
776 AddAccountingEntry(debit
, &walletdb
);
779 CAccountingEntry credit
;
780 credit
.nOrderPos
= IncOrderPosNext(&walletdb
);
781 credit
.strAccount
= strTo
;
782 credit
.nCreditDebit
= nAmount
;
784 credit
.strOtherAccount
= strFrom
;
785 credit
.strComment
= strComment
;
786 AddAccountingEntry(credit
, &walletdb
);
788 if (!walletdb
.TxnCommit())
794 bool CWallet::GetAccountPubkey(CPubKey
&pubKey
, std::string strAccount
, bool bForceNew
)
796 CWalletDB
walletdb(*dbw
);
799 walletdb
.ReadAccount(strAccount
, account
);
802 if (!account
.vchPubKey
.IsValid())
805 // Check if the current key has been used
806 CScript scriptPubKey
= GetScriptForDestination(account
.vchPubKey
.GetID());
807 for (std::map
<uint256
, CWalletTx
>::iterator it
= mapWallet
.begin();
808 it
!= mapWallet
.end() && account
.vchPubKey
.IsValid();
810 for (const CTxOut
& txout
: (*it
).second
.tx
->vout
)
811 if (txout
.scriptPubKey
== scriptPubKey
) {
818 // Generate a new key
820 if (!GetKeyFromPool(account
.vchPubKey
, false))
823 SetAddressBook(account
.vchPubKey
.GetID(), strAccount
, "receive");
824 walletdb
.WriteAccount(strAccount
, account
);
827 pubKey
= account
.vchPubKey
;
832 void CWallet::MarkDirty()
836 for (std::pair
<const uint256
, CWalletTx
>& item
: mapWallet
)
837 item
.second
.MarkDirty();
841 bool CWallet::MarkReplaced(const uint256
& originalHash
, const uint256
& newHash
)
845 auto mi
= mapWallet
.find(originalHash
);
847 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
848 assert(mi
!= mapWallet
.end());
850 CWalletTx
& wtx
= (*mi
).second
;
852 // Ensure for now that we're not overwriting data
853 assert(wtx
.mapValue
.count("replaced_by_txid") == 0);
855 wtx
.mapValue
["replaced_by_txid"] = newHash
.ToString();
857 CWalletDB
walletdb(*dbw
, "r+");
860 if (!walletdb
.WriteTx(wtx
)) {
861 LogPrintf("%s: Updating walletdb tx %s failed", __func__
, wtx
.GetHash().ToString());
865 NotifyTransactionChanged(this, originalHash
, CT_UPDATED
);
870 bool CWallet::AddToWallet(const CWalletTx
& wtxIn
, bool fFlushOnClose
)
874 CWalletDB
walletdb(*dbw
, "r+", fFlushOnClose
);
876 uint256 hash
= wtxIn
.GetHash();
878 // Inserts only if not already there, returns tx inserted or tx found
879 std::pair
<std::map
<uint256
, CWalletTx
>::iterator
, bool> ret
= mapWallet
.insert(std::make_pair(hash
, wtxIn
));
880 CWalletTx
& wtx
= (*ret
.first
).second
;
881 wtx
.BindWallet(this);
882 bool fInsertedNew
= ret
.second
;
885 wtx
.nTimeReceived
= GetAdjustedTime();
886 wtx
.nOrderPos
= IncOrderPosNext(&walletdb
);
887 wtxOrdered
.insert(std::make_pair(wtx
.nOrderPos
, TxPair(&wtx
, nullptr)));
888 wtx
.nTimeSmart
= ComputeTimeSmart(wtx
);
892 bool fUpdated
= false;
896 if (!wtxIn
.hashUnset() && wtxIn
.hashBlock
!= wtx
.hashBlock
)
898 wtx
.hashBlock
= wtxIn
.hashBlock
;
901 // If no longer abandoned, update
902 if (wtxIn
.hashBlock
.IsNull() && wtx
.isAbandoned())
904 wtx
.hashBlock
= wtxIn
.hashBlock
;
907 if (wtxIn
.nIndex
!= -1 && (wtxIn
.nIndex
!= wtx
.nIndex
))
909 wtx
.nIndex
= wtxIn
.nIndex
;
912 if (wtxIn
.fFromMe
&& wtxIn
.fFromMe
!= wtx
.fFromMe
)
914 wtx
.fFromMe
= wtxIn
.fFromMe
;
920 LogPrintf("AddToWallet %s %s%s\n", wtxIn
.GetHash().ToString(), (fInsertedNew
? "new" : ""), (fUpdated
? "update" : ""));
923 if (fInsertedNew
|| fUpdated
)
924 if (!walletdb
.WriteTx(wtx
))
927 // Break debit/credit balance caches:
930 // Notify UI of new or updated transaction
931 NotifyTransactionChanged(this, hash
, fInsertedNew
? CT_NEW
: CT_UPDATED
);
933 // notify an external script when a wallet transaction comes in or is updated
934 std::string strCmd
= gArgs
.GetArg("-walletnotify", "");
936 if ( !strCmd
.empty())
938 boost::replace_all(strCmd
, "%s", wtxIn
.GetHash().GetHex());
939 boost::thread
t(runCommand
, strCmd
); // thread runs free
945 bool CWallet::LoadToWallet(const CWalletTx
& wtxIn
)
947 uint256 hash
= wtxIn
.GetHash();
949 mapWallet
[hash
] = wtxIn
;
950 CWalletTx
& wtx
= mapWallet
[hash
];
951 wtx
.BindWallet(this);
952 wtxOrdered
.insert(std::make_pair(wtx
.nOrderPos
, TxPair(&wtx
, nullptr)));
954 for (const CTxIn
& txin
: wtx
.tx
->vin
) {
955 auto it
= mapWallet
.find(txin
.prevout
.hash
);
956 if (it
!= mapWallet
.end()) {
957 CWalletTx
& prevtx
= it
->second
;
958 if (prevtx
.nIndex
== -1 && !prevtx
.hashUnset()) {
959 MarkConflicted(prevtx
.hashBlock
, wtx
.GetHash());
968 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
969 * be set when the transaction was known to be included in a block. When
970 * pIndex == nullptr, then wallet state is not updated in AddToWallet, but
971 * notifications happen and cached balances are marked dirty.
973 * If fUpdate is true, existing transactions will be updated.
974 * TODO: One exception to this is that the abandoned state is cleared under the
975 * assumption that any further notification of a transaction that was considered
976 * abandoned is an indication that it is not safe to be considered abandoned.
977 * Abandoned state should probably be more carefully tracked via different
978 * posInBlock signals or by checking mempool presence when necessary.
980 bool CWallet::AddToWalletIfInvolvingMe(const CTransactionRef
& ptx
, const CBlockIndex
* pIndex
, int posInBlock
, bool fUpdate
)
982 const CTransaction
& tx
= *ptx
;
984 AssertLockHeld(cs_wallet
);
986 if (pIndex
!= nullptr) {
987 for (const CTxIn
& txin
: tx
.vin
) {
988 std::pair
<TxSpends::const_iterator
, TxSpends::const_iterator
> range
= mapTxSpends
.equal_range(txin
.prevout
);
989 while (range
.first
!= range
.second
) {
990 if (range
.first
->second
!= tx
.GetHash()) {
991 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
);
992 MarkConflicted(pIndex
->GetBlockHash(), range
.first
->second
);
999 bool fExisted
= mapWallet
.count(tx
.GetHash()) != 0;
1000 if (fExisted
&& !fUpdate
) return false;
1001 if (fExisted
|| IsMine(tx
) || IsFromMe(tx
))
1003 /* Check if any keys in the wallet keypool that were supposed to be unused
1004 * have appeared in a new transaction. If so, remove those keys from the keypool.
1005 * This can happen when restoring an old wallet backup that does not contain
1006 * the mostly recently created transactions from newer versions of the wallet.
1009 // loop though all outputs
1010 for (const CTxOut
& txout
: tx
.vout
) {
1011 // extract addresses and check if they match with an unused keypool key
1012 std::vector
<CKeyID
> vAffected
;
1013 CAffectedKeysVisitor(*this, vAffected
).Process(txout
.scriptPubKey
);
1014 for (const CKeyID
&keyid
: vAffected
) {
1015 std::map
<CKeyID
, int64_t>::const_iterator mi
= m_pool_key_to_index
.find(keyid
);
1016 if (mi
!= m_pool_key_to_index
.end()) {
1017 LogPrintf("%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__
);
1018 MarkReserveKeysAsUsed(mi
->second
);
1020 if (!TopUpKeyPool()) {
1021 LogPrintf("%s: Topping up keypool failed (locked wallet)\n", __func__
);
1027 CWalletTx
wtx(this, ptx
);
1029 // Get merkle branch if transaction was found in a block
1030 if (pIndex
!= nullptr)
1031 wtx
.SetMerkleBranch(pIndex
, posInBlock
);
1033 return AddToWallet(wtx
, false);
1039 bool CWallet::TransactionCanBeAbandoned(const uint256
& hashTx
) const
1041 LOCK2(cs_main
, cs_wallet
);
1042 const CWalletTx
* wtx
= GetWalletTx(hashTx
);
1043 return wtx
&& !wtx
->isAbandoned() && wtx
->GetDepthInMainChain() <= 0 && !wtx
->InMempool();
1046 bool CWallet::AbandonTransaction(const uint256
& hashTx
)
1048 LOCK2(cs_main
, cs_wallet
);
1050 CWalletDB
walletdb(*dbw
, "r+");
1052 std::set
<uint256
> todo
;
1053 std::set
<uint256
> done
;
1055 // Can't mark abandoned if confirmed or in mempool
1056 auto it
= mapWallet
.find(hashTx
);
1057 assert(it
!= mapWallet
.end());
1058 CWalletTx
& origtx
= it
->second
;
1059 if (origtx
.GetDepthInMainChain() > 0 || origtx
.InMempool()) {
1063 todo
.insert(hashTx
);
1065 while (!todo
.empty()) {
1066 uint256 now
= *todo
.begin();
1069 auto it
= mapWallet
.find(now
);
1070 assert(it
!= mapWallet
.end());
1071 CWalletTx
& wtx
= it
->second
;
1072 int currentconfirm
= wtx
.GetDepthInMainChain();
1073 // If the orig tx was not in block, none of its spends can be
1074 assert(currentconfirm
<= 0);
1075 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1076 if (currentconfirm
== 0 && !wtx
.isAbandoned()) {
1077 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1078 assert(!wtx
.InMempool());
1082 walletdb
.WriteTx(wtx
);
1083 NotifyTransactionChanged(this, wtx
.GetHash(), CT_UPDATED
);
1084 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1085 TxSpends::const_iterator iter
= mapTxSpends
.lower_bound(COutPoint(hashTx
, 0));
1086 while (iter
!= mapTxSpends
.end() && iter
->first
.hash
== now
) {
1087 if (!done
.count(iter
->second
)) {
1088 todo
.insert(iter
->second
);
1092 // If a transaction changes 'conflicted' state, that changes the balance
1093 // available of the outputs it spends. So force those to be recomputed
1094 for (const CTxIn
& txin
: wtx
.tx
->vin
)
1096 auto it
= mapWallet
.find(txin
.prevout
.hash
);
1097 if (it
!= mapWallet
.end()) {
1098 it
->second
.MarkDirty();
1107 void CWallet::MarkConflicted(const uint256
& hashBlock
, const uint256
& hashTx
)
1109 LOCK2(cs_main
, cs_wallet
);
1111 int conflictconfirms
= 0;
1112 if (mapBlockIndex
.count(hashBlock
)) {
1113 CBlockIndex
* pindex
= mapBlockIndex
[hashBlock
];
1114 if (chainActive
.Contains(pindex
)) {
1115 conflictconfirms
= -(chainActive
.Height() - pindex
->nHeight
+ 1);
1118 // If number of conflict confirms cannot be determined, this means
1119 // that the block is still unknown or not yet part of the main chain,
1120 // for example when loading the wallet during a reindex. Do nothing in that
1122 if (conflictconfirms
>= 0)
1125 // Do not flush the wallet here for performance reasons
1126 CWalletDB
walletdb(*dbw
, "r+", false);
1128 std::set
<uint256
> todo
;
1129 std::set
<uint256
> done
;
1131 todo
.insert(hashTx
);
1133 while (!todo
.empty()) {
1134 uint256 now
= *todo
.begin();
1137 auto it
= mapWallet
.find(now
);
1138 assert(it
!= mapWallet
.end());
1139 CWalletTx
& wtx
= it
->second
;
1140 int currentconfirm
= wtx
.GetDepthInMainChain();
1141 if (conflictconfirms
< currentconfirm
) {
1142 // Block is 'more conflicted' than current confirm; update.
1143 // Mark transaction as conflicted with this block.
1145 wtx
.hashBlock
= hashBlock
;
1147 walletdb
.WriteTx(wtx
);
1148 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1149 TxSpends::const_iterator iter
= mapTxSpends
.lower_bound(COutPoint(now
, 0));
1150 while (iter
!= mapTxSpends
.end() && iter
->first
.hash
== now
) {
1151 if (!done
.count(iter
->second
)) {
1152 todo
.insert(iter
->second
);
1156 // If a transaction changes 'conflicted' state, that changes the balance
1157 // available of the outputs it spends. So force those to be recomputed
1158 for (const CTxIn
& txin
: wtx
.tx
->vin
) {
1159 auto it
= mapWallet
.find(txin
.prevout
.hash
);
1160 if (it
!= mapWallet
.end()) {
1161 it
->second
.MarkDirty();
1168 void CWallet::SyncTransaction(const CTransactionRef
& ptx
, const CBlockIndex
*pindex
, int posInBlock
) {
1169 const CTransaction
& tx
= *ptx
;
1171 if (!AddToWalletIfInvolvingMe(ptx
, pindex
, posInBlock
, true))
1172 return; // Not one of ours
1174 // If a transaction changes 'conflicted' state, that changes the balance
1175 // available of the outputs it spends. So force those to be
1176 // recomputed, also:
1177 for (const CTxIn
& txin
: tx
.vin
) {
1178 auto it
= mapWallet
.find(txin
.prevout
.hash
);
1179 if (it
!= mapWallet
.end()) {
1180 it
->second
.MarkDirty();
1185 void CWallet::TransactionAddedToMempool(const CTransactionRef
& ptx
) {
1186 LOCK2(cs_main
, cs_wallet
);
1187 SyncTransaction(ptx
);
1190 void CWallet::BlockConnected(const std::shared_ptr
<const CBlock
>& pblock
, const CBlockIndex
*pindex
, const std::vector
<CTransactionRef
>& vtxConflicted
) {
1191 LOCK2(cs_main
, cs_wallet
);
1192 // TODO: Temporarily ensure that mempool removals are notified before
1193 // connected transactions. This shouldn't matter, but the abandoned
1194 // state of transactions in our wallet is currently cleared when we
1195 // receive another notification and there is a race condition where
1196 // notification of a connected conflict might cause an outside process
1197 // to abandon a transaction and then have it inadvertently cleared by
1198 // the notification that the conflicted transaction was evicted.
1200 for (const CTransactionRef
& ptx
: vtxConflicted
) {
1201 SyncTransaction(ptx
);
1203 for (size_t i
= 0; i
< pblock
->vtx
.size(); i
++) {
1204 SyncTransaction(pblock
->vtx
[i
], pindex
, i
);
1208 void CWallet::BlockDisconnected(const std::shared_ptr
<const CBlock
>& pblock
) {
1209 LOCK2(cs_main
, cs_wallet
);
1211 for (const CTransactionRef
& ptx
: pblock
->vtx
) {
1212 SyncTransaction(ptx
);
1218 isminetype
CWallet::IsMine(const CTxIn
&txin
) const
1222 std::map
<uint256
, CWalletTx
>::const_iterator mi
= mapWallet
.find(txin
.prevout
.hash
);
1223 if (mi
!= mapWallet
.end())
1225 const CWalletTx
& prev
= (*mi
).second
;
1226 if (txin
.prevout
.n
< prev
.tx
->vout
.size())
1227 return IsMine(prev
.tx
->vout
[txin
.prevout
.n
]);
1233 // Note that this function doesn't distinguish between a 0-valued input,
1234 // and a not-"is mine" (according to the filter) input.
1235 CAmount
CWallet::GetDebit(const CTxIn
&txin
, const isminefilter
& filter
) const
1239 std::map
<uint256
, CWalletTx
>::const_iterator mi
= mapWallet
.find(txin
.prevout
.hash
);
1240 if (mi
!= mapWallet
.end())
1242 const CWalletTx
& prev
= (*mi
).second
;
1243 if (txin
.prevout
.n
< prev
.tx
->vout
.size())
1244 if (IsMine(prev
.tx
->vout
[txin
.prevout
.n
]) & filter
)
1245 return prev
.tx
->vout
[txin
.prevout
.n
].nValue
;
1251 isminetype
CWallet::IsMine(const CTxOut
& txout
) const
1253 return ::IsMine(*this, txout
.scriptPubKey
);
1256 CAmount
CWallet::GetCredit(const CTxOut
& txout
, const isminefilter
& filter
) const
1258 if (!MoneyRange(txout
.nValue
))
1259 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1260 return ((IsMine(txout
) & filter
) ? txout
.nValue
: 0);
1263 bool CWallet::IsChange(const CTxOut
& txout
) const
1265 // TODO: fix handling of 'change' outputs. The assumption is that any
1266 // payment to a script that is ours, but is not in the address book
1267 // is change. That assumption is likely to break when we implement multisignature
1268 // wallets that return change back into a multi-signature-protected address;
1269 // a better way of identifying which outputs are 'the send' and which are
1270 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1271 // which output, if any, was change).
1272 if (::IsMine(*this, txout
.scriptPubKey
))
1274 CTxDestination address
;
1275 if (!ExtractDestination(txout
.scriptPubKey
, address
))
1279 if (!mapAddressBook
.count(address
))
1285 CAmount
CWallet::GetChange(const CTxOut
& txout
) const
1287 if (!MoneyRange(txout
.nValue
))
1288 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1289 return (IsChange(txout
) ? txout
.nValue
: 0);
1292 bool CWallet::IsMine(const CTransaction
& tx
) const
1294 for (const CTxOut
& txout
: tx
.vout
)
1300 bool CWallet::IsFromMe(const CTransaction
& tx
) const
1302 return (GetDebit(tx
, ISMINE_ALL
) > 0);
1305 CAmount
CWallet::GetDebit(const CTransaction
& tx
, const isminefilter
& filter
) const
1308 for (const CTxIn
& txin
: tx
.vin
)
1310 nDebit
+= GetDebit(txin
, filter
);
1311 if (!MoneyRange(nDebit
))
1312 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1317 bool CWallet::IsAllFromMe(const CTransaction
& tx
, const isminefilter
& filter
) const
1321 for (const CTxIn
& txin
: tx
.vin
)
1323 auto mi
= mapWallet
.find(txin
.prevout
.hash
);
1324 if (mi
== mapWallet
.end())
1325 return false; // any unknown inputs can't be from us
1327 const CWalletTx
& prev
= (*mi
).second
;
1329 if (txin
.prevout
.n
>= prev
.tx
->vout
.size())
1330 return false; // invalid input!
1332 if (!(IsMine(prev
.tx
->vout
[txin
.prevout
.n
]) & filter
))
1338 CAmount
CWallet::GetCredit(const CTransaction
& tx
, const isminefilter
& filter
) const
1340 CAmount nCredit
= 0;
1341 for (const CTxOut
& txout
: tx
.vout
)
1343 nCredit
+= GetCredit(txout
, filter
);
1344 if (!MoneyRange(nCredit
))
1345 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1350 CAmount
CWallet::GetChange(const CTransaction
& tx
) const
1352 CAmount nChange
= 0;
1353 for (const CTxOut
& txout
: tx
.vout
)
1355 nChange
+= GetChange(txout
);
1356 if (!MoneyRange(nChange
))
1357 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1362 CPubKey
CWallet::GenerateNewHDMasterKey()
1365 key
.MakeNewKey(true);
1367 int64_t nCreationTime
= GetTime();
1368 CKeyMetadata
metadata(nCreationTime
);
1370 // calculate the pubkey
1371 CPubKey pubkey
= key
.GetPubKey();
1372 assert(key
.VerifyPubKey(pubkey
));
1374 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1375 metadata
.hdKeypath
= "m";
1376 metadata
.hdMasterKeyID
= pubkey
.GetID();
1381 // mem store the metadata
1382 mapKeyMetadata
[pubkey
.GetID()] = metadata
;
1384 // write the key&metadata to the database
1385 if (!AddKeyPubKey(key
, pubkey
))
1386 throw std::runtime_error(std::string(__func__
) + ": AddKeyPubKey failed");
1392 bool CWallet::SetHDMasterKey(const CPubKey
& pubkey
)
1395 // store the keyid (hash160) together with
1396 // the child index counter in the database
1397 // as a hdchain object
1398 CHDChain newHdChain
;
1399 newHdChain
.nVersion
= CanSupportFeature(FEATURE_HD_SPLIT
) ? CHDChain::VERSION_HD_CHAIN_SPLIT
: CHDChain::VERSION_HD_BASE
;
1400 newHdChain
.masterKeyID
= pubkey
.GetID();
1401 SetHDChain(newHdChain
, false);
1406 bool CWallet::SetHDChain(const CHDChain
& chain
, bool memonly
)
1409 if (!memonly
&& !CWalletDB(*dbw
).WriteHDChain(chain
))
1410 throw std::runtime_error(std::string(__func__
) + ": writing chain failed");
1416 bool CWallet::IsHDEnabled() const
1418 return !hdChain
.masterKeyID
.IsNull();
1421 int64_t CWalletTx::GetTxTime() const
1423 int64_t n
= nTimeSmart
;
1424 return n
? n
: nTimeReceived
;
1427 int CWalletTx::GetRequestCount() const
1429 // Returns -1 if it wasn't being tracked
1432 LOCK(pwallet
->cs_wallet
);
1438 std::map
<uint256
, int>::const_iterator mi
= pwallet
->mapRequestCount
.find(hashBlock
);
1439 if (mi
!= pwallet
->mapRequestCount
.end())
1440 nRequests
= (*mi
).second
;
1445 // Did anyone request this transaction?
1446 std::map
<uint256
, int>::const_iterator mi
= pwallet
->mapRequestCount
.find(GetHash());
1447 if (mi
!= pwallet
->mapRequestCount
.end())
1449 nRequests
= (*mi
).second
;
1451 // How about the block it's in?
1452 if (nRequests
== 0 && !hashUnset())
1454 std::map
<uint256
, int>::const_iterator _mi
= pwallet
->mapRequestCount
.find(hashBlock
);
1455 if (_mi
!= pwallet
->mapRequestCount
.end())
1456 nRequests
= (*_mi
).second
;
1458 nRequests
= 1; // If it's in someone else's block it must have got out
1466 void CWalletTx::GetAmounts(std::list
<COutputEntry
>& listReceived
,
1467 std::list
<COutputEntry
>& listSent
, CAmount
& nFee
, std::string
& strSentAccount
, const isminefilter
& filter
) const
1470 listReceived
.clear();
1472 strSentAccount
= strFromAccount
;
1475 CAmount nDebit
= GetDebit(filter
);
1476 if (nDebit
> 0) // debit>0 means we signed/sent this transaction
1478 CAmount nValueOut
= tx
->GetValueOut();
1479 nFee
= nDebit
- nValueOut
;
1483 for (unsigned int i
= 0; i
< tx
->vout
.size(); ++i
)
1485 const CTxOut
& txout
= tx
->vout
[i
];
1486 isminetype fIsMine
= pwallet
->IsMine(txout
);
1487 // Only need to handle txouts if AT LEAST one of these is true:
1488 // 1) they debit from us (sent)
1489 // 2) the output is to us (received)
1492 // Don't report 'change' txouts
1493 if (pwallet
->IsChange(txout
))
1496 else if (!(fIsMine
& filter
))
1499 // In either case, we need to get the destination address
1500 CTxDestination address
;
1502 if (!ExtractDestination(txout
.scriptPubKey
, address
) && !txout
.scriptPubKey
.IsUnspendable())
1504 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1505 this->GetHash().ToString());
1506 address
= CNoDestination();
1509 COutputEntry output
= {address
, txout
.nValue
, (int)i
};
1511 // If we are debited by the transaction, add the output as a "sent" entry
1513 listSent
.push_back(output
);
1515 // If we are receiving the output, add it as a "received" entry
1516 if (fIsMine
& filter
)
1517 listReceived
.push_back(output
);
1523 * Scan active chain for relevant transactions after importing keys. This should
1524 * be called whenever new keys are added to the wallet, with the oldest key
1527 * @return Earliest timestamp that could be successfully scanned from. Timestamp
1528 * returned will be higher than startTime if relevant blocks could not be read.
1530 int64_t CWallet::RescanFromTime(int64_t startTime
, bool update
)
1532 AssertLockHeld(cs_main
);
1533 AssertLockHeld(cs_wallet
);
1535 // Find starting block. May be null if nCreateTime is greater than the
1536 // highest blockchain timestamp, in which case there is nothing that needs
1538 CBlockIndex
* const startBlock
= chainActive
.FindEarliestAtLeast(startTime
- TIMESTAMP_WINDOW
);
1539 LogPrintf("%s: Rescanning last %i blocks\n", __func__
, startBlock
? chainActive
.Height() - startBlock
->nHeight
+ 1 : 0);
1542 const CBlockIndex
* const failedBlock
= ScanForWalletTransactions(startBlock
, update
);
1544 return failedBlock
->GetBlockTimeMax() + TIMESTAMP_WINDOW
+ 1;
1551 * Scan the block chain (starting in pindexStart) for transactions
1552 * from or to us. If fUpdate is true, found transactions that already
1553 * exist in the wallet will be updated.
1555 * Returns null if scan was successful. Otherwise, if a complete rescan was not
1556 * possible (due to pruning or corruption), returns pointer to the most recent
1557 * block that could not be scanned.
1559 CBlockIndex
* CWallet::ScanForWalletTransactions(CBlockIndex
* pindexStart
, bool fUpdate
)
1561 int64_t nNow
= GetTime();
1562 const CChainParams
& chainParams
= Params();
1564 CBlockIndex
* pindex
= pindexStart
;
1565 CBlockIndex
* ret
= nullptr;
1567 LOCK2(cs_main
, cs_wallet
);
1568 fAbortRescan
= false;
1569 fScanningWallet
= true;
1571 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1572 double dProgressStart
= GuessVerificationProgress(chainParams
.TxData(), pindex
);
1573 double dProgressTip
= GuessVerificationProgress(chainParams
.TxData(), chainActive
.Tip());
1574 while (pindex
&& !fAbortRescan
)
1576 if (pindex
->nHeight
% 100 == 0 && dProgressTip
- dProgressStart
> 0.0)
1577 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams
.TxData(), pindex
) - dProgressStart
) / (dProgressTip
- dProgressStart
) * 100))));
1578 if (GetTime() >= nNow
+ 60) {
1580 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex
->nHeight
, GuessVerificationProgress(chainParams
.TxData(), pindex
));
1584 if (ReadBlockFromDisk(block
, pindex
, Params().GetConsensus())) {
1585 for (size_t posInBlock
= 0; posInBlock
< block
.vtx
.size(); ++posInBlock
) {
1586 AddToWalletIfInvolvingMe(block
.vtx
[posInBlock
], pindex
, posInBlock
, fUpdate
);
1591 pindex
= chainActive
.Next(pindex
);
1593 if (pindex
&& fAbortRescan
) {
1594 LogPrintf("Rescan aborted at block %d. Progress=%f\n", pindex
->nHeight
, GuessVerificationProgress(chainParams
.TxData(), pindex
));
1596 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1598 fScanningWallet
= false;
1603 void CWallet::ReacceptWalletTransactions()
1605 // If transactions aren't being broadcasted, don't let them into local mempool either
1606 if (!fBroadcastTransactions
)
1608 LOCK2(cs_main
, cs_wallet
);
1609 std::map
<int64_t, CWalletTx
*> mapSorted
;
1611 // Sort pending wallet transactions based on their initial wallet insertion order
1612 for (std::pair
<const uint256
, CWalletTx
>& item
: mapWallet
)
1614 const uint256
& wtxid
= item
.first
;
1615 CWalletTx
& wtx
= item
.second
;
1616 assert(wtx
.GetHash() == wtxid
);
1618 int nDepth
= wtx
.GetDepthInMainChain();
1620 if (!wtx
.IsCoinBase() && (nDepth
== 0 && !wtx
.isAbandoned())) {
1621 mapSorted
.insert(std::make_pair(wtx
.nOrderPos
, &wtx
));
1625 // Try to add wallet transactions to memory pool
1626 for (std::pair
<const int64_t, CWalletTx
*>& item
: mapSorted
)
1628 CWalletTx
& wtx
= *(item
.second
);
1631 CValidationState state
;
1632 wtx
.AcceptToMemoryPool(maxTxFee
, state
);
1636 bool CWalletTx::RelayWalletTransaction(CConnman
* connman
)
1638 assert(pwallet
->GetBroadcastTransactions());
1639 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1641 CValidationState state
;
1642 /* GetDepthInMainChain already catches known conflicts. */
1643 if (InMempool() || AcceptToMemoryPool(maxTxFee
, state
)) {
1644 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1646 CInv
inv(MSG_TX
, GetHash());
1647 connman
->ForEachNode([&inv
](CNode
* pnode
)
1649 pnode
->PushInventory(inv
);
1658 std::set
<uint256
> CWalletTx::GetConflicts() const
1660 std::set
<uint256
> result
;
1661 if (pwallet
!= nullptr)
1663 uint256 myHash
= GetHash();
1664 result
= pwallet
->GetConflicts(myHash
);
1665 result
.erase(myHash
);
1670 CAmount
CWalletTx::GetDebit(const isminefilter
& filter
) const
1672 if (tx
->vin
.empty())
1676 if(filter
& ISMINE_SPENDABLE
)
1679 debit
+= nDebitCached
;
1682 nDebitCached
= pwallet
->GetDebit(*this, ISMINE_SPENDABLE
);
1683 fDebitCached
= true;
1684 debit
+= nDebitCached
;
1687 if(filter
& ISMINE_WATCH_ONLY
)
1689 if(fWatchDebitCached
)
1690 debit
+= nWatchDebitCached
;
1693 nWatchDebitCached
= pwallet
->GetDebit(*this, ISMINE_WATCH_ONLY
);
1694 fWatchDebitCached
= true;
1695 debit
+= nWatchDebitCached
;
1701 CAmount
CWalletTx::GetCredit(const isminefilter
& filter
) const
1703 // Must wait until coinbase is safely deep enough in the chain before valuing it
1704 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1708 if (filter
& ISMINE_SPENDABLE
)
1710 // GetBalance can assume transactions in mapWallet won't change
1712 credit
+= nCreditCached
;
1715 nCreditCached
= pwallet
->GetCredit(*this, ISMINE_SPENDABLE
);
1716 fCreditCached
= true;
1717 credit
+= nCreditCached
;
1720 if (filter
& ISMINE_WATCH_ONLY
)
1722 if (fWatchCreditCached
)
1723 credit
+= nWatchCreditCached
;
1726 nWatchCreditCached
= pwallet
->GetCredit(*this, ISMINE_WATCH_ONLY
);
1727 fWatchCreditCached
= true;
1728 credit
+= nWatchCreditCached
;
1734 CAmount
CWalletTx::GetImmatureCredit(bool fUseCache
) const
1736 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1738 if (fUseCache
&& fImmatureCreditCached
)
1739 return nImmatureCreditCached
;
1740 nImmatureCreditCached
= pwallet
->GetCredit(*this, ISMINE_SPENDABLE
);
1741 fImmatureCreditCached
= true;
1742 return nImmatureCreditCached
;
1748 CAmount
CWalletTx::GetAvailableCredit(bool fUseCache
) const
1750 if (pwallet
== nullptr)
1753 // Must wait until coinbase is safely deep enough in the chain before valuing it
1754 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1757 if (fUseCache
&& fAvailableCreditCached
)
1758 return nAvailableCreditCached
;
1760 CAmount nCredit
= 0;
1761 uint256 hashTx
= GetHash();
1762 for (unsigned int i
= 0; i
< tx
->vout
.size(); i
++)
1764 if (!pwallet
->IsSpent(hashTx
, i
))
1766 const CTxOut
&txout
= tx
->vout
[i
];
1767 nCredit
+= pwallet
->GetCredit(txout
, ISMINE_SPENDABLE
);
1768 if (!MoneyRange(nCredit
))
1769 throw std::runtime_error(std::string(__func__
) + " : value out of range");
1773 nAvailableCreditCached
= nCredit
;
1774 fAvailableCreditCached
= true;
1778 CAmount
CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache
) const
1780 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1782 if (fUseCache
&& fImmatureWatchCreditCached
)
1783 return nImmatureWatchCreditCached
;
1784 nImmatureWatchCreditCached
= pwallet
->GetCredit(*this, ISMINE_WATCH_ONLY
);
1785 fImmatureWatchCreditCached
= true;
1786 return nImmatureWatchCreditCached
;
1792 CAmount
CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache
) const
1794 if (pwallet
== nullptr)
1797 // Must wait until coinbase is safely deep enough in the chain before valuing it
1798 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1801 if (fUseCache
&& fAvailableWatchCreditCached
)
1802 return nAvailableWatchCreditCached
;
1804 CAmount nCredit
= 0;
1805 for (unsigned int i
= 0; i
< tx
->vout
.size(); i
++)
1807 if (!pwallet
->IsSpent(GetHash(), i
))
1809 const CTxOut
&txout
= tx
->vout
[i
];
1810 nCredit
+= pwallet
->GetCredit(txout
, ISMINE_WATCH_ONLY
);
1811 if (!MoneyRange(nCredit
))
1812 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1816 nAvailableWatchCreditCached
= nCredit
;
1817 fAvailableWatchCreditCached
= true;
1821 CAmount
CWalletTx::GetChange() const
1824 return nChangeCached
;
1825 nChangeCached
= pwallet
->GetChange(*this);
1826 fChangeCached
= true;
1827 return nChangeCached
;
1830 bool CWalletTx::InMempool() const
1833 return mempool
.exists(GetHash());
1836 bool CWalletTx::IsTrusted() const
1838 // Quick answer in most cases
1839 if (!CheckFinalTx(*this))
1841 int nDepth
= GetDepthInMainChain();
1846 if (!bSpendZeroConfChange
|| !IsFromMe(ISMINE_ALL
)) // using wtx's cached debit
1849 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1853 // Trusted if all inputs are from us and are in the mempool:
1854 for (const CTxIn
& txin
: tx
->vin
)
1856 // Transactions not sent by us: not trusted
1857 const CWalletTx
* parent
= pwallet
->GetWalletTx(txin
.prevout
.hash
);
1858 if (parent
== nullptr)
1860 const CTxOut
& parentOut
= parent
->tx
->vout
[txin
.prevout
.n
];
1861 if (pwallet
->IsMine(parentOut
) != ISMINE_SPENDABLE
)
1867 bool CWalletTx::IsEquivalentTo(const CWalletTx
& _tx
) const
1869 CMutableTransaction tx1
= *this->tx
;
1870 CMutableTransaction tx2
= *_tx
.tx
;
1871 for (auto& txin
: tx1
.vin
) txin
.scriptSig
= CScript();
1872 for (auto& txin
: tx2
.vin
) txin
.scriptSig
= CScript();
1873 return CTransaction(tx1
) == CTransaction(tx2
);
1876 std::vector
<uint256
> CWallet::ResendWalletTransactionsBefore(int64_t nTime
, CConnman
* connman
)
1878 std::vector
<uint256
> result
;
1882 // Sort them in chronological order
1883 std::multimap
<unsigned int, CWalletTx
*> mapSorted
;
1884 for (std::pair
<const uint256
, CWalletTx
>& item
: mapWallet
)
1886 CWalletTx
& wtx
= item
.second
;
1887 // Don't rebroadcast if newer than nTime:
1888 if (wtx
.nTimeReceived
> nTime
)
1890 mapSorted
.insert(std::make_pair(wtx
.nTimeReceived
, &wtx
));
1892 for (std::pair
<const unsigned int, CWalletTx
*>& item
: mapSorted
)
1894 CWalletTx
& wtx
= *item
.second
;
1895 if (wtx
.RelayWalletTransaction(connman
))
1896 result
.push_back(wtx
.GetHash());
1901 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime
, CConnman
* connman
)
1903 // Do this infrequently and randomly to avoid giving away
1904 // that these are our transactions.
1905 if (GetTime() < nNextResend
|| !fBroadcastTransactions
)
1907 bool fFirst
= (nNextResend
== 0);
1908 nNextResend
= GetTime() + GetRand(30 * 60);
1912 // Only do it if there's been a new block since last time
1913 if (nBestBlockTime
< nLastResend
)
1915 nLastResend
= GetTime();
1917 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1919 std::vector
<uint256
> relayed
= ResendWalletTransactionsBefore(nBestBlockTime
-5*60, connman
);
1920 if (!relayed
.empty())
1921 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__
, relayed
.size());
1924 /** @} */ // end of mapWallet
1929 /** @defgroup Actions
1935 CAmount
CWallet::GetBalance() const
1939 LOCK2(cs_main
, cs_wallet
);
1940 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
1942 const CWalletTx
* pcoin
= &(*it
).second
;
1943 if (pcoin
->IsTrusted())
1944 nTotal
+= pcoin
->GetAvailableCredit();
1951 CAmount
CWallet::GetUnconfirmedBalance() const
1955 LOCK2(cs_main
, cs_wallet
);
1956 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
1958 const CWalletTx
* pcoin
= &(*it
).second
;
1959 if (!pcoin
->IsTrusted() && pcoin
->GetDepthInMainChain() == 0 && pcoin
->InMempool())
1960 nTotal
+= pcoin
->GetAvailableCredit();
1966 CAmount
CWallet::GetImmatureBalance() const
1970 LOCK2(cs_main
, cs_wallet
);
1971 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
1973 const CWalletTx
* pcoin
= &(*it
).second
;
1974 nTotal
+= pcoin
->GetImmatureCredit();
1980 CAmount
CWallet::GetWatchOnlyBalance() 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())
1989 nTotal
+= pcoin
->GetAvailableWatchOnlyCredit();
1996 CAmount
CWallet::GetUnconfirmedWatchOnlyBalance() const
2000 LOCK2(cs_main
, cs_wallet
);
2001 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
2003 const CWalletTx
* pcoin
= &(*it
).second
;
2004 if (!pcoin
->IsTrusted() && pcoin
->GetDepthInMainChain() == 0 && pcoin
->InMempool())
2005 nTotal
+= pcoin
->GetAvailableWatchOnlyCredit();
2011 CAmount
CWallet::GetImmatureWatchOnlyBalance() const
2015 LOCK2(cs_main
, cs_wallet
);
2016 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
2018 const CWalletTx
* pcoin
= &(*it
).second
;
2019 nTotal
+= pcoin
->GetImmatureWatchOnlyCredit();
2025 // Calculate total balance in a different way from GetBalance. The biggest
2026 // difference is that GetBalance sums up all unspent TxOuts paying to the
2027 // wallet, while this sums up both spent and unspent TxOuts paying to the
2028 // wallet, and then subtracts the values of TxIns spending from the wallet. This
2029 // also has fewer restrictions on which unconfirmed transactions are considered
2031 CAmount
CWallet::GetLegacyBalance(const isminefilter
& filter
, int minDepth
, const std::string
* account
) const
2033 LOCK2(cs_main
, cs_wallet
);
2035 CAmount balance
= 0;
2036 for (const auto& entry
: mapWallet
) {
2037 const CWalletTx
& wtx
= entry
.second
;
2038 const int depth
= wtx
.GetDepthInMainChain();
2039 if (depth
< 0 || !CheckFinalTx(*wtx
.tx
) || wtx
.GetBlocksToMaturity() > 0) {
2043 // Loop through tx outputs and add incoming payments. For outgoing txs,
2044 // treat change outputs specially, as part of the amount debited.
2045 CAmount debit
= wtx
.GetDebit(filter
);
2046 const bool outgoing
= debit
> 0;
2047 for (const CTxOut
& out
: wtx
.tx
->vout
) {
2048 if (outgoing
&& IsChange(out
)) {
2049 debit
-= out
.nValue
;
2050 } else if (IsMine(out
) & filter
&& depth
>= minDepth
&& (!account
|| *account
== GetAccountName(out
.scriptPubKey
))) {
2051 balance
+= out
.nValue
;
2055 // For outgoing txs, subtract amount debited.
2056 if (outgoing
&& (!account
|| *account
== wtx
.strFromAccount
)) {
2062 balance
+= CWalletDB(*dbw
).GetAccountCreditDebit(*account
);
2068 CAmount
CWallet::GetAvailableBalance(const CCoinControl
* coinControl
) const
2070 LOCK2(cs_main
, cs_wallet
);
2072 CAmount balance
= 0;
2073 std::vector
<COutput
> vCoins
;
2074 AvailableCoins(vCoins
, true, coinControl
);
2075 for (const COutput
& out
: vCoins
) {
2076 if (out
.fSpendable
) {
2077 balance
+= out
.tx
->tx
->vout
[out
.i
].nValue
;
2083 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
2088 LOCK2(cs_main
, cs_wallet
);
2092 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
2094 const uint256
& wtxid
= it
->first
;
2095 const CWalletTx
* pcoin
= &(*it
).second
;
2097 if (!CheckFinalTx(*pcoin
))
2100 if (pcoin
->IsCoinBase() && pcoin
->GetBlocksToMaturity() > 0)
2103 int nDepth
= pcoin
->GetDepthInMainChain();
2107 // We should not consider coins which aren't at least in our mempool
2108 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2109 if (nDepth
== 0 && !pcoin
->InMempool())
2112 bool safeTx
= pcoin
->IsTrusted();
2114 // We should not consider coins from transactions that are replacing
2115 // other transactions.
2117 // Example: There is a transaction A which is replaced by bumpfee
2118 // transaction B. In this case, we want to prevent creation of
2119 // a transaction B' which spends an output of B.
2121 // Reason: If transaction A were initially confirmed, transactions B
2122 // and B' would no longer be valid, so the user would have to create
2123 // a new transaction C to replace B'. However, in the case of a
2124 // one-block reorg, transactions B' and C might BOTH be accepted,
2125 // when the user only wanted one of them. Specifically, there could
2126 // be a 1-block reorg away from the chain where transactions A and C
2127 // were accepted to another chain where B, B', and C were all
2129 if (nDepth
== 0 && pcoin
->mapValue
.count("replaces_txid")) {
2133 // Similarly, we should not consider coins from transactions that
2134 // have been replaced. In the example above, we would want to prevent
2135 // creation of a transaction A' spending an output of A, because if
2136 // transaction B were initially confirmed, conflicting with A and
2137 // A', we wouldn't want to the user to create a transaction D
2138 // intending to replace A', but potentially resulting in a scenario
2139 // where A, A', and D could all be accepted (instead of just B and
2140 // D, or just A and A' like the user would want).
2141 if (nDepth
== 0 && pcoin
->mapValue
.count("replaced_by_txid")) {
2145 if (fOnlySafe
&& !safeTx
) {
2149 if (nDepth
< nMinDepth
|| nDepth
> nMaxDepth
)
2152 for (unsigned int i
= 0; i
< pcoin
->tx
->vout
.size(); i
++) {
2153 if (pcoin
->tx
->vout
[i
].nValue
< nMinimumAmount
|| pcoin
->tx
->vout
[i
].nValue
> nMaximumAmount
)
2156 if (coinControl
&& coinControl
->HasSelected() && !coinControl
->fAllowOtherInputs
&& !coinControl
->IsSelected(COutPoint((*it
).first
, i
)))
2159 if (IsLockedCoin((*it
).first
, i
))
2162 if (IsSpent(wtxid
, i
))
2165 isminetype mine
= IsMine(pcoin
->tx
->vout
[i
]);
2167 if (mine
== ISMINE_NO
) {
2171 bool fSpendableIn
= ((mine
& ISMINE_SPENDABLE
) != ISMINE_NO
) || (coinControl
&& coinControl
->fAllowWatchOnly
&& (mine
& ISMINE_WATCH_SOLVABLE
) != ISMINE_NO
);
2172 bool fSolvableIn
= (mine
& (ISMINE_SPENDABLE
| ISMINE_WATCH_SOLVABLE
)) != ISMINE_NO
;
2174 vCoins
.push_back(COutput(pcoin
, i
, nDepth
, fSpendableIn
, fSolvableIn
, safeTx
));
2176 // Checks the sum amount of all UTXO's.
2177 if (nMinimumSumAmount
!= MAX_MONEY
) {
2178 nTotal
+= pcoin
->tx
->vout
[i
].nValue
;
2180 if (nTotal
>= nMinimumSumAmount
) {
2185 // Checks the maximum number of UTXO's.
2186 if (nMaximumCount
> 0 && vCoins
.size() >= nMaximumCount
) {
2194 std::map
<CTxDestination
, std::vector
<COutput
>> CWallet::ListCoins() const
2196 // TODO: Add AssertLockHeld(cs_wallet) here.
2198 // Because the return value from this function contains pointers to
2199 // CWalletTx objects, callers to this function really should acquire the
2200 // cs_wallet lock before calling it. However, the current caller doesn't
2201 // acquire this lock yet. There was an attempt to add the missing lock in
2202 // https://github.com/bitcoin/bitcoin/pull/10340, but that change has been
2203 // postponed until after https://github.com/bitcoin/bitcoin/pull/10244 to
2204 // avoid adding some extra complexity to the Qt code.
2206 std::map
<CTxDestination
, std::vector
<COutput
>> result
;
2208 std::vector
<COutput
> availableCoins
;
2209 AvailableCoins(availableCoins
);
2211 LOCK2(cs_main
, cs_wallet
);
2212 for (auto& coin
: availableCoins
) {
2213 CTxDestination address
;
2214 if (coin
.fSpendable
&&
2215 ExtractDestination(FindNonChangeParentOutput(*coin
.tx
->tx
, coin
.i
).scriptPubKey
, address
)) {
2216 result
[address
].emplace_back(std::move(coin
));
2220 std::vector
<COutPoint
> lockedCoins
;
2221 ListLockedCoins(lockedCoins
);
2222 for (const auto& output
: lockedCoins
) {
2223 auto it
= mapWallet
.find(output
.hash
);
2224 if (it
!= mapWallet
.end()) {
2225 int depth
= it
->second
.GetDepthInMainChain();
2226 if (depth
>= 0 && output
.n
< it
->second
.tx
->vout
.size() &&
2227 IsMine(it
->second
.tx
->vout
[output
.n
]) == ISMINE_SPENDABLE
) {
2228 CTxDestination address
;
2229 if (ExtractDestination(FindNonChangeParentOutput(*it
->second
.tx
, output
.n
).scriptPubKey
, address
)) {
2230 result
[address
].emplace_back(
2231 &it
->second
, output
.n
, depth
, true /* spendable */, true /* solvable */, false /* safe */);
2240 const CTxOut
& CWallet::FindNonChangeParentOutput(const CTransaction
& tx
, int output
) const
2242 const CTransaction
* ptx
= &tx
;
2244 while (IsChange(ptx
->vout
[n
]) && ptx
->vin
.size() > 0) {
2245 const COutPoint
& prevout
= ptx
->vin
[0].prevout
;
2246 auto it
= mapWallet
.find(prevout
.hash
);
2247 if (it
== mapWallet
.end() || it
->second
.tx
->vout
.size() <= prevout
.n
||
2248 !IsMine(it
->second
.tx
->vout
[prevout
.n
])) {
2251 ptx
= it
->second
.tx
.get();
2254 return ptx
->vout
[n
];
2257 static void ApproximateBestSubset(const std::vector
<CInputCoin
>& vValue
, const CAmount
& nTotalLower
, const CAmount
& nTargetValue
,
2258 std::vector
<char>& vfBest
, CAmount
& nBest
, int iterations
= 1000)
2260 std::vector
<char> vfIncluded
;
2262 vfBest
.assign(vValue
.size(), true);
2263 nBest
= nTotalLower
;
2265 FastRandomContext insecure_rand
;
2267 for (int nRep
= 0; nRep
< iterations
&& nBest
!= nTargetValue
; nRep
++)
2269 vfIncluded
.assign(vValue
.size(), false);
2271 bool fReachedTarget
= false;
2272 for (int nPass
= 0; nPass
< 2 && !fReachedTarget
; nPass
++)
2274 for (unsigned int i
= 0; i
< vValue
.size(); i
++)
2276 //The solver here uses a randomized algorithm,
2277 //the randomness serves no real security purpose but is just
2278 //needed to prevent degenerate behavior and it is important
2279 //that the rng is fast. We do not use a constant random sequence,
2280 //because there may be some privacy improvement by making
2281 //the selection random.
2282 if (nPass
== 0 ? insecure_rand
.randbool() : !vfIncluded
[i
])
2284 nTotal
+= vValue
[i
].txout
.nValue
;
2285 vfIncluded
[i
] = true;
2286 if (nTotal
>= nTargetValue
)
2288 fReachedTarget
= true;
2292 vfBest
= vfIncluded
;
2294 nTotal
-= vValue
[i
].txout
.nValue
;
2295 vfIncluded
[i
] = false;
2303 bool CWallet::SelectCoinsMinConf(const CAmount
& nTargetValue
, const int nConfMine
, const int nConfTheirs
, const uint64_t nMaxAncestors
, std::vector
<COutput
> vCoins
,
2304 std::set
<CInputCoin
>& setCoinsRet
, CAmount
& nValueRet
) const
2306 setCoinsRet
.clear();
2309 // List of values less than target
2310 boost::optional
<CInputCoin
> coinLowestLarger
;
2311 std::vector
<CInputCoin
> vValue
;
2312 CAmount nTotalLower
= 0;
2314 random_shuffle(vCoins
.begin(), vCoins
.end(), GetRandInt
);
2316 for (const COutput
&output
: vCoins
)
2318 if (!output
.fSpendable
)
2321 const CWalletTx
*pcoin
= output
.tx
;
2323 if (output
.nDepth
< (pcoin
->IsFromMe(ISMINE_ALL
) ? nConfMine
: nConfTheirs
))
2326 if (!mempool
.TransactionWithinChainLimit(pcoin
->GetHash(), nMaxAncestors
))
2331 CInputCoin coin
= CInputCoin(pcoin
, i
);
2333 if (coin
.txout
.nValue
== nTargetValue
)
2335 setCoinsRet
.insert(coin
);
2336 nValueRet
+= coin
.txout
.nValue
;
2339 else if (coin
.txout
.nValue
< nTargetValue
+ MIN_CHANGE
)
2341 vValue
.push_back(coin
);
2342 nTotalLower
+= coin
.txout
.nValue
;
2344 else if (!coinLowestLarger
|| coin
.txout
.nValue
< coinLowestLarger
->txout
.nValue
)
2346 coinLowestLarger
= coin
;
2350 if (nTotalLower
== nTargetValue
)
2352 for (const auto& input
: vValue
)
2354 setCoinsRet
.insert(input
);
2355 nValueRet
+= input
.txout
.nValue
;
2360 if (nTotalLower
< nTargetValue
)
2362 if (!coinLowestLarger
)
2364 setCoinsRet
.insert(coinLowestLarger
.get());
2365 nValueRet
+= coinLowestLarger
->txout
.nValue
;
2369 // Solve subset sum by stochastic approximation
2370 std::sort(vValue
.begin(), vValue
.end(), CompareValueOnly());
2371 std::reverse(vValue
.begin(), vValue
.end());
2372 std::vector
<char> vfBest
;
2375 ApproximateBestSubset(vValue
, nTotalLower
, nTargetValue
, vfBest
, nBest
);
2376 if (nBest
!= nTargetValue
&& nTotalLower
>= nTargetValue
+ MIN_CHANGE
)
2377 ApproximateBestSubset(vValue
, nTotalLower
, nTargetValue
+ MIN_CHANGE
, vfBest
, nBest
);
2379 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2380 // or the next bigger coin is closer), return the bigger coin
2381 if (coinLowestLarger
&&
2382 ((nBest
!= nTargetValue
&& nBest
< nTargetValue
+ MIN_CHANGE
) || coinLowestLarger
->txout
.nValue
<= nBest
))
2384 setCoinsRet
.insert(coinLowestLarger
.get());
2385 nValueRet
+= coinLowestLarger
->txout
.nValue
;
2388 for (unsigned int i
= 0; i
< vValue
.size(); i
++)
2391 setCoinsRet
.insert(vValue
[i
]);
2392 nValueRet
+= vValue
[i
].txout
.nValue
;
2395 if (LogAcceptCategory(BCLog::SELECTCOINS
)) {
2396 LogPrint(BCLog::SELECTCOINS
, "SelectCoins() best subset: ");
2397 for (unsigned int i
= 0; i
< vValue
.size(); i
++) {
2399 LogPrint(BCLog::SELECTCOINS
, "%s ", FormatMoney(vValue
[i
].txout
.nValue
));
2402 LogPrint(BCLog::SELECTCOINS
, "total %s\n", FormatMoney(nBest
));
2409 bool CWallet::SelectCoins(const std::vector
<COutput
>& vAvailableCoins
, const CAmount
& nTargetValue
, std::set
<CInputCoin
>& setCoinsRet
, CAmount
& nValueRet
, const CCoinControl
* coinControl
) const
2411 std::vector
<COutput
> vCoins(vAvailableCoins
);
2413 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2414 if (coinControl
&& coinControl
->HasSelected() && !coinControl
->fAllowOtherInputs
)
2416 for (const COutput
& out
: vCoins
)
2418 if (!out
.fSpendable
)
2420 nValueRet
+= out
.tx
->tx
->vout
[out
.i
].nValue
;
2421 setCoinsRet
.insert(CInputCoin(out
.tx
, out
.i
));
2423 return (nValueRet
>= nTargetValue
);
2426 // calculate value from preset inputs and store them
2427 std::set
<CInputCoin
> setPresetCoins
;
2428 CAmount nValueFromPresetInputs
= 0;
2430 std::vector
<COutPoint
> vPresetInputs
;
2432 coinControl
->ListSelected(vPresetInputs
);
2433 for (const COutPoint
& outpoint
: vPresetInputs
)
2435 std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.find(outpoint
.hash
);
2436 if (it
!= mapWallet
.end())
2438 const CWalletTx
* pcoin
= &it
->second
;
2439 // Clearly invalid input, fail
2440 if (pcoin
->tx
->vout
.size() <= outpoint
.n
)
2442 nValueFromPresetInputs
+= pcoin
->tx
->vout
[outpoint
.n
].nValue
;
2443 setPresetCoins
.insert(CInputCoin(pcoin
, outpoint
.n
));
2445 return false; // TODO: Allow non-wallet inputs
2448 // remove preset inputs from vCoins
2449 for (std::vector
<COutput
>::iterator it
= vCoins
.begin(); it
!= vCoins
.end() && coinControl
&& coinControl
->HasSelected();)
2451 if (setPresetCoins
.count(CInputCoin(it
->tx
, it
->i
)))
2452 it
= vCoins
.erase(it
);
2457 size_t nMaxChainLength
= std::min(gArgs
.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT
), gArgs
.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT
));
2458 bool fRejectLongChains
= gArgs
.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS
);
2460 bool res
= nTargetValue
<= nValueFromPresetInputs
||
2461 SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 1, 6, 0, vCoins
, setCoinsRet
, nValueRet
) ||
2462 SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 1, 1, 0, vCoins
, setCoinsRet
, nValueRet
) ||
2463 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, 2, vCoins
, setCoinsRet
, nValueRet
)) ||
2464 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, std::min((size_t)4, nMaxChainLength
/3), vCoins
, setCoinsRet
, nValueRet
)) ||
2465 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, nMaxChainLength
/2, vCoins
, setCoinsRet
, nValueRet
)) ||
2466 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, nMaxChainLength
, vCoins
, setCoinsRet
, nValueRet
)) ||
2467 (bSpendZeroConfChange
&& !fRejectLongChains
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, std::numeric_limits
<uint64_t>::max(), vCoins
, setCoinsRet
, nValueRet
));
2469 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2470 setCoinsRet
.insert(setPresetCoins
.begin(), setPresetCoins
.end());
2472 // add preset inputs to the total value selected
2473 nValueRet
+= nValueFromPresetInputs
;
2478 bool CWallet::SignTransaction(CMutableTransaction
&tx
)
2480 AssertLockHeld(cs_wallet
); // mapWallet
2483 CTransaction
txNewConst(tx
);
2485 for (const auto& input
: tx
.vin
) {
2486 std::map
<uint256
, CWalletTx
>::const_iterator mi
= mapWallet
.find(input
.prevout
.hash
);
2487 if(mi
== mapWallet
.end() || input
.prevout
.n
>= mi
->second
.tx
->vout
.size()) {
2490 const CScript
& scriptPubKey
= mi
->second
.tx
->vout
[input
.prevout
.n
].scriptPubKey
;
2491 const CAmount
& amount
= mi
->second
.tx
->vout
[input
.prevout
.n
].nValue
;
2492 SignatureData sigdata
;
2493 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst
, nIn
, amount
, SIGHASH_ALL
), scriptPubKey
, sigdata
)) {
2496 UpdateTransaction(tx
, nIn
, sigdata
);
2502 bool CWallet::FundTransaction(CMutableTransaction
& tx
, CAmount
& nFeeRet
, int& nChangePosInOut
, std::string
& strFailReason
, bool lockUnspents
, const std::set
<int>& setSubtractFeeFromOutputs
, CCoinControl coinControl
)
2504 std::vector
<CRecipient
> vecSend
;
2506 // Turn the txout set into a CRecipient vector
2507 for (size_t idx
= 0; idx
< tx
.vout
.size(); idx
++)
2509 const CTxOut
& txOut
= tx
.vout
[idx
];
2510 CRecipient recipient
= {txOut
.scriptPubKey
, txOut
.nValue
, setSubtractFeeFromOutputs
.count(idx
) == 1};
2511 vecSend
.push_back(recipient
);
2514 coinControl
.fAllowOtherInputs
= true;
2516 for (const CTxIn
& txin
: tx
.vin
)
2517 coinControl
.Select(txin
.prevout
);
2519 CReserveKey
reservekey(this);
2521 if (!CreateTransaction(vecSend
, wtx
, reservekey
, nFeeRet
, nChangePosInOut
, strFailReason
, coinControl
, false)) {
2525 if (nChangePosInOut
!= -1) {
2526 tx
.vout
.insert(tx
.vout
.begin() + nChangePosInOut
, wtx
.tx
->vout
[nChangePosInOut
]);
2527 // we don't have the normal Create/Commit cycle, and don't want to risk reusing change,
2528 // so just remove the key from the keypool here.
2529 reservekey
.KeepKey();
2532 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2533 for (unsigned int idx
= 0; idx
< tx
.vout
.size(); idx
++)
2534 tx
.vout
[idx
].nValue
= wtx
.tx
->vout
[idx
].nValue
;
2536 // Add new txins (keeping original txin scriptSig/order)
2537 for (const CTxIn
& txin
: wtx
.tx
->vin
)
2539 if (!coinControl
.IsSelected(txin
.prevout
))
2541 tx
.vin
.push_back(txin
);
2545 LOCK2(cs_main
, cs_wallet
);
2546 LockCoin(txin
.prevout
);
2555 bool CWallet::CreateTransaction(const std::vector
<CRecipient
>& vecSend
, CWalletTx
& wtxNew
, CReserveKey
& reservekey
, CAmount
& nFeeRet
,
2556 int& nChangePosInOut
, std::string
& strFailReason
, const CCoinControl
& coin_control
, bool sign
)
2559 int nChangePosRequest
= nChangePosInOut
;
2560 unsigned int nSubtractFeeFromAmount
= 0;
2561 for (const auto& recipient
: vecSend
)
2563 if (nValue
< 0 || recipient
.nAmount
< 0)
2565 strFailReason
= _("Transaction amounts must not be negative");
2568 nValue
+= recipient
.nAmount
;
2570 if (recipient
.fSubtractFeeFromAmount
)
2571 nSubtractFeeFromAmount
++;
2573 if (vecSend
.empty())
2575 strFailReason
= _("Transaction must have at least one recipient");
2579 wtxNew
.fTimeReceivedIsTxTime
= true;
2580 wtxNew
.BindWallet(this);
2581 CMutableTransaction txNew
;
2583 // Discourage fee sniping.
2585 // For a large miner the value of the transactions in the best block and
2586 // the mempool can exceed the cost of deliberately attempting to mine two
2587 // blocks to orphan the current best block. By setting nLockTime such that
2588 // only the next block can include the transaction, we discourage this
2589 // practice as the height restricted and limited blocksize gives miners
2590 // considering fee sniping fewer options for pulling off this attack.
2592 // A simple way to think about this is from the wallet's point of view we
2593 // always want the blockchain to move forward. By setting nLockTime this
2594 // way we're basically making the statement that we only want this
2595 // transaction to appear in the next block; we don't want to potentially
2596 // encourage reorgs by allowing transactions to appear at lower heights
2597 // than the next block in forks of the best chain.
2599 // Of course, the subsidy is high enough, and transaction volume low
2600 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2601 // now we ensure code won't be written that makes assumptions about
2602 // nLockTime that preclude a fix later.
2603 txNew
.nLockTime
= chainActive
.Height();
2605 // Secondly occasionally randomly pick a nLockTime even further back, so
2606 // that transactions that are delayed after signing for whatever reason,
2607 // e.g. high-latency mix networks and some CoinJoin implementations, have
2609 if (GetRandInt(10) == 0)
2610 txNew
.nLockTime
= std::max(0, (int)txNew
.nLockTime
- GetRandInt(100));
2612 assert(txNew
.nLockTime
<= (unsigned int)chainActive
.Height());
2613 assert(txNew
.nLockTime
< LOCKTIME_THRESHOLD
);
2614 FeeCalculation feeCalc
;
2616 unsigned int nBytes
;
2618 std::set
<CInputCoin
> setCoins
;
2619 LOCK2(cs_main
, cs_wallet
);
2621 std::vector
<COutput
> vAvailableCoins
;
2622 AvailableCoins(vAvailableCoins
, true, &coin_control
);
2624 // Create change script that will be used if we need change
2625 // TODO: pass in scriptChange instead of reservekey so
2626 // change transaction isn't always pay-to-bitcoin-address
2627 CScript scriptChange
;
2629 // coin control: send change to custom address
2630 if (!boost::get
<CNoDestination
>(&coin_control
.destChange
)) {
2631 scriptChange
= GetScriptForDestination(coin_control
.destChange
);
2632 } else { // no coin control: send change to newly generated address
2633 // Note: We use a new key here to keep it from being obvious which side is the change.
2634 // The drawback is that by not reusing a previous key, the change may be lost if a
2635 // backup is restored, if the backup doesn't have the new private key for the change.
2636 // If we reused the old key, it would be possible to add code to look for and
2637 // rediscover unknown transactions that were written with keys of ours to recover
2638 // post-backup change.
2640 // Reserve a new key pair from key pool
2643 ret
= reservekey
.GetReservedKey(vchPubKey
, true);
2646 strFailReason
= _("Keypool ran out, please call keypoolrefill first");
2650 scriptChange
= GetScriptForDestination(vchPubKey
.GetID());
2652 CTxOut
change_prototype_txout(0, scriptChange
);
2653 size_t change_prototype_size
= GetSerializeSize(change_prototype_txout
, SER_DISK
, 0);
2655 CFeeRate discard_rate
= GetDiscardRate(::feeEstimator
);
2657 bool pick_new_inputs
= true;
2658 CAmount nValueIn
= 0;
2659 // Start with no fee and loop until there is enough fee
2662 nChangePosInOut
= nChangePosRequest
;
2665 wtxNew
.fFromMe
= true;
2668 CAmount nValueToSelect
= nValue
;
2669 if (nSubtractFeeFromAmount
== 0)
2670 nValueToSelect
+= nFeeRet
;
2671 // vouts to the payees
2672 for (const auto& recipient
: vecSend
)
2674 CTxOut
txout(recipient
.nAmount
, recipient
.scriptPubKey
);
2676 if (recipient
.fSubtractFeeFromAmount
)
2678 txout
.nValue
-= nFeeRet
/ nSubtractFeeFromAmount
; // Subtract fee equally from each selected recipient
2680 if (fFirst
) // first receiver pays the remainder not divisible by output count
2683 txout
.nValue
-= nFeeRet
% nSubtractFeeFromAmount
;
2687 if (IsDust(txout
, ::dustRelayFee
))
2689 if (recipient
.fSubtractFeeFromAmount
&& nFeeRet
> 0)
2691 if (txout
.nValue
< 0)
2692 strFailReason
= _("The transaction amount is too small to pay the fee");
2694 strFailReason
= _("The transaction amount is too small to send after the fee has been deducted");
2697 strFailReason
= _("Transaction amount too small");
2700 txNew
.vout
.push_back(txout
);
2703 // Choose coins to use
2704 if (pick_new_inputs
) {
2707 if (!SelectCoins(vAvailableCoins
, nValueToSelect
, setCoins
, nValueIn
, &coin_control
))
2709 strFailReason
= _("Insufficient funds");
2714 const CAmount nChange
= nValueIn
- nValueToSelect
;
2718 // Fill a vout to ourself
2719 CTxOut
newTxOut(nChange
, scriptChange
);
2721 // Never create dust outputs; if we would, just
2722 // add the dust to the fee.
2723 if (IsDust(newTxOut
, discard_rate
))
2725 nChangePosInOut
= -1;
2730 if (nChangePosInOut
== -1)
2732 // Insert change txn at random position:
2733 nChangePosInOut
= GetRandInt(txNew
.vout
.size()+1);
2735 else if ((unsigned int)nChangePosInOut
> txNew
.vout
.size())
2737 strFailReason
= _("Change index out of range");
2741 std::vector
<CTxOut
>::iterator position
= txNew
.vout
.begin()+nChangePosInOut
;
2742 txNew
.vout
.insert(position
, newTxOut
);
2745 nChangePosInOut
= -1;
2750 // Note how the sequence number is set to non-maxint so that
2751 // the nLockTime set above actually works.
2753 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2754 // we use the highest possible value in that range (maxint-2)
2755 // to avoid conflicting with other possible uses of nSequence,
2756 // and in the spirit of "smallest possible change from prior
2758 const uint32_t nSequence
= coin_control
.signalRbf
? MAX_BIP125_RBF_SEQUENCE
: (CTxIn::SEQUENCE_FINAL
- 1);
2759 for (const auto& coin
: setCoins
)
2760 txNew
.vin
.push_back(CTxIn(coin
.outpoint
,CScript(),
2763 // Fill in dummy signatures for fee calculation.
2764 if (!DummySignTx(txNew
, setCoins
)) {
2765 strFailReason
= _("Signing transaction failed");
2769 nBytes
= GetVirtualTransactionSize(txNew
);
2771 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2772 for (auto& vin
: txNew
.vin
) {
2773 vin
.scriptSig
= CScript();
2774 vin
.scriptWitness
.SetNull();
2777 nFeeNeeded
= GetMinimumFee(nBytes
, coin_control
, ::mempool
, ::feeEstimator
, &feeCalc
);
2779 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2780 // because we must be at the maximum allowed fee.
2781 if (nFeeNeeded
< ::minRelayTxFee
.GetFee(nBytes
))
2783 strFailReason
= _("Transaction too large for fee policy");
2787 if (nFeeRet
>= nFeeNeeded
) {
2788 // Reduce fee to only the needed amount if possible. This
2789 // prevents potential overpayment in fees if the coins
2790 // selected to meet nFeeNeeded result in a transaction that
2791 // requires less fee than the prior iteration.
2793 // If we have no change and a big enough excess fee, then
2794 // try to construct transaction again only without picking
2795 // new inputs. We now know we only need the smaller fee
2796 // (because of reduced tx size) and so we should add a
2797 // change output. Only try this once.
2798 if (nChangePosInOut
== -1 && nSubtractFeeFromAmount
== 0 && pick_new_inputs
) {
2799 unsigned int tx_size_with_change
= nBytes
+ change_prototype_size
+ 2; // Add 2 as a buffer in case increasing # of outputs changes compact size
2800 CAmount fee_needed_with_change
= GetMinimumFee(tx_size_with_change
, coin_control
, ::mempool
, ::feeEstimator
, nullptr);
2801 CAmount minimum_value_for_change
= GetDustThreshold(change_prototype_txout
, discard_rate
);
2802 if (nFeeRet
>= fee_needed_with_change
+ minimum_value_for_change
) {
2803 pick_new_inputs
= false;
2804 nFeeRet
= fee_needed_with_change
;
2809 // If we have change output already, just increase it
2810 if (nFeeRet
> nFeeNeeded
&& nChangePosInOut
!= -1 && nSubtractFeeFromAmount
== 0) {
2811 CAmount extraFeePaid
= nFeeRet
- nFeeNeeded
;
2812 std::vector
<CTxOut
>::iterator change_position
= txNew
.vout
.begin()+nChangePosInOut
;
2813 change_position
->nValue
+= extraFeePaid
;
2814 nFeeRet
-= extraFeePaid
;
2816 break; // Done, enough fee included.
2818 else if (!pick_new_inputs
) {
2819 // This shouldn't happen, we should have had enough excess
2820 // fee to pay for the new output and still meet nFeeNeeded
2821 // Or we should have just subtracted fee from recipients and
2822 // nFeeNeeded should not have changed
2823 strFailReason
= _("Transaction fee and change calculation failed");
2827 // Try to reduce change to include necessary fee
2828 if (nChangePosInOut
!= -1 && nSubtractFeeFromAmount
== 0) {
2829 CAmount additionalFeeNeeded
= nFeeNeeded
- nFeeRet
;
2830 std::vector
<CTxOut
>::iterator change_position
= txNew
.vout
.begin()+nChangePosInOut
;
2831 // Only reduce change if remaining amount is still a large enough output.
2832 if (change_position
->nValue
>= MIN_FINAL_CHANGE
+ additionalFeeNeeded
) {
2833 change_position
->nValue
-= additionalFeeNeeded
;
2834 nFeeRet
+= additionalFeeNeeded
;
2835 break; // Done, able to increase fee from change
2839 // If subtracting fee from recipients, we now know what fee we
2840 // need to subtract, we have no reason to reselect inputs
2841 if (nSubtractFeeFromAmount
> 0) {
2842 pick_new_inputs
= false;
2845 // Include more fee and try again.
2846 nFeeRet
= nFeeNeeded
;
2851 if (nChangePosInOut
== -1) reservekey
.ReturnKey(); // Return any reserved key if we don't have change
2855 CTransaction
txNewConst(txNew
);
2857 for (const auto& coin
: setCoins
)
2859 const CScript
& scriptPubKey
= coin
.txout
.scriptPubKey
;
2860 SignatureData sigdata
;
2862 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst
, nIn
, coin
.txout
.nValue
, SIGHASH_ALL
), scriptPubKey
, sigdata
))
2864 strFailReason
= _("Signing transaction failed");
2867 UpdateTransaction(txNew
, nIn
, sigdata
);
2874 // Embed the constructed transaction data in wtxNew.
2875 wtxNew
.SetTx(MakeTransactionRef(std::move(txNew
)));
2878 if (GetTransactionWeight(wtxNew
) >= MAX_STANDARD_TX_WEIGHT
)
2880 strFailReason
= _("Transaction too large");
2885 if (gArgs
.GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS
)) {
2886 // Lastly, ensure this tx will pass the mempool's chain limits
2888 CTxMemPoolEntry
entry(wtxNew
.tx
, 0, 0, 0, false, 0, lp
);
2889 CTxMemPool::setEntries setAncestors
;
2890 size_t nLimitAncestors
= gArgs
.GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT
);
2891 size_t nLimitAncestorSize
= gArgs
.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT
)*1000;
2892 size_t nLimitDescendants
= gArgs
.GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT
);
2893 size_t nLimitDescendantSize
= gArgs
.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT
)*1000;
2894 std::string errString
;
2895 if (!mempool
.CalculateMemPoolAncestors(entry
, setAncestors
, nLimitAncestors
, nLimitAncestorSize
, nLimitDescendants
, nLimitDescendantSize
, errString
)) {
2896 strFailReason
= _("Transaction has too long of a mempool chain");
2901 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",
2902 nFeeRet
, nBytes
, nFeeNeeded
, feeCalc
.returnedTarget
, feeCalc
.desiredTarget
, StringForFeeReason(feeCalc
.reason
), feeCalc
.est
.decay
,
2903 feeCalc
.est
.pass
.start
, feeCalc
.est
.pass
.end
,
2904 100 * feeCalc
.est
.pass
.withinTarget
/ (feeCalc
.est
.pass
.totalConfirmed
+ feeCalc
.est
.pass
.inMempool
+ feeCalc
.est
.pass
.leftMempool
),
2905 feeCalc
.est
.pass
.withinTarget
, feeCalc
.est
.pass
.totalConfirmed
, feeCalc
.est
.pass
.inMempool
, feeCalc
.est
.pass
.leftMempool
,
2906 feeCalc
.est
.fail
.start
, feeCalc
.est
.fail
.end
,
2907 100 * feeCalc
.est
.fail
.withinTarget
/ (feeCalc
.est
.fail
.totalConfirmed
+ feeCalc
.est
.fail
.inMempool
+ feeCalc
.est
.fail
.leftMempool
),
2908 feeCalc
.est
.fail
.withinTarget
, feeCalc
.est
.fail
.totalConfirmed
, feeCalc
.est
.fail
.inMempool
, feeCalc
.est
.fail
.leftMempool
);
2913 * Call after CreateTransaction unless you want to abort
2915 bool CWallet::CommitTransaction(CWalletTx
& wtxNew
, CReserveKey
& reservekey
, CConnman
* connman
, CValidationState
& state
)
2918 LOCK2(cs_main
, cs_wallet
);
2919 LogPrintf("CommitTransaction:\n%s", wtxNew
.tx
->ToString());
2921 // Take key pair from key pool so it won't be used again
2922 reservekey
.KeepKey();
2924 // Add tx to wallet, because if it has change it's also ours,
2925 // otherwise just for transaction history.
2926 AddToWallet(wtxNew
);
2928 // Notify that old coins are spent
2929 for (const CTxIn
& txin
: wtxNew
.tx
->vin
)
2931 CWalletTx
&coin
= mapWallet
[txin
.prevout
.hash
];
2932 coin
.BindWallet(this);
2933 NotifyTransactionChanged(this, coin
.GetHash(), CT_UPDATED
);
2937 // Track how many getdata requests our transaction gets
2938 mapRequestCount
[wtxNew
.GetHash()] = 0;
2940 if (fBroadcastTransactions
)
2943 if (!wtxNew
.AcceptToMemoryPool(maxTxFee
, state
)) {
2944 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state
.GetRejectReason());
2945 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2947 wtxNew
.RelayWalletTransaction(connman
);
2954 void CWallet::ListAccountCreditDebit(const std::string
& strAccount
, std::list
<CAccountingEntry
>& entries
) {
2955 CWalletDB
walletdb(*dbw
);
2956 return walletdb
.ListAccountCreditDebit(strAccount
, entries
);
2959 bool CWallet::AddAccountingEntry(const CAccountingEntry
& acentry
)
2961 CWalletDB
walletdb(*dbw
);
2963 return AddAccountingEntry(acentry
, &walletdb
);
2966 bool CWallet::AddAccountingEntry(const CAccountingEntry
& acentry
, CWalletDB
*pwalletdb
)
2968 if (!pwalletdb
->WriteAccountingEntry(++nAccountingEntryNumber
, acentry
)) {
2972 laccentries
.push_back(acentry
);
2973 CAccountingEntry
& entry
= laccentries
.back();
2974 wtxOrdered
.insert(std::make_pair(entry
.nOrderPos
, TxPair(nullptr, &entry
)));
2979 DBErrors
CWallet::LoadWallet(bool& fFirstRunRet
)
2981 LOCK2(cs_main
, cs_wallet
);
2983 fFirstRunRet
= false;
2984 DBErrors nLoadWalletRet
= CWalletDB(*dbw
,"cr+").LoadWallet(this);
2985 if (nLoadWalletRet
== DB_NEED_REWRITE
)
2987 if (dbw
->Rewrite("\x04pool"))
2989 setInternalKeyPool
.clear();
2990 setExternalKeyPool
.clear();
2991 m_pool_key_to_index
.clear();
2992 // Note: can't top-up keypool here, because wallet is locked.
2993 // User will be prompted to unlock wallet the next operation
2994 // that requires a new key.
2998 // This wallet is in its first run if all of these are empty
2999 fFirstRunRet
= mapKeys
.empty() && mapCryptedKeys
.empty() && mapWatchKeys
.empty() && setWatchOnly
.empty() && mapScripts
.empty();
3001 if (nLoadWalletRet
!= DB_LOAD_OK
)
3002 return nLoadWalletRet
;
3004 uiInterface
.LoadWallet(this);
3009 DBErrors
CWallet::ZapSelectTx(std::vector
<uint256
>& vHashIn
, std::vector
<uint256
>& vHashOut
)
3011 AssertLockHeld(cs_wallet
); // mapWallet
3012 DBErrors nZapSelectTxRet
= CWalletDB(*dbw
,"cr+").ZapSelectTx(vHashIn
, vHashOut
);
3013 for (uint256 hash
: vHashOut
)
3014 mapWallet
.erase(hash
);
3016 if (nZapSelectTxRet
== DB_NEED_REWRITE
)
3018 if (dbw
->Rewrite("\x04pool"))
3020 setInternalKeyPool
.clear();
3021 setExternalKeyPool
.clear();
3022 m_pool_key_to_index
.clear();
3023 // Note: can't top-up keypool here, because wallet is locked.
3024 // User will be prompted to unlock wallet the next operation
3025 // that requires a new key.
3029 if (nZapSelectTxRet
!= DB_LOAD_OK
)
3030 return nZapSelectTxRet
;
3038 DBErrors
CWallet::ZapWalletTx(std::vector
<CWalletTx
>& vWtx
)
3040 DBErrors nZapWalletTxRet
= CWalletDB(*dbw
,"cr+").ZapWalletTx(vWtx
);
3041 if (nZapWalletTxRet
== DB_NEED_REWRITE
)
3043 if (dbw
->Rewrite("\x04pool"))
3046 setInternalKeyPool
.clear();
3047 setExternalKeyPool
.clear();
3048 m_pool_key_to_index
.clear();
3049 // Note: can't top-up keypool here, because wallet is locked.
3050 // User will be prompted to unlock wallet the next operation
3051 // that requires a new key.
3055 if (nZapWalletTxRet
!= DB_LOAD_OK
)
3056 return nZapWalletTxRet
;
3062 bool CWallet::SetAddressBook(const CTxDestination
& address
, const std::string
& strName
, const std::string
& strPurpose
)
3064 bool fUpdated
= false;
3066 LOCK(cs_wallet
); // mapAddressBook
3067 std::map
<CTxDestination
, CAddressBookData
>::iterator mi
= mapAddressBook
.find(address
);
3068 fUpdated
= mi
!= mapAddressBook
.end();
3069 mapAddressBook
[address
].name
= strName
;
3070 if (!strPurpose
.empty()) /* update purpose only if requested */
3071 mapAddressBook
[address
].purpose
= strPurpose
;
3073 NotifyAddressBookChanged(this, address
, strName
, ::IsMine(*this, address
) != ISMINE_NO
,
3074 strPurpose
, (fUpdated
? CT_UPDATED
: CT_NEW
) );
3075 if (!strPurpose
.empty() && !CWalletDB(*dbw
).WritePurpose(EncodeDestination(address
), strPurpose
))
3077 return CWalletDB(*dbw
).WriteName(EncodeDestination(address
), strName
);
3080 bool CWallet::DelAddressBook(const CTxDestination
& address
)
3083 LOCK(cs_wallet
); // mapAddressBook
3085 // Delete destdata tuples associated with address
3086 std::string strAddress
= EncodeDestination(address
);
3087 for (const std::pair
<std::string
, std::string
> &item
: mapAddressBook
[address
].destdata
)
3089 CWalletDB(*dbw
).EraseDestData(strAddress
, item
.first
);
3091 mapAddressBook
.erase(address
);
3094 NotifyAddressBookChanged(this, address
, "", ::IsMine(*this, address
) != ISMINE_NO
, "", CT_DELETED
);
3096 CWalletDB(*dbw
).ErasePurpose(EncodeDestination(address
));
3097 return CWalletDB(*dbw
).EraseName(EncodeDestination(address
));
3100 const std::string
& CWallet::GetAccountName(const CScript
& scriptPubKey
) const
3102 CTxDestination address
;
3103 if (ExtractDestination(scriptPubKey
, address
) && !scriptPubKey
.IsUnspendable()) {
3104 auto mi
= mapAddressBook
.find(address
);
3105 if (mi
!= mapAddressBook
.end()) {
3106 return mi
->second
.name
;
3109 // A scriptPubKey that doesn't have an entry in the address book is
3110 // associated with the default account ("").
3111 const static std::string DEFAULT_ACCOUNT_NAME
;
3112 return DEFAULT_ACCOUNT_NAME
;
3116 * Mark old keypool keys as used,
3117 * and generate all new keys
3119 bool CWallet::NewKeyPool()
3123 CWalletDB
walletdb(*dbw
);
3125 for (int64_t nIndex
: setInternalKeyPool
) {
3126 walletdb
.ErasePool(nIndex
);
3128 setInternalKeyPool
.clear();
3130 for (int64_t nIndex
: setExternalKeyPool
) {
3131 walletdb
.ErasePool(nIndex
);
3133 setExternalKeyPool
.clear();
3135 m_pool_key_to_index
.clear();
3137 if (!TopUpKeyPool()) {
3140 LogPrintf("CWallet::NewKeyPool rewrote keypool\n");
3145 size_t CWallet::KeypoolCountExternalKeys()
3147 AssertLockHeld(cs_wallet
); // setExternalKeyPool
3148 return setExternalKeyPool
.size();
3151 void CWallet::LoadKeyPool(int64_t nIndex
, const CKeyPool
&keypool
)
3153 AssertLockHeld(cs_wallet
);
3154 if (keypool
.fInternal
) {
3155 setInternalKeyPool
.insert(nIndex
);
3157 setExternalKeyPool
.insert(nIndex
);
3159 m_max_keypool_index
= std::max(m_max_keypool_index
, nIndex
);
3160 m_pool_key_to_index
[keypool
.vchPubKey
.GetID()] = nIndex
;
3162 // If no metadata exists yet, create a default with the pool key's
3163 // creation time. Note that this may be overwritten by actually
3164 // stored metadata for that key later, which is fine.
3165 CKeyID keyid
= keypool
.vchPubKey
.GetID();
3166 if (mapKeyMetadata
.count(keyid
) == 0)
3167 mapKeyMetadata
[keyid
] = CKeyMetadata(keypool
.nTime
);
3170 bool CWallet::TopUpKeyPool(unsigned int kpSize
)
3179 unsigned int nTargetSize
;
3181 nTargetSize
= kpSize
;
3183 nTargetSize
= std::max(gArgs
.GetArg("-keypool", DEFAULT_KEYPOOL_SIZE
), (int64_t) 0);
3185 // count amount of available keys (internal, external)
3186 // make sure the keypool of external and internal keys fits the user selected target (-keypool)
3187 int64_t missingExternal
= std::max(std::max((int64_t) nTargetSize
, (int64_t) 1) - (int64_t)setExternalKeyPool
.size(), (int64_t) 0);
3188 int64_t missingInternal
= std::max(std::max((int64_t) nTargetSize
, (int64_t) 1) - (int64_t)setInternalKeyPool
.size(), (int64_t) 0);
3190 if (!IsHDEnabled() || !CanSupportFeature(FEATURE_HD_SPLIT
))
3192 // don't create extra internal keys
3193 missingInternal
= 0;
3195 bool internal
= false;
3196 CWalletDB
walletdb(*dbw
);
3197 for (int64_t i
= missingInternal
+ missingExternal
; i
--;)
3199 if (i
< missingInternal
) {
3203 assert(m_max_keypool_index
< std::numeric_limits
<int64_t>::max()); // How in the hell did you use so many keys?
3204 int64_t index
= ++m_max_keypool_index
;
3206 CPubKey
pubkey(GenerateNewKey(walletdb
, internal
));
3207 if (!walletdb
.WritePool(index
, CKeyPool(pubkey
, internal
))) {
3208 throw std::runtime_error(std::string(__func__
) + ": writing generated key failed");
3212 setInternalKeyPool
.insert(index
);
3214 setExternalKeyPool
.insert(index
);
3216 m_pool_key_to_index
[pubkey
.GetID()] = index
;
3218 if (missingInternal
+ missingExternal
> 0) {
3219 LogPrintf("keypool added %d keys (%d internal), size=%u (%u internal)\n", missingInternal
+ missingExternal
, missingInternal
, setInternalKeyPool
.size() + setExternalKeyPool
.size(), setInternalKeyPool
.size());
3225 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex
, CKeyPool
& keypool
, bool fRequestedInternal
)
3228 keypool
.vchPubKey
= CPubKey();
3235 bool fReturningInternal
= IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT
) && fRequestedInternal
;
3236 std::set
<int64_t>& setKeyPool
= fReturningInternal
? setInternalKeyPool
: setExternalKeyPool
;
3238 // Get the oldest key
3239 if(setKeyPool
.empty())
3242 CWalletDB
walletdb(*dbw
);
3244 auto it
= setKeyPool
.begin();
3246 setKeyPool
.erase(it
);
3247 if (!walletdb
.ReadPool(nIndex
, keypool
)) {
3248 throw std::runtime_error(std::string(__func__
) + ": read failed");
3250 if (!HaveKey(keypool
.vchPubKey
.GetID())) {
3251 throw std::runtime_error(std::string(__func__
) + ": unknown key in key pool");
3253 if (keypool
.fInternal
!= fReturningInternal
) {
3254 throw std::runtime_error(std::string(__func__
) + ": keypool entry misclassified");
3257 assert(keypool
.vchPubKey
.IsValid());
3258 m_pool_key_to_index
.erase(keypool
.vchPubKey
.GetID());
3259 LogPrintf("keypool reserve %d\n", nIndex
);
3263 void CWallet::KeepKey(int64_t nIndex
)
3265 // Remove from key pool
3266 CWalletDB
walletdb(*dbw
);
3267 walletdb
.ErasePool(nIndex
);
3268 LogPrintf("keypool keep %d\n", nIndex
);
3271 void CWallet::ReturnKey(int64_t nIndex
, bool fInternal
, const CPubKey
& pubkey
)
3273 // Return to key pool
3277 setInternalKeyPool
.insert(nIndex
);
3279 setExternalKeyPool
.insert(nIndex
);
3281 m_pool_key_to_index
[pubkey
.GetID()] = nIndex
;
3283 LogPrintf("keypool return %d\n", nIndex
);
3286 bool CWallet::GetKeyFromPool(CPubKey
& result
, bool internal
)
3292 ReserveKeyFromKeyPool(nIndex
, keypool
, internal
);
3295 if (IsLocked()) return false;
3296 CWalletDB
walletdb(*dbw
);
3297 result
= GenerateNewKey(walletdb
, internal
);
3301 result
= keypool
.vchPubKey
;
3306 static int64_t GetOldestKeyTimeInPool(const std::set
<int64_t>& setKeyPool
, CWalletDB
& walletdb
) {
3307 if (setKeyPool
.empty()) {
3312 int64_t nIndex
= *(setKeyPool
.begin());
3313 if (!walletdb
.ReadPool(nIndex
, keypool
)) {
3314 throw std::runtime_error(std::string(__func__
) + ": read oldest key in keypool failed");
3316 assert(keypool
.vchPubKey
.IsValid());
3317 return keypool
.nTime
;
3320 int64_t CWallet::GetOldestKeyPoolTime()
3324 CWalletDB
walletdb(*dbw
);
3326 // load oldest key from keypool, get time and return
3327 int64_t oldestKey
= GetOldestKeyTimeInPool(setExternalKeyPool
, walletdb
);
3328 if (IsHDEnabled() && CanSupportFeature(FEATURE_HD_SPLIT
)) {
3329 oldestKey
= std::max(GetOldestKeyTimeInPool(setInternalKeyPool
, walletdb
), oldestKey
);
3335 std::map
<CTxDestination
, CAmount
> CWallet::GetAddressBalances()
3337 std::map
<CTxDestination
, CAmount
> balances
;
3341 for (const auto& walletEntry
: mapWallet
)
3343 const CWalletTx
*pcoin
= &walletEntry
.second
;
3345 if (!pcoin
->IsTrusted())
3348 if (pcoin
->IsCoinBase() && pcoin
->GetBlocksToMaturity() > 0)
3351 int nDepth
= pcoin
->GetDepthInMainChain();
3352 if (nDepth
< (pcoin
->IsFromMe(ISMINE_ALL
) ? 0 : 1))
3355 for (unsigned int i
= 0; i
< pcoin
->tx
->vout
.size(); i
++)
3357 CTxDestination addr
;
3358 if (!IsMine(pcoin
->tx
->vout
[i
]))
3360 if(!ExtractDestination(pcoin
->tx
->vout
[i
].scriptPubKey
, addr
))
3363 CAmount n
= IsSpent(walletEntry
.first
, i
) ? 0 : pcoin
->tx
->vout
[i
].nValue
;
3365 if (!balances
.count(addr
))
3367 balances
[addr
] += n
;
3375 std::set
< std::set
<CTxDestination
> > CWallet::GetAddressGroupings()
3377 AssertLockHeld(cs_wallet
); // mapWallet
3378 std::set
< std::set
<CTxDestination
> > groupings
;
3379 std::set
<CTxDestination
> grouping
;
3381 for (const auto& walletEntry
: mapWallet
)
3383 const CWalletTx
*pcoin
= &walletEntry
.second
;
3385 if (pcoin
->tx
->vin
.size() > 0)
3387 bool any_mine
= false;
3388 // group all input addresses with each other
3389 for (CTxIn txin
: pcoin
->tx
->vin
)
3391 CTxDestination address
;
3392 if(!IsMine(txin
)) /* If this input isn't mine, ignore it */
3394 if(!ExtractDestination(mapWallet
[txin
.prevout
.hash
].tx
->vout
[txin
.prevout
.n
].scriptPubKey
, address
))
3396 grouping
.insert(address
);
3400 // group change with input addresses
3403 for (CTxOut txout
: pcoin
->tx
->vout
)
3404 if (IsChange(txout
))
3406 CTxDestination txoutAddr
;
3407 if(!ExtractDestination(txout
.scriptPubKey
, txoutAddr
))
3409 grouping
.insert(txoutAddr
);
3412 if (grouping
.size() > 0)
3414 groupings
.insert(grouping
);
3419 // group lone addrs by themselves
3420 for (const auto& txout
: pcoin
->tx
->vout
)
3423 CTxDestination address
;
3424 if(!ExtractDestination(txout
.scriptPubKey
, address
))
3426 grouping
.insert(address
);
3427 groupings
.insert(grouping
);
3432 std::set
< std::set
<CTxDestination
>* > uniqueGroupings
; // a set of pointers to groups of addresses
3433 std::map
< CTxDestination
, std::set
<CTxDestination
>* > setmap
; // map addresses to the unique group containing it
3434 for (std::set
<CTxDestination
> _grouping
: groupings
)
3436 // make a set of all the groups hit by this new group
3437 std::set
< std::set
<CTxDestination
>* > hits
;
3438 std::map
< CTxDestination
, std::set
<CTxDestination
>* >::iterator it
;
3439 for (CTxDestination address
: _grouping
)
3440 if ((it
= setmap
.find(address
)) != setmap
.end())
3441 hits
.insert((*it
).second
);
3443 // merge all hit groups into a new single group and delete old groups
3444 std::set
<CTxDestination
>* merged
= new std::set
<CTxDestination
>(_grouping
);
3445 for (std::set
<CTxDestination
>* hit
: hits
)
3447 merged
->insert(hit
->begin(), hit
->end());
3448 uniqueGroupings
.erase(hit
);
3451 uniqueGroupings
.insert(merged
);
3454 for (CTxDestination element
: *merged
)
3455 setmap
[element
] = merged
;
3458 std::set
< std::set
<CTxDestination
> > ret
;
3459 for (std::set
<CTxDestination
>* uniqueGrouping
: uniqueGroupings
)
3461 ret
.insert(*uniqueGrouping
);
3462 delete uniqueGrouping
;
3468 std::set
<CTxDestination
> CWallet::GetAccountAddresses(const std::string
& strAccount
) const
3471 std::set
<CTxDestination
> result
;
3472 for (const std::pair
<CTxDestination
, CAddressBookData
>& item
: mapAddressBook
)
3474 const CTxDestination
& address
= item
.first
;
3475 const std::string
& strName
= item
.second
.name
;
3476 if (strName
== strAccount
)
3477 result
.insert(address
);
3482 bool CReserveKey::GetReservedKey(CPubKey
& pubkey
, bool internal
)
3487 pwallet
->ReserveKeyFromKeyPool(nIndex
, keypool
, internal
);
3489 vchPubKey
= keypool
.vchPubKey
;
3493 fInternal
= keypool
.fInternal
;
3495 assert(vchPubKey
.IsValid());
3500 void CReserveKey::KeepKey()
3503 pwallet
->KeepKey(nIndex
);
3505 vchPubKey
= CPubKey();
3508 void CReserveKey::ReturnKey()
3511 pwallet
->ReturnKey(nIndex
, fInternal
, vchPubKey
);
3514 vchPubKey
= CPubKey();
3517 void CWallet::MarkReserveKeysAsUsed(int64_t keypool_id
)
3519 AssertLockHeld(cs_wallet
);
3520 bool internal
= setInternalKeyPool
.count(keypool_id
);
3521 if (!internal
) assert(setExternalKeyPool
.count(keypool_id
));
3522 std::set
<int64_t> *setKeyPool
= internal
? &setInternalKeyPool
: &setExternalKeyPool
;
3523 auto it
= setKeyPool
->begin();
3525 CWalletDB
walletdb(*dbw
);
3526 while (it
!= std::end(*setKeyPool
)) {
3527 const int64_t& index
= *(it
);
3528 if (index
> keypool_id
) break; // set*KeyPool is ordered
3531 if (walletdb
.ReadPool(index
, keypool
)) { //TODO: This should be unnecessary
3532 m_pool_key_to_index
.erase(keypool
.vchPubKey
.GetID());
3534 walletdb
.ErasePool(index
);
3535 LogPrintf("keypool index %d removed\n", index
);
3536 it
= setKeyPool
->erase(it
);
3540 void CWallet::GetScriptForMining(std::shared_ptr
<CReserveScript
> &script
)
3542 std::shared_ptr
<CReserveKey
> rKey
= std::make_shared
<CReserveKey
>(this);
3544 if (!rKey
->GetReservedKey(pubkey
))
3548 script
->reserveScript
= CScript() << ToByteVector(pubkey
) << OP_CHECKSIG
;
3551 void CWallet::LockCoin(const COutPoint
& output
)
3553 AssertLockHeld(cs_wallet
); // setLockedCoins
3554 setLockedCoins
.insert(output
);
3557 void CWallet::UnlockCoin(const COutPoint
& output
)
3559 AssertLockHeld(cs_wallet
); // setLockedCoins
3560 setLockedCoins
.erase(output
);
3563 void CWallet::UnlockAllCoins()
3565 AssertLockHeld(cs_wallet
); // setLockedCoins
3566 setLockedCoins
.clear();
3569 bool CWallet::IsLockedCoin(uint256 hash
, unsigned int n
) const
3571 AssertLockHeld(cs_wallet
); // setLockedCoins
3572 COutPoint
outpt(hash
, n
);
3574 return (setLockedCoins
.count(outpt
) > 0);
3577 void CWallet::ListLockedCoins(std::vector
<COutPoint
>& vOutpts
) const
3579 AssertLockHeld(cs_wallet
); // setLockedCoins
3580 for (std::set
<COutPoint
>::iterator it
= setLockedCoins
.begin();
3581 it
!= setLockedCoins
.end(); it
++) {
3582 COutPoint outpt
= (*it
);
3583 vOutpts
.push_back(outpt
);
3587 /** @} */ // end of Actions
3589 void CWallet::GetKeyBirthTimes(std::map
<CTxDestination
, int64_t> &mapKeyBirth
) const {
3590 AssertLockHeld(cs_wallet
); // mapKeyMetadata
3591 mapKeyBirth
.clear();
3593 // get birth times for keys with metadata
3594 for (const auto& entry
: mapKeyMetadata
) {
3595 if (entry
.second
.nCreateTime
) {
3596 mapKeyBirth
[entry
.first
] = entry
.second
.nCreateTime
;
3600 // map in which we'll infer heights of other keys
3601 CBlockIndex
*pindexMax
= chainActive
[std::max(0, chainActive
.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3602 std::map
<CKeyID
, CBlockIndex
*> mapKeyFirstBlock
;
3603 for (const CKeyID
&keyid
: GetKeys()) {
3604 if (mapKeyBirth
.count(keyid
) == 0)
3605 mapKeyFirstBlock
[keyid
] = pindexMax
;
3608 // if there are no such keys, we're done
3609 if (mapKeyFirstBlock
.empty())
3612 // find first block that affects those keys, if there are any left
3613 std::vector
<CKeyID
> vAffected
;
3614 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); it
++) {
3615 // iterate over all wallet transactions...
3616 const CWalletTx
&wtx
= (*it
).second
;
3617 BlockMap::const_iterator blit
= mapBlockIndex
.find(wtx
.hashBlock
);
3618 if (blit
!= mapBlockIndex
.end() && chainActive
.Contains(blit
->second
)) {
3619 // ... which are already in a block
3620 int nHeight
= blit
->second
->nHeight
;
3621 for (const CTxOut
&txout
: wtx
.tx
->vout
) {
3622 // iterate over all their outputs
3623 CAffectedKeysVisitor(*this, vAffected
).Process(txout
.scriptPubKey
);
3624 for (const CKeyID
&keyid
: vAffected
) {
3625 // ... and all their affected keys
3626 std::map
<CKeyID
, CBlockIndex
*>::iterator rit
= mapKeyFirstBlock
.find(keyid
);
3627 if (rit
!= mapKeyFirstBlock
.end() && nHeight
< rit
->second
->nHeight
)
3628 rit
->second
= blit
->second
;
3635 // Extract block timestamps for those keys
3636 for (std::map
<CKeyID
, CBlockIndex
*>::const_iterator it
= mapKeyFirstBlock
.begin(); it
!= mapKeyFirstBlock
.end(); it
++)
3637 mapKeyBirth
[it
->first
] = it
->second
->GetBlockTime() - TIMESTAMP_WINDOW
; // block times can be 2h off
3641 * Compute smart timestamp for a transaction being added to the wallet.
3644 * - If sending a transaction, assign its timestamp to the current time.
3645 * - If receiving a transaction outside a block, assign its timestamp to the
3647 * - If receiving a block with a future timestamp, assign all its (not already
3648 * known) transactions' timestamps to the current time.
3649 * - If receiving a block with a past timestamp, before the most recent known
3650 * transaction (that we care about), assign all its (not already known)
3651 * transactions' timestamps to the same timestamp as that most-recent-known
3653 * - If receiving a block with a past timestamp, but after the most recent known
3654 * transaction, assign all its (not already known) transactions' timestamps to
3657 * For more information see CWalletTx::nTimeSmart,
3658 * https://bitcointalk.org/?topic=54527, or
3659 * https://github.com/bitcoin/bitcoin/pull/1393.
3661 unsigned int CWallet::ComputeTimeSmart(const CWalletTx
& wtx
) const
3663 unsigned int nTimeSmart
= wtx
.nTimeReceived
;
3664 if (!wtx
.hashUnset()) {
3665 if (mapBlockIndex
.count(wtx
.hashBlock
)) {
3666 int64_t latestNow
= wtx
.nTimeReceived
;
3667 int64_t latestEntry
= 0;
3669 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
3670 int64_t latestTolerated
= latestNow
+ 300;
3671 const TxItems
& txOrdered
= wtxOrdered
;
3672 for (auto it
= txOrdered
.rbegin(); it
!= txOrdered
.rend(); ++it
) {
3673 CWalletTx
* const pwtx
= it
->second
.first
;
3677 CAccountingEntry
* const pacentry
= it
->second
.second
;
3680 nSmartTime
= pwtx
->nTimeSmart
;
3682 nSmartTime
= pwtx
->nTimeReceived
;
3685 nSmartTime
= pacentry
->nTime
;
3687 if (nSmartTime
<= latestTolerated
) {
3688 latestEntry
= nSmartTime
;
3689 if (nSmartTime
> latestNow
) {
3690 latestNow
= nSmartTime
;
3696 int64_t blocktime
= mapBlockIndex
[wtx
.hashBlock
]->GetBlockTime();
3697 nTimeSmart
= std::max(latestEntry
, std::min(blocktime
, latestNow
));
3699 LogPrintf("%s: found %s in block %s not in index\n", __func__
, wtx
.GetHash().ToString(), wtx
.hashBlock
.ToString());
3705 bool CWallet::AddDestData(const CTxDestination
&dest
, const std::string
&key
, const std::string
&value
)
3707 if (boost::get
<CNoDestination
>(&dest
))
3710 mapAddressBook
[dest
].destdata
.insert(std::make_pair(key
, value
));
3711 return CWalletDB(*dbw
).WriteDestData(EncodeDestination(dest
), key
, value
);
3714 bool CWallet::EraseDestData(const CTxDestination
&dest
, const std::string
&key
)
3716 if (!mapAddressBook
[dest
].destdata
.erase(key
))
3718 return CWalletDB(*dbw
).EraseDestData(EncodeDestination(dest
), key
);
3721 bool CWallet::LoadDestData(const CTxDestination
&dest
, const std::string
&key
, const std::string
&value
)
3723 mapAddressBook
[dest
].destdata
.insert(std::make_pair(key
, value
));
3727 bool CWallet::GetDestData(const CTxDestination
&dest
, const std::string
&key
, std::string
*value
) const
3729 std::map
<CTxDestination
, CAddressBookData
>::const_iterator i
= mapAddressBook
.find(dest
);
3730 if(i
!= mapAddressBook
.end())
3732 CAddressBookData::StringMap::const_iterator j
= i
->second
.destdata
.find(key
);
3733 if(j
!= i
->second
.destdata
.end())
3743 std::vector
<std::string
> CWallet::GetDestValues(const std::string
& prefix
) const
3746 std::vector
<std::string
> values
;
3747 for (const auto& address
: mapAddressBook
) {
3748 for (const auto& data
: address
.second
.destdata
) {
3749 if (!data
.first
.compare(0, prefix
.size(), prefix
)) {
3750 values
.emplace_back(data
.second
);
3757 CWallet
* CWallet::CreateWalletFromFile(const std::string walletFile
)
3759 // needed to restore wallet transaction meta data after -zapwallettxes
3760 std::vector
<CWalletTx
> vWtx
;
3762 if (gArgs
.GetBoolArg("-zapwallettxes", false)) {
3763 uiInterface
.InitMessage(_("Zapping all transactions from wallet..."));
3765 std::unique_ptr
<CWalletDBWrapper
> dbw(new CWalletDBWrapper(&bitdb
, walletFile
));
3766 std::unique_ptr
<CWallet
> tempWallet(new CWallet(std::move(dbw
)));
3767 DBErrors nZapWalletRet
= tempWallet
->ZapWalletTx(vWtx
);
3768 if (nZapWalletRet
!= DB_LOAD_OK
) {
3769 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile
));
3774 uiInterface
.InitMessage(_("Loading wallet..."));
3776 int64_t nStart
= GetTimeMillis();
3777 bool fFirstRun
= true;
3778 std::unique_ptr
<CWalletDBWrapper
> dbw(new CWalletDBWrapper(&bitdb
, walletFile
));
3779 CWallet
*walletInstance
= new CWallet(std::move(dbw
));
3780 DBErrors nLoadWalletRet
= walletInstance
->LoadWallet(fFirstRun
);
3781 if (nLoadWalletRet
!= DB_LOAD_OK
)
3783 if (nLoadWalletRet
== DB_CORRUPT
) {
3784 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile
));
3787 else if (nLoadWalletRet
== DB_NONCRITICAL_ERROR
)
3789 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3790 " or address book entries might be missing or incorrect."),
3793 else if (nLoadWalletRet
== DB_TOO_NEW
) {
3794 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile
, _(PACKAGE_NAME
)));
3797 else if (nLoadWalletRet
== DB_NEED_REWRITE
)
3799 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME
)));
3803 InitError(strprintf(_("Error loading %s"), walletFile
));
3808 if (gArgs
.GetBoolArg("-upgradewallet", fFirstRun
))
3810 int nMaxVersion
= gArgs
.GetArg("-upgradewallet", 0);
3811 if (nMaxVersion
== 0) // the -upgradewallet without argument case
3813 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST
);
3814 nMaxVersion
= CLIENT_VERSION
;
3815 walletInstance
->SetMinVersion(FEATURE_LATEST
); // permanently upgrade the wallet immediately
3818 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion
);
3819 if (nMaxVersion
< walletInstance
->GetVersion())
3821 InitError(_("Cannot downgrade wallet"));
3824 walletInstance
->SetMaxVersion(nMaxVersion
);
3829 // ensure this wallet.dat can only be opened by clients supporting HD with chain split and expects no default key
3830 if (!gArgs
.GetBoolArg("-usehd", true)) {
3831 InitError(strprintf(_("Error creating %s: You can't create non-HD wallets with this version."), walletFile
));
3834 walletInstance
->SetMinVersion(FEATURE_NO_DEFAULT_KEY
);
3836 // generate a new master key
3837 CPubKey masterPubKey
= walletInstance
->GenerateNewHDMasterKey();
3838 if (!walletInstance
->SetHDMasterKey(masterPubKey
))
3839 throw std::runtime_error(std::string(__func__
) + ": Storing master key failed");
3841 // Top up the keypool
3842 if (!walletInstance
->TopUpKeyPool()) {
3843 InitError(_("Unable to generate initial keys") += "\n");
3847 walletInstance
->SetBestChain(chainActive
.GetLocator());
3849 else if (gArgs
.IsArgSet("-usehd")) {
3850 bool useHD
= gArgs
.GetBoolArg("-usehd", true);
3851 if (walletInstance
->IsHDEnabled() && !useHD
) {
3852 InitError(strprintf(_("Error loading %s: You can't disable HD on an already existing HD wallet"), walletFile
));
3855 if (!walletInstance
->IsHDEnabled() && useHD
) {
3856 InitError(strprintf(_("Error loading %s: You can't enable HD on an already existing non-HD wallet"), walletFile
));
3861 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart
);
3863 RegisterValidationInterface(walletInstance
);
3865 // Try to top up keypool. No-op if the wallet is locked.
3866 walletInstance
->TopUpKeyPool();
3868 CBlockIndex
*pindexRescan
= chainActive
.Genesis();
3869 if (!gArgs
.GetBoolArg("-rescan", false))
3871 CWalletDB
walletdb(*walletInstance
->dbw
);
3872 CBlockLocator locator
;
3873 if (walletdb
.ReadBestBlock(locator
))
3874 pindexRescan
= FindForkInGlobalIndex(chainActive
, locator
);
3876 if (chainActive
.Tip() && chainActive
.Tip() != pindexRescan
)
3878 //We can't rescan beyond non-pruned blocks, stop and throw an error
3879 //this might happen if a user uses an old wallet within a pruned node
3880 // or if he ran -disablewallet for a longer time, then decided to re-enable
3883 CBlockIndex
*block
= chainActive
.Tip();
3884 while (block
&& block
->pprev
&& (block
->pprev
->nStatus
& BLOCK_HAVE_DATA
) && block
->pprev
->nTx
> 0 && pindexRescan
!= block
)
3885 block
= block
->pprev
;
3887 if (pindexRescan
!= block
) {
3888 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3893 uiInterface
.InitMessage(_("Rescanning..."));
3894 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive
.Height() - pindexRescan
->nHeight
, pindexRescan
->nHeight
);
3896 // No need to read and scan block if block was created before
3897 // our wallet birthday (as adjusted for block time variability)
3898 while (pindexRescan
&& walletInstance
->nTimeFirstKey
&& (pindexRescan
->GetBlockTime() < (walletInstance
->nTimeFirstKey
- TIMESTAMP_WINDOW
))) {
3899 pindexRescan
= chainActive
.Next(pindexRescan
);
3902 nStart
= GetTimeMillis();
3903 walletInstance
->ScanForWalletTransactions(pindexRescan
, true);
3904 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart
);
3905 walletInstance
->SetBestChain(chainActive
.GetLocator());
3906 walletInstance
->dbw
->IncrementUpdateCounter();
3908 // Restore wallet transaction metadata after -zapwallettxes=1
3909 if (gArgs
.GetBoolArg("-zapwallettxes", false) && gArgs
.GetArg("-zapwallettxes", "1") != "2")
3911 CWalletDB
walletdb(*walletInstance
->dbw
);
3913 for (const CWalletTx
& wtxOld
: vWtx
)
3915 uint256 hash
= wtxOld
.GetHash();
3916 std::map
<uint256
, CWalletTx
>::iterator mi
= walletInstance
->mapWallet
.find(hash
);
3917 if (mi
!= walletInstance
->mapWallet
.end())
3919 const CWalletTx
* copyFrom
= &wtxOld
;
3920 CWalletTx
* copyTo
= &mi
->second
;
3921 copyTo
->mapValue
= copyFrom
->mapValue
;
3922 copyTo
->vOrderForm
= copyFrom
->vOrderForm
;
3923 copyTo
->nTimeReceived
= copyFrom
->nTimeReceived
;
3924 copyTo
->nTimeSmart
= copyFrom
->nTimeSmart
;
3925 copyTo
->fFromMe
= copyFrom
->fFromMe
;
3926 copyTo
->strFromAccount
= copyFrom
->strFromAccount
;
3927 copyTo
->nOrderPos
= copyFrom
->nOrderPos
;
3928 walletdb
.WriteTx(*copyTo
);
3933 walletInstance
->SetBroadcastTransactions(gArgs
.GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST
));
3936 LOCK(walletInstance
->cs_wallet
);
3937 LogPrintf("setKeyPool.size() = %u\n", walletInstance
->GetKeyPoolSize());
3938 LogPrintf("mapWallet.size() = %u\n", walletInstance
->mapWallet
.size());
3939 LogPrintf("mapAddressBook.size() = %u\n", walletInstance
->mapAddressBook
.size());
3942 return walletInstance
;
3945 std::atomic
<bool> CWallet::fFlushScheduled(false);
3947 void CWallet::postInitProcess(CScheduler
& scheduler
)
3949 // Add wallet transactions that aren't already in a block to mempool
3950 // Do this here as mempool requires genesis block to be loaded
3951 ReacceptWalletTransactions();
3953 // Run a thread to flush wallet periodically
3954 if (!CWallet::fFlushScheduled
.exchange(true)) {
3955 scheduler
.scheduleEvery(MaybeCompactWalletDB
, 500);
3959 bool CWallet::BackupWallet(const std::string
& strDest
)
3961 return dbw
->Backup(strDest
);
3964 CKeyPool::CKeyPool()
3970 CKeyPool::CKeyPool(const CPubKey
& vchPubKeyIn
, bool internalIn
)
3973 vchPubKey
= vchPubKeyIn
;
3974 fInternal
= internalIn
;
3977 CWalletKey::CWalletKey(int64_t nExpires
)
3979 nTimeCreated
= (nExpires
? GetTime() : 0);
3980 nTimeExpires
= nExpires
;
3983 void CMerkleTx::SetMerkleBranch(const CBlockIndex
* pindex
, int posInBlock
)
3985 // Update the tx's hashBlock
3986 hashBlock
= pindex
->GetBlockHash();
3988 // set the position of the transaction in the block
3989 nIndex
= posInBlock
;
3992 int CMerkleTx::GetDepthInMainChain(const CBlockIndex
* &pindexRet
) const
3997 AssertLockHeld(cs_main
);
3999 // Find the block it claims to be in
4000 BlockMap::iterator mi
= mapBlockIndex
.find(hashBlock
);
4001 if (mi
== mapBlockIndex
.end())
4003 CBlockIndex
* pindex
= (*mi
).second
;
4004 if (!pindex
|| !chainActive
.Contains(pindex
))
4008 return ((nIndex
== -1) ? (-1) : 1) * (chainActive
.Height() - pindex
->nHeight
+ 1);
4011 int CMerkleTx::GetBlocksToMaturity() const
4015 return std::max(0, (COINBASE_MATURITY
+1) - GetDepthInMainChain());
4019 bool CMerkleTx::AcceptToMemoryPool(const CAmount
& nAbsurdFee
, CValidationState
& state
)
4021 return ::AcceptToMemoryPool(mempool
, state
, tx
, true, nullptr, nullptr, false, nAbsurdFee
);