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"
16 #include "validation.h"
18 #include "policy/policy.h"
19 #include "primitives/block.h"
20 #include "primitives/transaction.h"
21 #include "script/script.h"
22 #include "script/sign.h"
24 #include "txmempool.h"
26 #include "ui_interface.h"
27 #include "utilmoneystr.h"
31 #include <boost/algorithm/string/replace.hpp>
32 #include <boost/filesystem.hpp>
33 #include <boost/thread.hpp>
37 CWallet
* pwalletMain
= NULL
;
38 /** Transaction fee set by the user */
39 CFeeRate
payTxFee(DEFAULT_TRANSACTION_FEE
);
40 unsigned int nTxConfirmTarget
= DEFAULT_TX_CONFIRM_TARGET
;
41 bool bSpendZeroConfChange
= DEFAULT_SPEND_ZEROCONF_CHANGE
;
42 bool fSendFreeTransactions
= DEFAULT_SEND_FREE_TRANSACTIONS
;
43 bool fWalletRbf
= DEFAULT_WALLET_RBF
;
45 const char * DEFAULT_WALLET_DAT
= "wallet.dat";
46 const uint32_t BIP32_HARDENED_KEY_LIMIT
= 0x80000000;
49 * Fees smaller than this (in satoshi) are considered zero fee (for transaction creation)
50 * Override with -mintxfee
52 CFeeRate
CWallet::minTxFee
= CFeeRate(DEFAULT_TRANSACTION_MINFEE
);
54 * If fee estimation does not have enough data to provide estimates, use this fee instead.
55 * Has no effect if not using fee estimation
56 * Override with -fallbackfee
58 CFeeRate
CWallet::fallbackFee
= CFeeRate(DEFAULT_FALLBACK_FEE
);
60 const uint256
CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
62 /** @defgroup mapWallet
67 struct CompareValueOnly
69 bool operator()(const pair
<CAmount
, pair
<const CWalletTx
*, unsigned int> >& t1
,
70 const pair
<CAmount
, pair
<const CWalletTx
*, unsigned int> >& t2
) const
72 return t1
.first
< t2
.first
;
76 std::string
COutput::ToString() const
78 return strprintf("COutput(%s, %d, %d) [%s]", tx
->GetHash().ToString(), i
, nDepth
, FormatMoney(tx
->tx
->vout
[i
].nValue
));
81 const CWalletTx
* CWallet::GetWalletTx(const uint256
& hash
) const
84 std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.find(hash
);
85 if (it
== mapWallet
.end())
90 CPubKey
CWallet::GenerateNewKey()
92 AssertLockHeld(cs_wallet
); // mapKeyMetadata
93 bool fCompressed
= CanSupportFeature(FEATURE_COMPRPUBKEY
); // default to compressed public keys if we want 0.6.0 wallets
97 // Create new metadata
98 int64_t nCreationTime
= GetTime();
99 CKeyMetadata
metadata(nCreationTime
);
101 // use HD key derivation if HD was enabled during wallet creation
103 DeriveNewChildKey(metadata
, secret
);
105 secret
.MakeNewKey(fCompressed
);
108 // Compressed public keys were introduced in version 0.6.0
110 SetMinVersion(FEATURE_COMPRPUBKEY
);
112 CPubKey pubkey
= secret
.GetPubKey();
113 assert(secret
.VerifyPubKey(pubkey
));
115 mapKeyMetadata
[pubkey
.GetID()] = metadata
;
116 if (!nTimeFirstKey
|| nCreationTime
< nTimeFirstKey
)
117 nTimeFirstKey
= nCreationTime
;
119 if (!AddKeyPubKey(secret
, pubkey
))
120 throw std::runtime_error(std::string(__func__
) + ": AddKey failed");
124 void CWallet::DeriveNewChildKey(CKeyMetadata
& metadata
, CKey
& secret
)
126 // for now we use a fixed keypath scheme of m/0'/0'/k
127 CKey key
; //master key seed (256bit)
128 CExtKey masterKey
; //hd master key
129 CExtKey accountKey
; //key at m/0'
130 CExtKey externalChainChildKey
; //key at m/0'/0'
131 CExtKey childKey
; //key at m/0'/0'/<n>'
133 // try to get the master key
134 if (!GetKey(hdChain
.masterKeyID
, key
))
135 throw std::runtime_error(std::string(__func__
) + ": Master key not found");
137 masterKey
.SetMaster(key
.begin(), key
.size());
140 // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
141 masterKey
.Derive(accountKey
, BIP32_HARDENED_KEY_LIMIT
);
144 accountKey
.Derive(externalChainChildKey
, BIP32_HARDENED_KEY_LIMIT
);
146 // derive child key at next index, skip keys already known to the wallet
148 // always derive hardened keys
149 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
150 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
151 externalChainChildKey
.Derive(childKey
, hdChain
.nExternalChainCounter
| BIP32_HARDENED_KEY_LIMIT
);
152 metadata
.hdKeypath
= "m/0'/0'/" + std::to_string(hdChain
.nExternalChainCounter
) + "'";
153 metadata
.hdMasterKeyID
= hdChain
.masterKeyID
;
154 // increment childkey index
155 hdChain
.nExternalChainCounter
++;
156 } while (HaveKey(childKey
.key
.GetPubKey().GetID()));
157 secret
= childKey
.key
;
159 // update the chain model in the database
160 if (!CWalletDB(strWalletFile
).WriteHDChain(hdChain
))
161 throw std::runtime_error(std::string(__func__
) + ": Writing HD chain model failed");
164 bool CWallet::AddKeyPubKey(const CKey
& secret
, const CPubKey
&pubkey
)
166 AssertLockHeld(cs_wallet
); // mapKeyMetadata
167 if (!CCryptoKeyStore::AddKeyPubKey(secret
, pubkey
))
170 // check if we need to remove from watch-only
172 script
= GetScriptForDestination(pubkey
.GetID());
173 if (HaveWatchOnly(script
))
174 RemoveWatchOnly(script
);
175 script
= GetScriptForRawPubKey(pubkey
);
176 if (HaveWatchOnly(script
))
177 RemoveWatchOnly(script
);
182 return CWalletDB(strWalletFile
).WriteKey(pubkey
,
184 mapKeyMetadata
[pubkey
.GetID()]);
189 bool CWallet::AddCryptedKey(const CPubKey
&vchPubKey
,
190 const vector
<unsigned char> &vchCryptedSecret
)
192 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey
, vchCryptedSecret
))
198 if (pwalletdbEncryption
)
199 return pwalletdbEncryption
->WriteCryptedKey(vchPubKey
,
201 mapKeyMetadata
[vchPubKey
.GetID()]);
203 return CWalletDB(strWalletFile
).WriteCryptedKey(vchPubKey
,
205 mapKeyMetadata
[vchPubKey
.GetID()]);
210 bool CWallet::LoadKeyMetadata(const CPubKey
&pubkey
, const CKeyMetadata
&meta
)
212 AssertLockHeld(cs_wallet
); // mapKeyMetadata
213 if (meta
.nCreateTime
&& (!nTimeFirstKey
|| meta
.nCreateTime
< nTimeFirstKey
))
214 nTimeFirstKey
= meta
.nCreateTime
;
216 mapKeyMetadata
[pubkey
.GetID()] = meta
;
220 bool CWallet::LoadCryptedKey(const CPubKey
&vchPubKey
, const std::vector
<unsigned char> &vchCryptedSecret
)
222 return CCryptoKeyStore::AddCryptedKey(vchPubKey
, vchCryptedSecret
);
225 bool CWallet::AddCScript(const CScript
& redeemScript
)
227 if (!CCryptoKeyStore::AddCScript(redeemScript
))
231 return CWalletDB(strWalletFile
).WriteCScript(Hash160(redeemScript
), redeemScript
);
234 bool CWallet::LoadCScript(const CScript
& redeemScript
)
236 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
237 * that never can be redeemed. However, old wallets may still contain
238 * these. Do not add them to the wallet and warn. */
239 if (redeemScript
.size() > MAX_SCRIPT_ELEMENT_SIZE
)
241 std::string strAddr
= CBitcoinAddress(CScriptID(redeemScript
)).ToString();
242 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",
243 __func__
, redeemScript
.size(), MAX_SCRIPT_ELEMENT_SIZE
, strAddr
);
247 return CCryptoKeyStore::AddCScript(redeemScript
);
250 bool CWallet::AddWatchOnly(const CScript
&dest
)
252 if (!CCryptoKeyStore::AddWatchOnly(dest
))
254 nTimeFirstKey
= 1; // No birthday information for watch-only keys.
255 NotifyWatchonlyChanged(true);
258 return CWalletDB(strWalletFile
).WriteWatchOnly(dest
);
261 bool CWallet::RemoveWatchOnly(const CScript
&dest
)
263 AssertLockHeld(cs_wallet
);
264 if (!CCryptoKeyStore::RemoveWatchOnly(dest
))
266 if (!HaveWatchOnly())
267 NotifyWatchonlyChanged(false);
269 if (!CWalletDB(strWalletFile
).EraseWatchOnly(dest
))
275 bool CWallet::LoadWatchOnly(const CScript
&dest
)
277 return CCryptoKeyStore::AddWatchOnly(dest
);
280 bool CWallet::Unlock(const SecureString
& strWalletPassphrase
)
283 CKeyingMaterial vMasterKey
;
287 BOOST_FOREACH(const MasterKeyMap::value_type
& pMasterKey
, mapMasterKeys
)
289 if(!crypter
.SetKeyFromPassphrase(strWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
))
291 if (!crypter
.Decrypt(pMasterKey
.second
.vchCryptedKey
, vMasterKey
))
292 continue; // try another master key
293 if (CCryptoKeyStore::Unlock(vMasterKey
))
300 bool CWallet::ChangeWalletPassphrase(const SecureString
& strOldWalletPassphrase
, const SecureString
& strNewWalletPassphrase
)
302 bool fWasLocked
= IsLocked();
309 CKeyingMaterial vMasterKey
;
310 BOOST_FOREACH(MasterKeyMap::value_type
& pMasterKey
, mapMasterKeys
)
312 if(!crypter
.SetKeyFromPassphrase(strOldWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
))
314 if (!crypter
.Decrypt(pMasterKey
.second
.vchCryptedKey
, vMasterKey
))
316 if (CCryptoKeyStore::Unlock(vMasterKey
))
318 int64_t nStartTime
= GetTimeMillis();
319 crypter
.SetKeyFromPassphrase(strNewWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
);
320 pMasterKey
.second
.nDeriveIterations
= pMasterKey
.second
.nDeriveIterations
* (100 / ((double)(GetTimeMillis() - nStartTime
)));
322 nStartTime
= GetTimeMillis();
323 crypter
.SetKeyFromPassphrase(strNewWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
);
324 pMasterKey
.second
.nDeriveIterations
= (pMasterKey
.second
.nDeriveIterations
+ pMasterKey
.second
.nDeriveIterations
* 100 / ((double)(GetTimeMillis() - nStartTime
))) / 2;
326 if (pMasterKey
.second
.nDeriveIterations
< 25000)
327 pMasterKey
.second
.nDeriveIterations
= 25000;
329 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey
.second
.nDeriveIterations
);
331 if (!crypter
.SetKeyFromPassphrase(strNewWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
))
333 if (!crypter
.Encrypt(vMasterKey
, pMasterKey
.second
.vchCryptedKey
))
335 CWalletDB(strWalletFile
).WriteMasterKey(pMasterKey
.first
, pMasterKey
.second
);
346 void CWallet::SetBestChain(const CBlockLocator
& loc
)
348 CWalletDB
walletdb(strWalletFile
);
349 walletdb
.WriteBestBlock(loc
);
352 bool CWallet::SetMinVersion(enum WalletFeature nVersion
, CWalletDB
* pwalletdbIn
, bool fExplicit
)
354 LOCK(cs_wallet
); // nWalletVersion
355 if (nWalletVersion
>= nVersion
)
358 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
359 if (fExplicit
&& nVersion
> nWalletMaxVersion
)
360 nVersion
= FEATURE_LATEST
;
362 nWalletVersion
= nVersion
;
364 if (nVersion
> nWalletMaxVersion
)
365 nWalletMaxVersion
= nVersion
;
369 CWalletDB
* pwalletdb
= pwalletdbIn
? pwalletdbIn
: new CWalletDB(strWalletFile
);
370 if (nWalletVersion
> 40000)
371 pwalletdb
->WriteMinVersion(nWalletVersion
);
379 bool CWallet::SetMaxVersion(int nVersion
)
381 LOCK(cs_wallet
); // nWalletVersion, nWalletMaxVersion
382 // cannot downgrade below current version
383 if (nWalletVersion
> nVersion
)
386 nWalletMaxVersion
= nVersion
;
391 set
<uint256
> CWallet::GetConflicts(const uint256
& txid
) const
394 AssertLockHeld(cs_wallet
);
396 std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.find(txid
);
397 if (it
== mapWallet
.end())
399 const CWalletTx
& wtx
= it
->second
;
401 std::pair
<TxSpends::const_iterator
, TxSpends::const_iterator
> range
;
403 BOOST_FOREACH(const CTxIn
& txin
, wtx
.tx
->vin
)
405 if (mapTxSpends
.count(txin
.prevout
) <= 1)
406 continue; // No conflict if zero or one spends
407 range
= mapTxSpends
.equal_range(txin
.prevout
);
408 for (TxSpends::const_iterator _it
= range
.first
; _it
!= range
.second
; ++_it
)
409 result
.insert(_it
->second
);
414 bool CWallet::HasWalletSpend(const uint256
& txid
) const
416 AssertLockHeld(cs_wallet
);
417 auto iter
= mapTxSpends
.lower_bound(COutPoint(txid
, 0));
418 return (iter
!= mapTxSpends
.end() && iter
->first
.hash
== txid
);
421 void CWallet::Flush(bool shutdown
)
423 bitdb
.Flush(shutdown
);
426 bool CWallet::Verify()
428 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET
))
431 LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
432 std::string walletFile
= GetArg("-wallet", DEFAULT_WALLET_DAT
);
434 LogPrintf("Using wallet %s\n", walletFile
);
435 uiInterface
.InitMessage(_("Verifying wallet..."));
437 // Wallet file must be a plain filename without a directory
438 if (walletFile
!= boost::filesystem::basename(walletFile
) + boost::filesystem::extension(walletFile
))
439 return InitError(strprintf(_("Wallet %s resides outside data directory %s"), walletFile
, GetDataDir().string()));
441 if (!bitdb
.Open(GetDataDir()))
443 // try moving the database env out of the way
444 boost::filesystem::path pathDatabase
= GetDataDir() / "database";
445 boost::filesystem::path pathDatabaseBak
= GetDataDir() / strprintf("database.%d.bak", GetTime());
447 boost::filesystem::rename(pathDatabase
, pathDatabaseBak
);
448 LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase
.string(), pathDatabaseBak
.string());
449 } catch (const boost::filesystem::filesystem_error
&) {
450 // failure is ok (well, not really, but it's not worse than what we started with)
454 if (!bitdb
.Open(GetDataDir())) {
455 // if it still fails, it probably means we can't even create the database env
456 return InitError(strprintf(_("Error initializing wallet database environment %s!"), GetDataDir()));
460 if (GetBoolArg("-salvagewallet", false))
462 // Recover readable keypairs:
463 if (!CWalletDB::Recover(bitdb
, walletFile
, true))
467 if (boost::filesystem::exists(GetDataDir() / walletFile
))
469 CDBEnv::VerifyResult r
= bitdb
.Verify(walletFile
, CWalletDB::Recover
);
470 if (r
== CDBEnv::RECOVER_OK
)
472 InitWarning(strprintf(_("Warning: Wallet file corrupt, data salvaged!"
473 " Original %s saved as %s in %s; if"
474 " your balance or transactions are incorrect you should"
475 " restore from a backup."),
476 walletFile
, "wallet.{timestamp}.bak", GetDataDir()));
478 if (r
== CDBEnv::RECOVER_FAIL
)
479 return InitError(strprintf(_("%s corrupt, salvage failed"), walletFile
));
485 void CWallet::SyncMetaData(pair
<TxSpends::iterator
, TxSpends::iterator
> range
)
487 // We want all the wallet transactions in range to have the same metadata as
488 // the oldest (smallest nOrderPos).
489 // So: find smallest nOrderPos:
491 int nMinOrderPos
= std::numeric_limits
<int>::max();
492 const CWalletTx
* copyFrom
= NULL
;
493 for (TxSpends::iterator it
= range
.first
; it
!= range
.second
; ++it
)
495 const uint256
& hash
= it
->second
;
496 int n
= mapWallet
[hash
].nOrderPos
;
497 if (n
< nMinOrderPos
)
500 copyFrom
= &mapWallet
[hash
];
503 // Now copy data from copyFrom to rest:
504 for (TxSpends::iterator it
= range
.first
; it
!= range
.second
; ++it
)
506 const uint256
& hash
= it
->second
;
507 CWalletTx
* copyTo
= &mapWallet
[hash
];
508 if (copyFrom
== copyTo
) continue;
509 if (!copyFrom
->IsEquivalentTo(*copyTo
)) continue;
510 copyTo
->mapValue
= copyFrom
->mapValue
;
511 copyTo
->vOrderForm
= copyFrom
->vOrderForm
;
512 // fTimeReceivedIsTxTime not copied on purpose
513 // nTimeReceived not copied on purpose
514 copyTo
->nTimeSmart
= copyFrom
->nTimeSmart
;
515 copyTo
->fFromMe
= copyFrom
->fFromMe
;
516 copyTo
->strFromAccount
= copyFrom
->strFromAccount
;
517 // nOrderPos not copied on purpose
518 // cached members not copied on purpose
523 * Outpoint is spent if any non-conflicted transaction
526 bool CWallet::IsSpent(const uint256
& hash
, unsigned int n
) const
528 const COutPoint
outpoint(hash
, n
);
529 pair
<TxSpends::const_iterator
, TxSpends::const_iterator
> range
;
530 range
= mapTxSpends
.equal_range(outpoint
);
532 for (TxSpends::const_iterator it
= range
.first
; it
!= range
.second
; ++it
)
534 const uint256
& wtxid
= it
->second
;
535 std::map
<uint256
, CWalletTx
>::const_iterator mit
= mapWallet
.find(wtxid
);
536 if (mit
!= mapWallet
.end()) {
537 int depth
= mit
->second
.GetDepthInMainChain();
538 if (depth
> 0 || (depth
== 0 && !mit
->second
.isAbandoned()))
539 return true; // Spent
545 void CWallet::AddToSpends(const COutPoint
& outpoint
, const uint256
& wtxid
)
547 mapTxSpends
.insert(make_pair(outpoint
, wtxid
));
549 pair
<TxSpends::iterator
, TxSpends::iterator
> range
;
550 range
= mapTxSpends
.equal_range(outpoint
);
555 void CWallet::AddToSpends(const uint256
& wtxid
)
557 assert(mapWallet
.count(wtxid
));
558 CWalletTx
& thisTx
= mapWallet
[wtxid
];
559 if (thisTx
.IsCoinBase()) // Coinbases don't spend anything!
562 BOOST_FOREACH(const CTxIn
& txin
, thisTx
.tx
->vin
)
563 AddToSpends(txin
.prevout
, wtxid
);
566 bool CWallet::EncryptWallet(const SecureString
& strWalletPassphrase
)
571 CKeyingMaterial vMasterKey
;
573 vMasterKey
.resize(WALLET_CRYPTO_KEY_SIZE
);
574 GetStrongRandBytes(&vMasterKey
[0], WALLET_CRYPTO_KEY_SIZE
);
576 CMasterKey kMasterKey
;
578 kMasterKey
.vchSalt
.resize(WALLET_CRYPTO_SALT_SIZE
);
579 GetStrongRandBytes(&kMasterKey
.vchSalt
[0], WALLET_CRYPTO_SALT_SIZE
);
582 int64_t nStartTime
= GetTimeMillis();
583 crypter
.SetKeyFromPassphrase(strWalletPassphrase
, kMasterKey
.vchSalt
, 25000, kMasterKey
.nDerivationMethod
);
584 kMasterKey
.nDeriveIterations
= 2500000 / ((double)(GetTimeMillis() - nStartTime
));
586 nStartTime
= GetTimeMillis();
587 crypter
.SetKeyFromPassphrase(strWalletPassphrase
, kMasterKey
.vchSalt
, kMasterKey
.nDeriveIterations
, kMasterKey
.nDerivationMethod
);
588 kMasterKey
.nDeriveIterations
= (kMasterKey
.nDeriveIterations
+ kMasterKey
.nDeriveIterations
* 100 / ((double)(GetTimeMillis() - nStartTime
))) / 2;
590 if (kMasterKey
.nDeriveIterations
< 25000)
591 kMasterKey
.nDeriveIterations
= 25000;
593 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey
.nDeriveIterations
);
595 if (!crypter
.SetKeyFromPassphrase(strWalletPassphrase
, kMasterKey
.vchSalt
, kMasterKey
.nDeriveIterations
, kMasterKey
.nDerivationMethod
))
597 if (!crypter
.Encrypt(vMasterKey
, kMasterKey
.vchCryptedKey
))
602 mapMasterKeys
[++nMasterKeyMaxID
] = kMasterKey
;
605 assert(!pwalletdbEncryption
);
606 pwalletdbEncryption
= new CWalletDB(strWalletFile
);
607 if (!pwalletdbEncryption
->TxnBegin()) {
608 delete pwalletdbEncryption
;
609 pwalletdbEncryption
= NULL
;
612 pwalletdbEncryption
->WriteMasterKey(nMasterKeyMaxID
, kMasterKey
);
615 if (!EncryptKeys(vMasterKey
))
618 pwalletdbEncryption
->TxnAbort();
619 delete pwalletdbEncryption
;
621 // We now probably have half of our keys encrypted in memory, and half not...
622 // die and let the user reload the unencrypted wallet.
626 // Encryption was introduced in version 0.4.0
627 SetMinVersion(FEATURE_WALLETCRYPT
, pwalletdbEncryption
, true);
631 if (!pwalletdbEncryption
->TxnCommit()) {
632 delete pwalletdbEncryption
;
633 // We now have keys encrypted in memory, but not on disk...
634 // die to avoid confusion and let the user reload the unencrypted wallet.
638 delete pwalletdbEncryption
;
639 pwalletdbEncryption
= NULL
;
643 Unlock(strWalletPassphrase
);
645 // if we are using HD, replace the HD master key (seed) with a new one
648 CPubKey masterPubKey
= GenerateNewHDMasterKey();
649 if (!SetHDMasterKey(masterPubKey
))
656 // Need to completely rewrite the wallet file; if we don't, bdb might keep
657 // bits of the unencrypted private key in slack space in the database file.
658 CDB::Rewrite(strWalletFile
);
661 NotifyStatusChanged(this);
666 DBErrors
CWallet::ReorderTransactions()
669 CWalletDB
walletdb(strWalletFile
);
671 // Old wallets didn't have any defined order for transactions
672 // Probably a bad idea to change the output of this
674 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
675 typedef pair
<CWalletTx
*, CAccountingEntry
*> TxPair
;
676 typedef multimap
<int64_t, TxPair
> TxItems
;
679 for (map
<uint256
, CWalletTx
>::iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
681 CWalletTx
* wtx
= &((*it
).second
);
682 txByTime
.insert(make_pair(wtx
->nTimeReceived
, TxPair(wtx
, (CAccountingEntry
*)0)));
684 list
<CAccountingEntry
> acentries
;
685 walletdb
.ListAccountCreditDebit("", acentries
);
686 BOOST_FOREACH(CAccountingEntry
& entry
, acentries
)
688 txByTime
.insert(make_pair(entry
.nTime
, TxPair((CWalletTx
*)0, &entry
)));
692 std::vector
<int64_t> nOrderPosOffsets
;
693 for (TxItems::iterator it
= txByTime
.begin(); it
!= txByTime
.end(); ++it
)
695 CWalletTx
*const pwtx
= (*it
).second
.first
;
696 CAccountingEntry
*const pacentry
= (*it
).second
.second
;
697 int64_t& nOrderPos
= (pwtx
!= 0) ? pwtx
->nOrderPos
: pacentry
->nOrderPos
;
701 nOrderPos
= nOrderPosNext
++;
702 nOrderPosOffsets
.push_back(nOrderPos
);
706 if (!walletdb
.WriteTx(*pwtx
))
710 if (!walletdb
.WriteAccountingEntry(pacentry
->nEntryNo
, *pacentry
))
715 int64_t nOrderPosOff
= 0;
716 BOOST_FOREACH(const int64_t& nOffsetStart
, nOrderPosOffsets
)
718 if (nOrderPos
>= nOffsetStart
)
721 nOrderPos
+= nOrderPosOff
;
722 nOrderPosNext
= std::max(nOrderPosNext
, nOrderPos
+ 1);
727 // Since we're changing the order, write it back
730 if (!walletdb
.WriteTx(*pwtx
))
734 if (!walletdb
.WriteAccountingEntry(pacentry
->nEntryNo
, *pacentry
))
738 walletdb
.WriteOrderPosNext(nOrderPosNext
);
743 int64_t CWallet::IncOrderPosNext(CWalletDB
*pwalletdb
)
745 AssertLockHeld(cs_wallet
); // nOrderPosNext
746 int64_t nRet
= nOrderPosNext
++;
748 pwalletdb
->WriteOrderPosNext(nOrderPosNext
);
750 CWalletDB(strWalletFile
).WriteOrderPosNext(nOrderPosNext
);
755 bool CWallet::AccountMove(std::string strFrom
, std::string strTo
, CAmount nAmount
, std::string strComment
)
757 CWalletDB
walletdb(strWalletFile
);
758 if (!walletdb
.TxnBegin())
761 int64_t nNow
= GetAdjustedTime();
764 CAccountingEntry debit
;
765 debit
.nOrderPos
= IncOrderPosNext(&walletdb
);
766 debit
.strAccount
= strFrom
;
767 debit
.nCreditDebit
= -nAmount
;
769 debit
.strOtherAccount
= strTo
;
770 debit
.strComment
= strComment
;
771 AddAccountingEntry(debit
, &walletdb
);
774 CAccountingEntry credit
;
775 credit
.nOrderPos
= IncOrderPosNext(&walletdb
);
776 credit
.strAccount
= strTo
;
777 credit
.nCreditDebit
= nAmount
;
779 credit
.strOtherAccount
= strFrom
;
780 credit
.strComment
= strComment
;
781 AddAccountingEntry(credit
, &walletdb
);
783 if (!walletdb
.TxnCommit())
789 bool CWallet::GetAccountPubkey(CPubKey
&pubKey
, std::string strAccount
, bool bForceNew
)
791 CWalletDB
walletdb(strWalletFile
);
794 walletdb
.ReadAccount(strAccount
, account
);
797 if (!account
.vchPubKey
.IsValid())
800 // Check if the current key has been used
801 CScript scriptPubKey
= GetScriptForDestination(account
.vchPubKey
.GetID());
802 for (map
<uint256
, CWalletTx
>::iterator it
= mapWallet
.begin();
803 it
!= mapWallet
.end() && account
.vchPubKey
.IsValid();
805 BOOST_FOREACH(const CTxOut
& txout
, (*it
).second
.tx
->vout
)
806 if (txout
.scriptPubKey
== scriptPubKey
) {
813 // Generate a new key
815 if (!GetKeyFromPool(account
.vchPubKey
))
818 SetAddressBook(account
.vchPubKey
.GetID(), strAccount
, "receive");
819 walletdb
.WriteAccount(strAccount
, account
);
822 pubKey
= account
.vchPubKey
;
827 void CWallet::MarkDirty()
831 BOOST_FOREACH(PAIRTYPE(const uint256
, CWalletTx
)& item
, mapWallet
)
832 item
.second
.MarkDirty();
836 bool CWallet::MarkReplaced(const uint256
& originalHash
, const uint256
& newHash
)
840 auto mi
= mapWallet
.find(originalHash
);
842 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
843 assert(mi
!= mapWallet
.end());
845 CWalletTx
& wtx
= (*mi
).second
;
847 // Ensure for now that we're not overwriting data
848 assert(wtx
.mapValue
.count("replaced_by_txid") == 0);
850 wtx
.mapValue
["replaced_by_txid"] = newHash
.ToString();
852 CWalletDB
walletdb(strWalletFile
, "r+");
855 if (!walletdb
.WriteTx(wtx
)) {
856 LogPrintf("%s: Updating walletdb tx %s failed", __func__
, wtx
.GetHash().ToString());
860 NotifyTransactionChanged(this, originalHash
, CT_UPDATED
);
865 bool CWallet::AddToWallet(const CWalletTx
& wtxIn
, bool fFlushOnClose
)
869 CWalletDB
walletdb(strWalletFile
, "r+", fFlushOnClose
);
871 uint256 hash
= wtxIn
.GetHash();
873 // Inserts only if not already there, returns tx inserted or tx found
874 pair
<map
<uint256
, CWalletTx
>::iterator
, bool> ret
= mapWallet
.insert(make_pair(hash
, wtxIn
));
875 CWalletTx
& wtx
= (*ret
.first
).second
;
876 wtx
.BindWallet(this);
877 bool fInsertedNew
= ret
.second
;
880 wtx
.nTimeReceived
= GetAdjustedTime();
881 wtx
.nOrderPos
= IncOrderPosNext(&walletdb
);
882 wtxOrdered
.insert(make_pair(wtx
.nOrderPos
, TxPair(&wtx
, (CAccountingEntry
*)0)));
884 wtx
.nTimeSmart
= wtx
.nTimeReceived
;
885 if (!wtxIn
.hashUnset())
887 if (mapBlockIndex
.count(wtxIn
.hashBlock
))
889 int64_t latestNow
= wtx
.nTimeReceived
;
890 int64_t latestEntry
= 0;
892 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
893 int64_t latestTolerated
= latestNow
+ 300;
894 const TxItems
& txOrdered
= wtxOrdered
;
895 for (TxItems::const_reverse_iterator it
= txOrdered
.rbegin(); it
!= txOrdered
.rend(); ++it
)
897 CWalletTx
*const pwtx
= (*it
).second
.first
;
900 CAccountingEntry
*const pacentry
= (*it
).second
.second
;
904 nSmartTime
= pwtx
->nTimeSmart
;
906 nSmartTime
= pwtx
->nTimeReceived
;
909 nSmartTime
= pacentry
->nTime
;
910 if (nSmartTime
<= latestTolerated
)
912 latestEntry
= nSmartTime
;
913 if (nSmartTime
> latestNow
)
914 latestNow
= nSmartTime
;
920 int64_t blocktime
= mapBlockIndex
[wtxIn
.hashBlock
]->GetBlockTime();
921 wtx
.nTimeSmart
= std::max(latestEntry
, std::min(blocktime
, latestNow
));
924 LogPrintf("AddToWallet(): found %s in block %s not in index\n",
925 wtxIn
.GetHash().ToString(),
926 wtxIn
.hashBlock
.ToString());
931 bool fUpdated
= false;
935 if (!wtxIn
.hashUnset() && wtxIn
.hashBlock
!= wtx
.hashBlock
)
937 wtx
.hashBlock
= wtxIn
.hashBlock
;
940 // If no longer abandoned, update
941 if (wtxIn
.hashBlock
.IsNull() && wtx
.isAbandoned())
943 wtx
.hashBlock
= wtxIn
.hashBlock
;
946 if (wtxIn
.nIndex
!= -1 && (wtxIn
.nIndex
!= wtx
.nIndex
))
948 wtx
.nIndex
= wtxIn
.nIndex
;
951 if (wtxIn
.fFromMe
&& wtxIn
.fFromMe
!= wtx
.fFromMe
)
953 wtx
.fFromMe
= wtxIn
.fFromMe
;
959 LogPrintf("AddToWallet %s %s%s\n", wtxIn
.GetHash().ToString(), (fInsertedNew
? "new" : ""), (fUpdated
? "update" : ""));
962 if (fInsertedNew
|| fUpdated
)
963 if (!walletdb
.WriteTx(wtx
))
966 // Break debit/credit balance caches:
969 // Notify UI of new or updated transaction
970 NotifyTransactionChanged(this, hash
, fInsertedNew
? CT_NEW
: CT_UPDATED
);
972 // notify an external script when a wallet transaction comes in or is updated
973 std::string strCmd
= GetArg("-walletnotify", "");
975 if ( !strCmd
.empty())
977 boost::replace_all(strCmd
, "%s", wtxIn
.GetHash().GetHex());
978 boost::thread
t(runCommand
, strCmd
); // thread runs free
984 bool CWallet::LoadToWallet(const CWalletTx
& wtxIn
)
986 uint256 hash
= wtxIn
.GetHash();
988 mapWallet
[hash
] = wtxIn
;
989 CWalletTx
& wtx
= mapWallet
[hash
];
990 wtx
.BindWallet(this);
991 wtxOrdered
.insert(make_pair(wtx
.nOrderPos
, TxPair(&wtx
, (CAccountingEntry
*)0)));
993 BOOST_FOREACH(const CTxIn
& txin
, wtx
.tx
->vin
) {
994 if (mapWallet
.count(txin
.prevout
.hash
)) {
995 CWalletTx
& prevtx
= mapWallet
[txin
.prevout
.hash
];
996 if (prevtx
.nIndex
== -1 && !prevtx
.hashUnset()) {
997 MarkConflicted(prevtx
.hashBlock
, wtx
.GetHash());
1006 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
1007 * be set when the transaction was known to be included in a block. When
1008 * posInBlock = SYNC_TRANSACTION_NOT_IN_BLOCK (-1) , then wallet state is not
1009 * updated in AddToWallet, but notifications happen and cached balances are
1011 * If fUpdate is true, existing transactions will be updated.
1012 * TODO: One exception to this is that the abandoned state is cleared under the
1013 * assumption that any further notification of a transaction that was considered
1014 * abandoned is an indication that it is not safe to be considered abandoned.
1015 * Abandoned state should probably be more carefully tracked via different
1016 * posInBlock signals or by checking mempool presence when necessary.
1018 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction
& tx
, const CBlockIndex
* pIndex
, int posInBlock
, bool fUpdate
)
1021 AssertLockHeld(cs_wallet
);
1023 if (posInBlock
!= -1) {
1024 BOOST_FOREACH(const CTxIn
& txin
, tx
.vin
) {
1025 std::pair
<TxSpends::const_iterator
, TxSpends::const_iterator
> range
= mapTxSpends
.equal_range(txin
.prevout
);
1026 while (range
.first
!= range
.second
) {
1027 if (range
.first
->second
!= tx
.GetHash()) {
1028 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
);
1029 MarkConflicted(pIndex
->GetBlockHash(), range
.first
->second
);
1036 bool fExisted
= mapWallet
.count(tx
.GetHash()) != 0;
1037 if (fExisted
&& !fUpdate
) return false;
1038 if (fExisted
|| IsMine(tx
) || IsFromMe(tx
))
1040 CWalletTx
wtx(this, MakeTransactionRef(tx
));
1042 // Get merkle branch if transaction was found in a block
1043 if (posInBlock
!= -1)
1044 wtx
.SetMerkleBranch(pIndex
, posInBlock
);
1046 return AddToWallet(wtx
, false);
1052 bool CWallet::AbandonTransaction(const uint256
& hashTx
)
1054 LOCK2(cs_main
, cs_wallet
);
1056 CWalletDB
walletdb(strWalletFile
, "r+");
1058 std::set
<uint256
> todo
;
1059 std::set
<uint256
> done
;
1061 // Can't mark abandoned if confirmed or in mempool
1062 assert(mapWallet
.count(hashTx
));
1063 CWalletTx
& origtx
= mapWallet
[hashTx
];
1064 if (origtx
.GetDepthInMainChain() > 0 || origtx
.InMempool()) {
1068 todo
.insert(hashTx
);
1070 while (!todo
.empty()) {
1071 uint256 now
= *todo
.begin();
1074 assert(mapWallet
.count(now
));
1075 CWalletTx
& wtx
= mapWallet
[now
];
1076 int currentconfirm
= wtx
.GetDepthInMainChain();
1077 // If the orig tx was not in block, none of its spends can be
1078 assert(currentconfirm
<= 0);
1079 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1080 if (currentconfirm
== 0 && !wtx
.isAbandoned()) {
1081 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1082 assert(!wtx
.InMempool());
1086 walletdb
.WriteTx(wtx
);
1087 NotifyTransactionChanged(this, wtx
.GetHash(), CT_UPDATED
);
1088 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1089 TxSpends::const_iterator iter
= mapTxSpends
.lower_bound(COutPoint(hashTx
, 0));
1090 while (iter
!= mapTxSpends
.end() && iter
->first
.hash
== now
) {
1091 if (!done
.count(iter
->second
)) {
1092 todo
.insert(iter
->second
);
1096 // If a transaction changes 'conflicted' state, that changes the balance
1097 // available of the outputs it spends. So force those to be recomputed
1098 BOOST_FOREACH(const CTxIn
& txin
, wtx
.tx
->vin
)
1100 if (mapWallet
.count(txin
.prevout
.hash
))
1101 mapWallet
[txin
.prevout
.hash
].MarkDirty();
1109 void CWallet::MarkConflicted(const uint256
& hashBlock
, const uint256
& hashTx
)
1111 LOCK2(cs_main
, cs_wallet
);
1113 int conflictconfirms
= 0;
1114 if (mapBlockIndex
.count(hashBlock
)) {
1115 CBlockIndex
* pindex
= mapBlockIndex
[hashBlock
];
1116 if (chainActive
.Contains(pindex
)) {
1117 conflictconfirms
= -(chainActive
.Height() - pindex
->nHeight
+ 1);
1120 // If number of conflict confirms cannot be determined, this means
1121 // that the block is still unknown or not yet part of the main chain,
1122 // for example when loading the wallet during a reindex. Do nothing in that
1124 if (conflictconfirms
>= 0)
1127 // Do not flush the wallet here for performance reasons
1128 CWalletDB
walletdb(strWalletFile
, "r+", false);
1130 std::set
<uint256
> todo
;
1131 std::set
<uint256
> done
;
1133 todo
.insert(hashTx
);
1135 while (!todo
.empty()) {
1136 uint256 now
= *todo
.begin();
1139 assert(mapWallet
.count(now
));
1140 CWalletTx
& wtx
= mapWallet
[now
];
1141 int currentconfirm
= wtx
.GetDepthInMainChain();
1142 if (conflictconfirms
< currentconfirm
) {
1143 // Block is 'more conflicted' than current confirm; update.
1144 // Mark transaction as conflicted with this block.
1146 wtx
.hashBlock
= hashBlock
;
1148 walletdb
.WriteTx(wtx
);
1149 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1150 TxSpends::const_iterator iter
= mapTxSpends
.lower_bound(COutPoint(now
, 0));
1151 while (iter
!= mapTxSpends
.end() && iter
->first
.hash
== now
) {
1152 if (!done
.count(iter
->second
)) {
1153 todo
.insert(iter
->second
);
1157 // If a transaction changes 'conflicted' state, that changes the balance
1158 // available of the outputs it spends. So force those to be recomputed
1159 BOOST_FOREACH(const CTxIn
& txin
, wtx
.tx
->vin
)
1161 if (mapWallet
.count(txin
.prevout
.hash
))
1162 mapWallet
[txin
.prevout
.hash
].MarkDirty();
1168 void CWallet::SyncTransaction(const CTransaction
& tx
, const CBlockIndex
*pindex
, int posInBlock
)
1170 LOCK2(cs_main
, cs_wallet
);
1172 if (!AddToWalletIfInvolvingMe(tx
, pindex
, posInBlock
, true))
1173 return; // Not one of ours
1175 // If a transaction changes 'conflicted' state, that changes the balance
1176 // available of the outputs it spends. So force those to be
1177 // recomputed, also:
1178 BOOST_FOREACH(const CTxIn
& txin
, tx
.vin
)
1180 if (mapWallet
.count(txin
.prevout
.hash
))
1181 mapWallet
[txin
.prevout
.hash
].MarkDirty();
1186 isminetype
CWallet::IsMine(const CTxIn
&txin
) const
1190 map
<uint256
, CWalletTx
>::const_iterator mi
= mapWallet
.find(txin
.prevout
.hash
);
1191 if (mi
!= mapWallet
.end())
1193 const CWalletTx
& prev
= (*mi
).second
;
1194 if (txin
.prevout
.n
< prev
.tx
->vout
.size())
1195 return IsMine(prev
.tx
->vout
[txin
.prevout
.n
]);
1201 // Note that this function doesn't distinguish between a 0-valued input,
1202 // and a not-"is mine" (according to the filter) input.
1203 CAmount
CWallet::GetDebit(const CTxIn
&txin
, const isminefilter
& filter
) const
1207 map
<uint256
, CWalletTx
>::const_iterator mi
= mapWallet
.find(txin
.prevout
.hash
);
1208 if (mi
!= mapWallet
.end())
1210 const CWalletTx
& prev
= (*mi
).second
;
1211 if (txin
.prevout
.n
< prev
.tx
->vout
.size())
1212 if (IsMine(prev
.tx
->vout
[txin
.prevout
.n
]) & filter
)
1213 return prev
.tx
->vout
[txin
.prevout
.n
].nValue
;
1219 isminetype
CWallet::IsMine(const CTxOut
& txout
) const
1221 return ::IsMine(*this, txout
.scriptPubKey
);
1224 CAmount
CWallet::GetCredit(const CTxOut
& txout
, const isminefilter
& filter
) const
1226 if (!MoneyRange(txout
.nValue
))
1227 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1228 return ((IsMine(txout
) & filter
) ? txout
.nValue
: 0);
1231 bool CWallet::IsChange(const CTxOut
& txout
) const
1233 // TODO: fix handling of 'change' outputs. The assumption is that any
1234 // payment to a script that is ours, but is not in the address book
1235 // is change. That assumption is likely to break when we implement multisignature
1236 // wallets that return change back into a multi-signature-protected address;
1237 // a better way of identifying which outputs are 'the send' and which are
1238 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1239 // which output, if any, was change).
1240 if (::IsMine(*this, txout
.scriptPubKey
))
1242 CTxDestination address
;
1243 if (!ExtractDestination(txout
.scriptPubKey
, address
))
1247 if (!mapAddressBook
.count(address
))
1253 CAmount
CWallet::GetChange(const CTxOut
& txout
) const
1255 if (!MoneyRange(txout
.nValue
))
1256 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1257 return (IsChange(txout
) ? txout
.nValue
: 0);
1260 bool CWallet::IsMine(const CTransaction
& tx
) const
1262 BOOST_FOREACH(const CTxOut
& txout
, tx
.vout
)
1268 bool CWallet::IsFromMe(const CTransaction
& tx
) const
1270 return (GetDebit(tx
, ISMINE_ALL
) > 0);
1273 CAmount
CWallet::GetDebit(const CTransaction
& tx
, const isminefilter
& filter
) const
1276 BOOST_FOREACH(const CTxIn
& txin
, tx
.vin
)
1278 nDebit
+= GetDebit(txin
, filter
);
1279 if (!MoneyRange(nDebit
))
1280 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1285 bool CWallet::IsAllFromMe(const CTransaction
& tx
, const isminefilter
& filter
) const
1289 BOOST_FOREACH(const CTxIn
& txin
, tx
.vin
)
1291 auto mi
= mapWallet
.find(txin
.prevout
.hash
);
1292 if (mi
== mapWallet
.end())
1293 return false; // any unknown inputs can't be from us
1295 const CWalletTx
& prev
= (*mi
).second
;
1297 if (txin
.prevout
.n
>= prev
.tx
->vout
.size())
1298 return false; // invalid input!
1300 if (!(IsMine(prev
.tx
->vout
[txin
.prevout
.n
]) & filter
))
1306 CAmount
CWallet::GetCredit(const CTransaction
& tx
, const isminefilter
& filter
) const
1308 CAmount nCredit
= 0;
1309 BOOST_FOREACH(const CTxOut
& txout
, tx
.vout
)
1311 nCredit
+= GetCredit(txout
, filter
);
1312 if (!MoneyRange(nCredit
))
1313 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1318 CAmount
CWallet::GetChange(const CTransaction
& tx
) const
1320 CAmount nChange
= 0;
1321 BOOST_FOREACH(const CTxOut
& txout
, tx
.vout
)
1323 nChange
+= GetChange(txout
);
1324 if (!MoneyRange(nChange
))
1325 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1330 CPubKey
CWallet::GenerateNewHDMasterKey()
1333 key
.MakeNewKey(true);
1335 int64_t nCreationTime
= GetTime();
1336 CKeyMetadata
metadata(nCreationTime
);
1338 // calculate the pubkey
1339 CPubKey pubkey
= key
.GetPubKey();
1340 assert(key
.VerifyPubKey(pubkey
));
1342 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1343 metadata
.hdKeypath
= "m";
1344 metadata
.hdMasterKeyID
= pubkey
.GetID();
1349 // mem store the metadata
1350 mapKeyMetadata
[pubkey
.GetID()] = metadata
;
1352 // write the key&metadata to the database
1353 if (!AddKeyPubKey(key
, pubkey
))
1354 throw std::runtime_error(std::string(__func__
) + ": AddKeyPubKey failed");
1360 bool CWallet::SetHDMasterKey(const CPubKey
& pubkey
)
1364 // ensure this wallet.dat can only be opened by clients supporting HD
1365 SetMinVersion(FEATURE_HD
);
1367 // store the keyid (hash160) together with
1368 // the child index counter in the database
1369 // as a hdchain object
1370 CHDChain newHdChain
;
1371 newHdChain
.masterKeyID
= pubkey
.GetID();
1372 SetHDChain(newHdChain
, false);
1377 bool CWallet::SetHDChain(const CHDChain
& chain
, bool memonly
)
1380 if (!memonly
&& !CWalletDB(strWalletFile
).WriteHDChain(chain
))
1381 throw runtime_error(std::string(__func__
) + ": writing chain failed");
1387 bool CWallet::IsHDEnabled()
1389 return !hdChain
.masterKeyID
.IsNull();
1392 int64_t CWalletTx::GetTxTime() const
1394 int64_t n
= nTimeSmart
;
1395 return n
? n
: nTimeReceived
;
1398 int CWalletTx::GetRequestCount() const
1400 // Returns -1 if it wasn't being tracked
1403 LOCK(pwallet
->cs_wallet
);
1409 map
<uint256
, int>::const_iterator mi
= pwallet
->mapRequestCount
.find(hashBlock
);
1410 if (mi
!= pwallet
->mapRequestCount
.end())
1411 nRequests
= (*mi
).second
;
1416 // Did anyone request this transaction?
1417 map
<uint256
, int>::const_iterator mi
= pwallet
->mapRequestCount
.find(GetHash());
1418 if (mi
!= pwallet
->mapRequestCount
.end())
1420 nRequests
= (*mi
).second
;
1422 // How about the block it's in?
1423 if (nRequests
== 0 && !hashUnset())
1425 map
<uint256
, int>::const_iterator _mi
= pwallet
->mapRequestCount
.find(hashBlock
);
1426 if (_mi
!= pwallet
->mapRequestCount
.end())
1427 nRequests
= (*_mi
).second
;
1429 nRequests
= 1; // If it's in someone else's block it must have got out
1437 void CWalletTx::GetAmounts(list
<COutputEntry
>& listReceived
,
1438 list
<COutputEntry
>& listSent
, CAmount
& nFee
, string
& strSentAccount
, const isminefilter
& filter
) const
1441 listReceived
.clear();
1443 strSentAccount
= strFromAccount
;
1446 CAmount nDebit
= GetDebit(filter
);
1447 if (nDebit
> 0) // debit>0 means we signed/sent this transaction
1449 CAmount nValueOut
= tx
->GetValueOut();
1450 nFee
= nDebit
- nValueOut
;
1454 for (unsigned int i
= 0; i
< tx
->vout
.size(); ++i
)
1456 const CTxOut
& txout
= tx
->vout
[i
];
1457 isminetype fIsMine
= pwallet
->IsMine(txout
);
1458 // Only need to handle txouts if AT LEAST one of these is true:
1459 // 1) they debit from us (sent)
1460 // 2) the output is to us (received)
1463 // Don't report 'change' txouts
1464 if (pwallet
->IsChange(txout
))
1467 else if (!(fIsMine
& filter
))
1470 // In either case, we need to get the destination address
1471 CTxDestination address
;
1473 if (!ExtractDestination(txout
.scriptPubKey
, address
) && !txout
.scriptPubKey
.IsUnspendable())
1475 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1476 this->GetHash().ToString());
1477 address
= CNoDestination();
1480 COutputEntry output
= {address
, txout
.nValue
, (int)i
};
1482 // If we are debited by the transaction, add the output as a "sent" entry
1484 listSent
.push_back(output
);
1486 // If we are receiving the output, add it as a "received" entry
1487 if (fIsMine
& filter
)
1488 listReceived
.push_back(output
);
1493 void CWalletTx::GetAccountAmounts(const string
& strAccount
, CAmount
& nReceived
,
1494 CAmount
& nSent
, CAmount
& nFee
, const isminefilter
& filter
) const
1496 nReceived
= nSent
= nFee
= 0;
1499 string strSentAccount
;
1500 list
<COutputEntry
> listReceived
;
1501 list
<COutputEntry
> listSent
;
1502 GetAmounts(listReceived
, listSent
, allFee
, strSentAccount
, filter
);
1504 if (strAccount
== strSentAccount
)
1506 BOOST_FOREACH(const COutputEntry
& s
, listSent
)
1511 LOCK(pwallet
->cs_wallet
);
1512 BOOST_FOREACH(const COutputEntry
& r
, listReceived
)
1514 if (pwallet
->mapAddressBook
.count(r
.destination
))
1516 map
<CTxDestination
, CAddressBookData
>::const_iterator mi
= pwallet
->mapAddressBook
.find(r
.destination
);
1517 if (mi
!= pwallet
->mapAddressBook
.end() && (*mi
).second
.name
== strAccount
)
1518 nReceived
+= r
.amount
;
1520 else if (strAccount
.empty())
1522 nReceived
+= r
.amount
;
1529 * Scan the block chain (starting in pindexStart) for transactions
1530 * from or to us. If fUpdate is true, found transactions that already
1531 * exist in the wallet will be updated.
1533 int CWallet::ScanForWalletTransactions(CBlockIndex
* pindexStart
, bool fUpdate
)
1536 int64_t nNow
= GetTime();
1537 const CChainParams
& chainParams
= Params();
1539 CBlockIndex
* pindex
= pindexStart
;
1541 LOCK2(cs_main
, cs_wallet
);
1543 // no need to read and scan block, if block was created before
1544 // our wallet birthday (as adjusted for block time variability)
1545 while (pindex
&& nTimeFirstKey
&& (pindex
->GetBlockTime() < (nTimeFirstKey
- 7200)))
1546 pindex
= chainActive
.Next(pindex
);
1548 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1549 double dProgressStart
= GuessVerificationProgress(chainParams
.TxData(), pindex
);
1550 double dProgressTip
= GuessVerificationProgress(chainParams
.TxData(), chainActive
.Tip());
1553 if (pindex
->nHeight
% 100 == 0 && dProgressTip
- dProgressStart
> 0.0)
1554 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams
.TxData(), pindex
) - dProgressStart
) / (dProgressTip
- dProgressStart
) * 100))));
1557 ReadBlockFromDisk(block
, pindex
, Params().GetConsensus());
1559 for (posInBlock
= 0; posInBlock
< (int)block
.vtx
.size(); posInBlock
++)
1561 if (AddToWalletIfInvolvingMe(*block
.vtx
[posInBlock
], pindex
, posInBlock
, fUpdate
))
1564 pindex
= chainActive
.Next(pindex
);
1565 if (GetTime() >= nNow
+ 60) {
1567 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex
->nHeight
, GuessVerificationProgress(chainParams
.TxData(), pindex
));
1570 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1575 void CWallet::ReacceptWalletTransactions()
1577 // If transactions aren't being broadcasted, don't let them into local mempool either
1578 if (!fBroadcastTransactions
)
1580 LOCK2(cs_main
, cs_wallet
);
1581 std::map
<int64_t, CWalletTx
*> mapSorted
;
1583 // Sort pending wallet transactions based on their initial wallet insertion order
1584 BOOST_FOREACH(PAIRTYPE(const uint256
, CWalletTx
)& item
, mapWallet
)
1586 const uint256
& wtxid
= item
.first
;
1587 CWalletTx
& wtx
= item
.second
;
1588 assert(wtx
.GetHash() == wtxid
);
1590 int nDepth
= wtx
.GetDepthInMainChain();
1592 if (!wtx
.IsCoinBase() && (nDepth
== 0 && !wtx
.isAbandoned())) {
1593 mapSorted
.insert(std::make_pair(wtx
.nOrderPos
, &wtx
));
1597 // Try to add wallet transactions to memory pool
1598 BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx
*)& item
, mapSorted
)
1600 CWalletTx
& wtx
= *(item
.second
);
1603 CValidationState state
;
1604 wtx
.AcceptToMemoryPool(maxTxFee
, state
);
1608 bool CWalletTx::RelayWalletTransaction(CConnman
* connman
)
1610 assert(pwallet
->GetBroadcastTransactions());
1611 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1613 CValidationState state
;
1614 /* GetDepthInMainChain already catches known conflicts. */
1615 if (InMempool() || AcceptToMemoryPool(maxTxFee
, state
)) {
1616 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1618 CInv
inv(MSG_TX
, GetHash());
1619 connman
->ForEachNode([&inv
](CNode
* pnode
)
1621 pnode
->PushInventory(inv
);
1630 set
<uint256
> CWalletTx::GetConflicts() const
1632 set
<uint256
> result
;
1633 if (pwallet
!= NULL
)
1635 uint256 myHash
= GetHash();
1636 result
= pwallet
->GetConflicts(myHash
);
1637 result
.erase(myHash
);
1642 CAmount
CWalletTx::GetDebit(const isminefilter
& filter
) const
1644 if (tx
->vin
.empty())
1648 if(filter
& ISMINE_SPENDABLE
)
1651 debit
+= nDebitCached
;
1654 nDebitCached
= pwallet
->GetDebit(*this, ISMINE_SPENDABLE
);
1655 fDebitCached
= true;
1656 debit
+= nDebitCached
;
1659 if(filter
& ISMINE_WATCH_ONLY
)
1661 if(fWatchDebitCached
)
1662 debit
+= nWatchDebitCached
;
1665 nWatchDebitCached
= pwallet
->GetDebit(*this, ISMINE_WATCH_ONLY
);
1666 fWatchDebitCached
= true;
1667 debit
+= nWatchDebitCached
;
1673 CAmount
CWalletTx::GetCredit(const isminefilter
& filter
) const
1675 // Must wait until coinbase is safely deep enough in the chain before valuing it
1676 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1680 if (filter
& ISMINE_SPENDABLE
)
1682 // GetBalance can assume transactions in mapWallet won't change
1684 credit
+= nCreditCached
;
1687 nCreditCached
= pwallet
->GetCredit(*this, ISMINE_SPENDABLE
);
1688 fCreditCached
= true;
1689 credit
+= nCreditCached
;
1692 if (filter
& ISMINE_WATCH_ONLY
)
1694 if (fWatchCreditCached
)
1695 credit
+= nWatchCreditCached
;
1698 nWatchCreditCached
= pwallet
->GetCredit(*this, ISMINE_WATCH_ONLY
);
1699 fWatchCreditCached
= true;
1700 credit
+= nWatchCreditCached
;
1706 CAmount
CWalletTx::GetImmatureCredit(bool fUseCache
) const
1708 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1710 if (fUseCache
&& fImmatureCreditCached
)
1711 return nImmatureCreditCached
;
1712 nImmatureCreditCached
= pwallet
->GetCredit(*this, ISMINE_SPENDABLE
);
1713 fImmatureCreditCached
= true;
1714 return nImmatureCreditCached
;
1720 CAmount
CWalletTx::GetAvailableCredit(bool fUseCache
) const
1725 // Must wait until coinbase is safely deep enough in the chain before valuing it
1726 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1729 if (fUseCache
&& fAvailableCreditCached
)
1730 return nAvailableCreditCached
;
1732 CAmount nCredit
= 0;
1733 uint256 hashTx
= GetHash();
1734 for (unsigned int i
= 0; i
< tx
->vout
.size(); i
++)
1736 if (!pwallet
->IsSpent(hashTx
, i
))
1738 const CTxOut
&txout
= tx
->vout
[i
];
1739 nCredit
+= pwallet
->GetCredit(txout
, ISMINE_SPENDABLE
);
1740 if (!MoneyRange(nCredit
))
1741 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1745 nAvailableCreditCached
= nCredit
;
1746 fAvailableCreditCached
= true;
1750 CAmount
CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache
) const
1752 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1754 if (fUseCache
&& fImmatureWatchCreditCached
)
1755 return nImmatureWatchCreditCached
;
1756 nImmatureWatchCreditCached
= pwallet
->GetCredit(*this, ISMINE_WATCH_ONLY
);
1757 fImmatureWatchCreditCached
= true;
1758 return nImmatureWatchCreditCached
;
1764 CAmount
CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache
) const
1769 // Must wait until coinbase is safely deep enough in the chain before valuing it
1770 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1773 if (fUseCache
&& fAvailableWatchCreditCached
)
1774 return nAvailableWatchCreditCached
;
1776 CAmount nCredit
= 0;
1777 for (unsigned int i
= 0; i
< tx
->vout
.size(); i
++)
1779 if (!pwallet
->IsSpent(GetHash(), i
))
1781 const CTxOut
&txout
= tx
->vout
[i
];
1782 nCredit
+= pwallet
->GetCredit(txout
, ISMINE_WATCH_ONLY
);
1783 if (!MoneyRange(nCredit
))
1784 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1788 nAvailableWatchCreditCached
= nCredit
;
1789 fAvailableWatchCreditCached
= true;
1793 CAmount
CWalletTx::GetChange() const
1796 return nChangeCached
;
1797 nChangeCached
= pwallet
->GetChange(*this);
1798 fChangeCached
= true;
1799 return nChangeCached
;
1802 bool CWalletTx::InMempool() const
1805 if (mempool
.exists(GetHash())) {
1811 bool CWalletTx::IsTrusted() const
1813 // Quick answer in most cases
1814 if (!CheckFinalTx(*this))
1816 int nDepth
= GetDepthInMainChain();
1821 if (!bSpendZeroConfChange
|| !IsFromMe(ISMINE_ALL
)) // using wtx's cached debit
1824 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1828 // Trusted if all inputs are from us and are in the mempool:
1829 BOOST_FOREACH(const CTxIn
& txin
, tx
->vin
)
1831 // Transactions not sent by us: not trusted
1832 const CWalletTx
* parent
= pwallet
->GetWalletTx(txin
.prevout
.hash
);
1835 const CTxOut
& parentOut
= parent
->tx
->vout
[txin
.prevout
.n
];
1836 if (pwallet
->IsMine(parentOut
) != ISMINE_SPENDABLE
)
1842 bool CWalletTx::IsEquivalentTo(const CWalletTx
& _tx
) const
1844 CMutableTransaction tx1
= *this->tx
;
1845 CMutableTransaction tx2
= *_tx
.tx
;
1846 for (unsigned int i
= 0; i
< tx1
.vin
.size(); i
++) tx1
.vin
[i
].scriptSig
= CScript();
1847 for (unsigned int i
= 0; i
< tx2
.vin
.size(); i
++) tx2
.vin
[i
].scriptSig
= CScript();
1848 return CTransaction(tx1
) == CTransaction(tx2
);
1851 std::vector
<uint256
> CWallet::ResendWalletTransactionsBefore(int64_t nTime
, CConnman
* connman
)
1853 std::vector
<uint256
> result
;
1856 // Sort them in chronological order
1857 multimap
<unsigned int, CWalletTx
*> mapSorted
;
1858 BOOST_FOREACH(PAIRTYPE(const uint256
, CWalletTx
)& item
, mapWallet
)
1860 CWalletTx
& wtx
= item
.second
;
1861 // Don't rebroadcast if newer than nTime:
1862 if (wtx
.nTimeReceived
> nTime
)
1864 mapSorted
.insert(make_pair(wtx
.nTimeReceived
, &wtx
));
1866 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx
*)& item
, mapSorted
)
1868 CWalletTx
& wtx
= *item
.second
;
1869 if (wtx
.RelayWalletTransaction(connman
))
1870 result
.push_back(wtx
.GetHash());
1875 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime
, CConnman
* connman
)
1877 // Do this infrequently and randomly to avoid giving away
1878 // that these are our transactions.
1879 if (GetTime() < nNextResend
|| !fBroadcastTransactions
)
1881 bool fFirst
= (nNextResend
== 0);
1882 nNextResend
= GetTime() + GetRand(30 * 60);
1886 // Only do it if there's been a new block since last time
1887 if (nBestBlockTime
< nLastResend
)
1889 nLastResend
= GetTime();
1891 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1893 std::vector
<uint256
> relayed
= ResendWalletTransactionsBefore(nBestBlockTime
-5*60, connman
);
1894 if (!relayed
.empty())
1895 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__
, relayed
.size());
1898 /** @} */ // end of mapWallet
1903 /** @defgroup Actions
1909 CAmount
CWallet::GetBalance() const
1913 LOCK2(cs_main
, cs_wallet
);
1914 for (map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
1916 const CWalletTx
* pcoin
= &(*it
).second
;
1917 if (pcoin
->IsTrusted())
1918 nTotal
+= pcoin
->GetAvailableCredit();
1925 CAmount
CWallet::GetUnconfirmedBalance() const
1929 LOCK2(cs_main
, cs_wallet
);
1930 for (map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
1932 const CWalletTx
* pcoin
= &(*it
).second
;
1933 if (!pcoin
->IsTrusted() && pcoin
->GetDepthInMainChain() == 0 && pcoin
->InMempool())
1934 nTotal
+= pcoin
->GetAvailableCredit();
1940 CAmount
CWallet::GetImmatureBalance() const
1944 LOCK2(cs_main
, cs_wallet
);
1945 for (map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
1947 const CWalletTx
* pcoin
= &(*it
).second
;
1948 nTotal
+= pcoin
->GetImmatureCredit();
1954 CAmount
CWallet::GetWatchOnlyBalance() const
1958 LOCK2(cs_main
, cs_wallet
);
1959 for (map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
1961 const CWalletTx
* pcoin
= &(*it
).second
;
1962 if (pcoin
->IsTrusted())
1963 nTotal
+= pcoin
->GetAvailableWatchOnlyCredit();
1970 CAmount
CWallet::GetUnconfirmedWatchOnlyBalance() const
1974 LOCK2(cs_main
, cs_wallet
);
1975 for (map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
1977 const CWalletTx
* pcoin
= &(*it
).second
;
1978 if (!pcoin
->IsTrusted() && pcoin
->GetDepthInMainChain() == 0 && pcoin
->InMempool())
1979 nTotal
+= pcoin
->GetAvailableWatchOnlyCredit();
1985 CAmount
CWallet::GetImmatureWatchOnlyBalance() const
1989 LOCK2(cs_main
, cs_wallet
);
1990 for (map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
1992 const CWalletTx
* pcoin
= &(*it
).second
;
1993 nTotal
+= pcoin
->GetImmatureWatchOnlyCredit();
1999 void CWallet::AvailableCoins(vector
<COutput
>& vCoins
, bool fOnlyConfirmed
, const CCoinControl
*coinControl
, bool fIncludeZeroValue
) const
2004 LOCK2(cs_main
, cs_wallet
);
2005 for (map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
2007 const uint256
& wtxid
= it
->first
;
2008 const CWalletTx
* pcoin
= &(*it
).second
;
2010 if (!CheckFinalTx(*pcoin
))
2013 if (fOnlyConfirmed
&& !pcoin
->IsTrusted())
2016 if (pcoin
->IsCoinBase() && pcoin
->GetBlocksToMaturity() > 0)
2019 int nDepth
= pcoin
->GetDepthInMainChain();
2023 // We should not consider coins which aren't at least in our mempool
2024 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2025 if (nDepth
== 0 && !pcoin
->InMempool())
2028 // We should not consider coins from transactions that are replacing
2029 // other transactions.
2031 // Example: There is a transaction A which is replaced by bumpfee
2032 // transaction B. In this case, we want to prevent creation of
2033 // a transaction B' which spends an output of B.
2035 // Reason: If transaction A were initially confirmed, transactions B
2036 // and B' would no longer be valid, so the user would have to create
2037 // a new transaction C to replace B'. However, in the case of a
2038 // one-block reorg, transactions B' and C might BOTH be accepted,
2039 // when the user only wanted one of them. Specifically, there could
2040 // be a 1-block reorg away from the chain where transactions A and C
2041 // were accepted to another chain where B, B', and C were all
2043 if (nDepth
== 0 && fOnlyConfirmed
&& pcoin
->mapValue
.count("replaces_txid")) {
2047 // Similarly, we should not consider coins from transactions that
2048 // have been replaced. In the example above, we would want to prevent
2049 // creation of a transaction A' spending an output of A, because if
2050 // transaction B were initially confirmed, conflicting with A and
2051 // A', we wouldn't want to the user to create a transaction D
2052 // intending to replace A', but potentially resulting in a scenario
2053 // where A, A', and D could all be accepted (instead of just B and
2054 // D, or just A and A' like the user would want).
2055 if (nDepth
== 0 && fOnlyConfirmed
&& pcoin
->mapValue
.count("replaced_by_txid")) {
2059 for (unsigned int i
= 0; i
< pcoin
->tx
->vout
.size(); i
++) {
2060 isminetype mine
= IsMine(pcoin
->tx
->vout
[i
]);
2061 if (!(IsSpent(wtxid
, i
)) && mine
!= ISMINE_NO
&&
2062 !IsLockedCoin((*it
).first
, i
) && (pcoin
->tx
->vout
[i
].nValue
> 0 || fIncludeZeroValue
) &&
2063 (!coinControl
|| !coinControl
->HasSelected() || coinControl
->fAllowOtherInputs
|| coinControl
->IsSelected(COutPoint((*it
).first
, i
))))
2064 vCoins
.push_back(COutput(pcoin
, i
, nDepth
,
2065 ((mine
& ISMINE_SPENDABLE
) != ISMINE_NO
) ||
2066 (coinControl
&& coinControl
->fAllowWatchOnly
&& (mine
& ISMINE_WATCH_SOLVABLE
) != ISMINE_NO
),
2067 (mine
& (ISMINE_SPENDABLE
| ISMINE_WATCH_SOLVABLE
)) != ISMINE_NO
));
2073 static void ApproximateBestSubset(vector
<pair
<CAmount
, pair
<const CWalletTx
*,unsigned int> > >vValue
, const CAmount
& nTotalLower
, const CAmount
& nTargetValue
,
2074 vector
<char>& vfBest
, CAmount
& nBest
, int iterations
= 1000)
2076 vector
<char> vfIncluded
;
2078 vfBest
.assign(vValue
.size(), true);
2079 nBest
= nTotalLower
;
2081 FastRandomContext insecure_rand
;
2083 for (int nRep
= 0; nRep
< iterations
&& nBest
!= nTargetValue
; nRep
++)
2085 vfIncluded
.assign(vValue
.size(), false);
2087 bool fReachedTarget
= false;
2088 for (int nPass
= 0; nPass
< 2 && !fReachedTarget
; nPass
++)
2090 for (unsigned int i
= 0; i
< vValue
.size(); i
++)
2092 //The solver here uses a randomized algorithm,
2093 //the randomness serves no real security purpose but is just
2094 //needed to prevent degenerate behavior and it is important
2095 //that the rng is fast. We do not use a constant random sequence,
2096 //because there may be some privacy improvement by making
2097 //the selection random.
2098 if (nPass
== 0 ? insecure_rand
.rand32()&1 : !vfIncluded
[i
])
2100 nTotal
+= vValue
[i
].first
;
2101 vfIncluded
[i
] = true;
2102 if (nTotal
>= nTargetValue
)
2104 fReachedTarget
= true;
2108 vfBest
= vfIncluded
;
2110 nTotal
-= vValue
[i
].first
;
2111 vfIncluded
[i
] = false;
2119 bool CWallet::SelectCoinsMinConf(const CAmount
& nTargetValue
, const int nConfMine
, const int nConfTheirs
, const uint64_t nMaxAncestors
, vector
<COutput
> vCoins
,
2120 set
<pair
<const CWalletTx
*,unsigned int> >& setCoinsRet
, CAmount
& nValueRet
) const
2122 setCoinsRet
.clear();
2125 // List of values less than target
2126 pair
<CAmount
, pair
<const CWalletTx
*,unsigned int> > coinLowestLarger
;
2127 coinLowestLarger
.first
= std::numeric_limits
<CAmount
>::max();
2128 coinLowestLarger
.second
.first
= NULL
;
2129 vector
<pair
<CAmount
, pair
<const CWalletTx
*,unsigned int> > > vValue
;
2130 CAmount nTotalLower
= 0;
2132 random_shuffle(vCoins
.begin(), vCoins
.end(), GetRandInt
);
2134 BOOST_FOREACH(const COutput
&output
, vCoins
)
2136 if (!output
.fSpendable
)
2139 const CWalletTx
*pcoin
= output
.tx
;
2141 if (output
.nDepth
< (pcoin
->IsFromMe(ISMINE_ALL
) ? nConfMine
: nConfTheirs
))
2144 if (!mempool
.TransactionWithinChainLimit(pcoin
->GetHash(), nMaxAncestors
))
2148 CAmount n
= pcoin
->tx
->vout
[i
].nValue
;
2150 pair
<CAmount
,pair
<const CWalletTx
*,unsigned int> > coin
= make_pair(n
,make_pair(pcoin
, i
));
2152 if (n
== nTargetValue
)
2154 setCoinsRet
.insert(coin
.second
);
2155 nValueRet
+= coin
.first
;
2158 else if (n
< nTargetValue
+ MIN_CHANGE
)
2160 vValue
.push_back(coin
);
2163 else if (n
< coinLowestLarger
.first
)
2165 coinLowestLarger
= coin
;
2169 if (nTotalLower
== nTargetValue
)
2171 for (unsigned int i
= 0; i
< vValue
.size(); ++i
)
2173 setCoinsRet
.insert(vValue
[i
].second
);
2174 nValueRet
+= vValue
[i
].first
;
2179 if (nTotalLower
< nTargetValue
)
2181 if (coinLowestLarger
.second
.first
== NULL
)
2183 setCoinsRet
.insert(coinLowestLarger
.second
);
2184 nValueRet
+= coinLowestLarger
.first
;
2188 // Solve subset sum by stochastic approximation
2189 std::sort(vValue
.begin(), vValue
.end(), CompareValueOnly());
2190 std::reverse(vValue
.begin(), vValue
.end());
2191 vector
<char> vfBest
;
2194 ApproximateBestSubset(vValue
, nTotalLower
, nTargetValue
, vfBest
, nBest
);
2195 if (nBest
!= nTargetValue
&& nTotalLower
>= nTargetValue
+ MIN_CHANGE
)
2196 ApproximateBestSubset(vValue
, nTotalLower
, nTargetValue
+ MIN_CHANGE
, vfBest
, nBest
);
2198 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2199 // or the next bigger coin is closer), return the bigger coin
2200 if (coinLowestLarger
.second
.first
&&
2201 ((nBest
!= nTargetValue
&& nBest
< nTargetValue
+ MIN_CHANGE
) || coinLowestLarger
.first
<= nBest
))
2203 setCoinsRet
.insert(coinLowestLarger
.second
);
2204 nValueRet
+= coinLowestLarger
.first
;
2207 for (unsigned int i
= 0; i
< vValue
.size(); i
++)
2210 setCoinsRet
.insert(vValue
[i
].second
);
2211 nValueRet
+= vValue
[i
].first
;
2214 LogPrint("selectcoins", "SelectCoins() best subset: ");
2215 for (unsigned int i
= 0; i
< vValue
.size(); i
++)
2217 LogPrint("selectcoins", "%s ", FormatMoney(vValue
[i
].first
));
2218 LogPrint("selectcoins", "total %s\n", FormatMoney(nBest
));
2224 bool CWallet::SelectCoins(const vector
<COutput
>& vAvailableCoins
, const CAmount
& nTargetValue
, set
<pair
<const CWalletTx
*,unsigned int> >& setCoinsRet
, CAmount
& nValueRet
, const CCoinControl
* coinControl
) const
2226 vector
<COutput
> vCoins(vAvailableCoins
);
2228 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2229 if (coinControl
&& coinControl
->HasSelected() && !coinControl
->fAllowOtherInputs
)
2231 BOOST_FOREACH(const COutput
& out
, vCoins
)
2233 if (!out
.fSpendable
)
2235 nValueRet
+= out
.tx
->tx
->vout
[out
.i
].nValue
;
2236 setCoinsRet
.insert(make_pair(out
.tx
, out
.i
));
2238 return (nValueRet
>= nTargetValue
);
2241 // calculate value from preset inputs and store them
2242 set
<pair
<const CWalletTx
*, uint32_t> > setPresetCoins
;
2243 CAmount nValueFromPresetInputs
= 0;
2245 std::vector
<COutPoint
> vPresetInputs
;
2247 coinControl
->ListSelected(vPresetInputs
);
2248 BOOST_FOREACH(const COutPoint
& outpoint
, vPresetInputs
)
2250 map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.find(outpoint
.hash
);
2251 if (it
!= mapWallet
.end())
2253 const CWalletTx
* pcoin
= &it
->second
;
2254 // Clearly invalid input, fail
2255 if (pcoin
->tx
->vout
.size() <= outpoint
.n
)
2257 nValueFromPresetInputs
+= pcoin
->tx
->vout
[outpoint
.n
].nValue
;
2258 setPresetCoins
.insert(make_pair(pcoin
, outpoint
.n
));
2260 return false; // TODO: Allow non-wallet inputs
2263 // remove preset inputs from vCoins
2264 for (vector
<COutput
>::iterator it
= vCoins
.begin(); it
!= vCoins
.end() && coinControl
&& coinControl
->HasSelected();)
2266 if (setPresetCoins
.count(make_pair(it
->tx
, it
->i
)))
2267 it
= vCoins
.erase(it
);
2272 size_t nMaxChainLength
= std::min(GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT
), GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT
));
2273 bool fRejectLongChains
= GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS
);
2275 bool res
= nTargetValue
<= nValueFromPresetInputs
||
2276 SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 1, 6, 0, vCoins
, setCoinsRet
, nValueRet
) ||
2277 SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 1, 1, 0, vCoins
, setCoinsRet
, nValueRet
) ||
2278 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, 2, vCoins
, setCoinsRet
, nValueRet
)) ||
2279 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, std::min((size_t)4, nMaxChainLength
/3), vCoins
, setCoinsRet
, nValueRet
)) ||
2280 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, nMaxChainLength
/2, vCoins
, setCoinsRet
, nValueRet
)) ||
2281 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, nMaxChainLength
, vCoins
, setCoinsRet
, nValueRet
)) ||
2282 (bSpendZeroConfChange
&& !fRejectLongChains
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, std::numeric_limits
<uint64_t>::max(), vCoins
, setCoinsRet
, nValueRet
));
2284 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2285 setCoinsRet
.insert(setPresetCoins
.begin(), setPresetCoins
.end());
2287 // add preset inputs to the total value selected
2288 nValueRet
+= nValueFromPresetInputs
;
2293 bool CWallet::FundTransaction(CMutableTransaction
& tx
, CAmount
& nFeeRet
, bool overrideEstimatedFeeRate
, const CFeeRate
& specificFeeRate
, int& nChangePosInOut
, std::string
& strFailReason
, bool includeWatching
, bool lockUnspents
, const std::set
<int>& setSubtractFeeFromOutputs
, bool keepReserveKey
, const CTxDestination
& destChange
)
2295 vector
<CRecipient
> vecSend
;
2297 // Turn the txout set into a CRecipient vector
2298 for (size_t idx
= 0; idx
< tx
.vout
.size(); idx
++)
2300 const CTxOut
& txOut
= tx
.vout
[idx
];
2301 CRecipient recipient
= {txOut
.scriptPubKey
, txOut
.nValue
, setSubtractFeeFromOutputs
.count(idx
) == 1};
2302 vecSend
.push_back(recipient
);
2305 CCoinControl coinControl
;
2306 coinControl
.destChange
= destChange
;
2307 coinControl
.fAllowOtherInputs
= true;
2308 coinControl
.fAllowWatchOnly
= includeWatching
;
2309 coinControl
.fOverrideFeeRate
= overrideEstimatedFeeRate
;
2310 coinControl
.nFeeRate
= specificFeeRate
;
2312 BOOST_FOREACH(const CTxIn
& txin
, tx
.vin
)
2313 coinControl
.Select(txin
.prevout
);
2315 CReserveKey
reservekey(this);
2317 if (!CreateTransaction(vecSend
, wtx
, reservekey
, nFeeRet
, nChangePosInOut
, strFailReason
, &coinControl
, false))
2320 if (nChangePosInOut
!= -1)
2321 tx
.vout
.insert(tx
.vout
.begin() + nChangePosInOut
, wtx
.tx
->vout
[nChangePosInOut
]);
2323 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2324 for (unsigned int idx
= 0; idx
< tx
.vout
.size(); idx
++)
2325 tx
.vout
[idx
].nValue
= wtx
.tx
->vout
[idx
].nValue
;
2327 // Add new txins (keeping original txin scriptSig/order)
2328 BOOST_FOREACH(const CTxIn
& txin
, wtx
.tx
->vin
)
2330 if (!coinControl
.IsSelected(txin
.prevout
))
2332 tx
.vin
.push_back(txin
);
2336 LOCK2(cs_main
, cs_wallet
);
2337 LockCoin(txin
.prevout
);
2342 // optionally keep the change output key
2344 reservekey
.KeepKey();
2349 bool CWallet::CreateTransaction(const vector
<CRecipient
>& vecSend
, CWalletTx
& wtxNew
, CReserveKey
& reservekey
, CAmount
& nFeeRet
,
2350 int& nChangePosInOut
, std::string
& strFailReason
, const CCoinControl
* coinControl
, bool sign
)
2353 int nChangePosRequest
= nChangePosInOut
;
2354 unsigned int nSubtractFeeFromAmount
= 0;
2355 for (const auto& recipient
: vecSend
)
2357 if (nValue
< 0 || recipient
.nAmount
< 0)
2359 strFailReason
= _("Transaction amounts must not be negative");
2362 nValue
+= recipient
.nAmount
;
2364 if (recipient
.fSubtractFeeFromAmount
)
2365 nSubtractFeeFromAmount
++;
2367 if (vecSend
.empty())
2369 strFailReason
= _("Transaction must have at least one recipient");
2373 wtxNew
.fTimeReceivedIsTxTime
= true;
2374 wtxNew
.BindWallet(this);
2375 CMutableTransaction txNew
;
2377 // Discourage fee sniping.
2379 // For a large miner the value of the transactions in the best block and
2380 // the mempool can exceed the cost of deliberately attempting to mine two
2381 // blocks to orphan the current best block. By setting nLockTime such that
2382 // only the next block can include the transaction, we discourage this
2383 // practice as the height restricted and limited blocksize gives miners
2384 // considering fee sniping fewer options for pulling off this attack.
2386 // A simple way to think about this is from the wallet's point of view we
2387 // always want the blockchain to move forward. By setting nLockTime this
2388 // way we're basically making the statement that we only want this
2389 // transaction to appear in the next block; we don't want to potentially
2390 // encourage reorgs by allowing transactions to appear at lower heights
2391 // than the next block in forks of the best chain.
2393 // Of course, the subsidy is high enough, and transaction volume low
2394 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2395 // now we ensure code won't be written that makes assumptions about
2396 // nLockTime that preclude a fix later.
2397 txNew
.nLockTime
= chainActive
.Height();
2399 // Secondly occasionally randomly pick a nLockTime even further back, so
2400 // that transactions that are delayed after signing for whatever reason,
2401 // e.g. high-latency mix networks and some CoinJoin implementations, have
2403 if (GetRandInt(10) == 0)
2404 txNew
.nLockTime
= std::max(0, (int)txNew
.nLockTime
- GetRandInt(100));
2406 assert(txNew
.nLockTime
<= (unsigned int)chainActive
.Height());
2407 assert(txNew
.nLockTime
< LOCKTIME_THRESHOLD
);
2410 set
<pair
<const CWalletTx
*,unsigned int> > setCoins
;
2411 LOCK2(cs_main
, cs_wallet
);
2413 std::vector
<COutput
> vAvailableCoins
;
2414 AvailableCoins(vAvailableCoins
, true, coinControl
);
2417 // Start with no fee and loop until there is enough fee
2420 nChangePosInOut
= nChangePosRequest
;
2423 wtxNew
.fFromMe
= true;
2426 CAmount nValueToSelect
= nValue
;
2427 if (nSubtractFeeFromAmount
== 0)
2428 nValueToSelect
+= nFeeRet
;
2429 double dPriority
= 0;
2430 // vouts to the payees
2431 for (const auto& recipient
: vecSend
)
2433 CTxOut
txout(recipient
.nAmount
, recipient
.scriptPubKey
);
2435 if (recipient
.fSubtractFeeFromAmount
)
2437 txout
.nValue
-= nFeeRet
/ nSubtractFeeFromAmount
; // Subtract fee equally from each selected recipient
2439 if (fFirst
) // first receiver pays the remainder not divisible by output count
2442 txout
.nValue
-= nFeeRet
% nSubtractFeeFromAmount
;
2446 if (txout
.IsDust(dustRelayFee
))
2448 if (recipient
.fSubtractFeeFromAmount
&& nFeeRet
> 0)
2450 if (txout
.nValue
< 0)
2451 strFailReason
= _("The transaction amount is too small to pay the fee");
2453 strFailReason
= _("The transaction amount is too small to send after the fee has been deducted");
2456 strFailReason
= _("Transaction amount too small");
2459 txNew
.vout
.push_back(txout
);
2462 // Choose coins to use
2463 CAmount nValueIn
= 0;
2465 if (!SelectCoins(vAvailableCoins
, nValueToSelect
, setCoins
, nValueIn
, coinControl
))
2467 strFailReason
= _("Insufficient funds");
2470 for (const auto& pcoin
: setCoins
)
2472 CAmount nCredit
= pcoin
.first
->tx
->vout
[pcoin
.second
].nValue
;
2473 //The coin age after the next block (depth+1) is used instead of the current,
2474 //reflecting an assumption the user would accept a bit more delay for
2475 //a chance at a free transaction.
2476 //But mempool inputs might still be in the mempool, so their age stays 0
2477 int age
= pcoin
.first
->GetDepthInMainChain();
2481 dPriority
+= (double)nCredit
* age
;
2484 const CAmount nChange
= nValueIn
- nValueToSelect
;
2487 // Fill a vout to ourself
2488 // TODO: pass in scriptChange instead of reservekey so
2489 // change transaction isn't always pay-to-bitcoin-address
2490 CScript scriptChange
;
2492 // coin control: send change to custom address
2493 if (coinControl
&& !boost::get
<CNoDestination
>(&coinControl
->destChange
))
2494 scriptChange
= GetScriptForDestination(coinControl
->destChange
);
2496 // no coin control: send change to newly generated address
2499 // Note: We use a new key here to keep it from being obvious which side is the change.
2500 // The drawback is that by not reusing a previous key, the change may be lost if a
2501 // backup is restored, if the backup doesn't have the new private key for the change.
2502 // If we reused the old key, it would be possible to add code to look for and
2503 // rediscover unknown transactions that were written with keys of ours to recover
2504 // post-backup change.
2506 // Reserve a new key pair from key pool
2509 ret
= reservekey
.GetReservedKey(vchPubKey
);
2512 strFailReason
= _("Keypool ran out, please call keypoolrefill first");
2516 scriptChange
= GetScriptForDestination(vchPubKey
.GetID());
2519 CTxOut
newTxOut(nChange
, scriptChange
);
2521 // We do not move dust-change to fees, because the sender would end up paying more than requested.
2522 // This would be against the purpose of the all-inclusive feature.
2523 // So instead we raise the change and deduct from the recipient.
2524 if (nSubtractFeeFromAmount
> 0 && newTxOut
.IsDust(dustRelayFee
))
2526 CAmount nDust
= newTxOut
.GetDustThreshold(dustRelayFee
) - newTxOut
.nValue
;
2527 newTxOut
.nValue
+= nDust
; // raise change until no more dust
2528 for (unsigned int i
= 0; i
< vecSend
.size(); i
++) // subtract from first recipient
2530 if (vecSend
[i
].fSubtractFeeFromAmount
)
2532 txNew
.vout
[i
].nValue
-= nDust
;
2533 if (txNew
.vout
[i
].IsDust(dustRelayFee
))
2535 strFailReason
= _("The transaction amount is too small to send after the fee has been deducted");
2543 // Never create dust outputs; if we would, just
2544 // add the dust to the fee.
2545 if (newTxOut
.IsDust(dustRelayFee
))
2547 nChangePosInOut
= -1;
2549 reservekey
.ReturnKey();
2553 if (nChangePosInOut
== -1)
2555 // Insert change txn at random position:
2556 nChangePosInOut
= GetRandInt(txNew
.vout
.size()+1);
2558 else if ((unsigned int)nChangePosInOut
> txNew
.vout
.size())
2560 strFailReason
= _("Change index out of range");
2564 vector
<CTxOut
>::iterator position
= txNew
.vout
.begin()+nChangePosInOut
;
2565 txNew
.vout
.insert(position
, newTxOut
);
2569 reservekey
.ReturnKey();
2573 // Note how the sequence number is set to non-maxint so that
2574 // the nLockTime set above actually works.
2576 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2577 // we use the highest possible value in that range (maxint-2)
2578 // to avoid conflicting with other possible uses of nSequence,
2579 // and in the spirit of "smallest possible change from prior
2581 for (const auto& coin
: setCoins
)
2582 txNew
.vin
.push_back(CTxIn(coin
.first
->GetHash(),coin
.second
,CScript(),
2583 std::numeric_limits
<unsigned int>::max() - (fWalletRbf
? 2 : 1)));
2585 // Fill in dummy signatures for fee calculation.
2586 if (!DummySignTx(txNew
, setCoins
)) {
2587 strFailReason
= _("Signing transaction failed");
2591 unsigned int nBytes
= GetVirtualTransactionSize(txNew
);
2593 CTransaction
txNewConst(txNew
);
2594 dPriority
= txNewConst
.ComputePriority(dPriority
, nBytes
);
2596 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2597 for (auto& vin
: txNew
.vin
) {
2598 vin
.scriptSig
= CScript();
2599 vin
.scriptWitness
.SetNull();
2602 // Allow to override the default confirmation target over the CoinControl instance
2603 int currentConfirmationTarget
= nTxConfirmTarget
;
2604 if (coinControl
&& coinControl
->nConfirmTarget
> 0)
2605 currentConfirmationTarget
= coinControl
->nConfirmTarget
;
2607 // Can we complete this as a free transaction?
2608 if (fSendFreeTransactions
&& nBytes
<= MAX_FREE_TRANSACTION_CREATE_SIZE
)
2610 // Not enough fee: enough priority?
2611 double dPriorityNeeded
= mempool
.estimateSmartPriority(currentConfirmationTarget
);
2612 // Require at least hard-coded AllowFree.
2613 if (dPriority
>= dPriorityNeeded
&& AllowFree(dPriority
))
2617 CAmount nFeeNeeded
= GetMinimumFee(nBytes
, currentConfirmationTarget
, mempool
);
2618 if (coinControl
&& nFeeNeeded
> 0 && coinControl
->nMinimumTotalFee
> nFeeNeeded
) {
2619 nFeeNeeded
= coinControl
->nMinimumTotalFee
;
2621 if (coinControl
&& coinControl
->fOverrideFeeRate
)
2622 nFeeNeeded
= coinControl
->nFeeRate
.GetFee(nBytes
);
2624 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2625 // because we must be at the maximum allowed fee.
2626 if (nFeeNeeded
< ::minRelayTxFee
.GetFee(nBytes
))
2628 strFailReason
= _("Transaction too large for fee policy");
2632 if (nFeeRet
>= nFeeNeeded
) {
2633 // Reduce fee to only the needed amount if we have change
2634 // output to increase. This prevents potential overpayment
2635 // in fees if the coins selected to meet nFeeNeeded result
2636 // in a transaction that requires less fee than the prior
2638 // TODO: The case where nSubtractFeeFromAmount > 0 remains
2639 // to be addressed because it requires returning the fee to
2640 // the payees and not the change output.
2641 // TODO: The case where there is no change output remains
2642 // to be addressed so we avoid creating too small an output.
2643 if (nFeeRet
> nFeeNeeded
&& nChangePosInOut
!= -1 && nSubtractFeeFromAmount
== 0) {
2644 CAmount extraFeePaid
= nFeeRet
- nFeeNeeded
;
2645 vector
<CTxOut
>::iterator change_position
= txNew
.vout
.begin()+nChangePosInOut
;
2646 change_position
->nValue
+= extraFeePaid
;
2647 nFeeRet
-= extraFeePaid
;
2649 break; // Done, enough fee included.
2652 // Try to reduce change to include necessary fee
2653 if (nChangePosInOut
!= -1 && nSubtractFeeFromAmount
== 0) {
2654 CAmount additionalFeeNeeded
= nFeeNeeded
- nFeeRet
;
2655 vector
<CTxOut
>::iterator change_position
= txNew
.vout
.begin()+nChangePosInOut
;
2656 // Only reduce change if remaining amount is still a large enough output.
2657 if (change_position
->nValue
>= MIN_FINAL_CHANGE
+ additionalFeeNeeded
) {
2658 change_position
->nValue
-= additionalFeeNeeded
;
2659 nFeeRet
+= additionalFeeNeeded
;
2660 break; // Done, able to increase fee from change
2664 // Include more fee and try again.
2665 nFeeRet
= nFeeNeeded
;
2672 CTransaction
txNewConst(txNew
);
2674 for (const auto& coin
: setCoins
)
2676 const CScript
& scriptPubKey
= coin
.first
->tx
->vout
[coin
.second
].scriptPubKey
;
2677 SignatureData sigdata
;
2679 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst
, nIn
, coin
.first
->tx
->vout
[coin
.second
].nValue
, SIGHASH_ALL
), scriptPubKey
, sigdata
))
2681 strFailReason
= _("Signing transaction failed");
2684 UpdateTransaction(txNew
, nIn
, sigdata
);
2691 // Embed the constructed transaction data in wtxNew.
2692 wtxNew
.SetTx(MakeTransactionRef(std::move(txNew
)));
2695 if (GetTransactionWeight(wtxNew
) >= MAX_STANDARD_TX_WEIGHT
)
2697 strFailReason
= _("Transaction too large");
2702 if (GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS
)) {
2703 // Lastly, ensure this tx will pass the mempool's chain limits
2705 CTxMemPoolEntry
entry(wtxNew
.tx
, 0, 0, 0, 0, 0, false, 0, lp
);
2706 CTxMemPool::setEntries setAncestors
;
2707 size_t nLimitAncestors
= GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT
);
2708 size_t nLimitAncestorSize
= GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT
)*1000;
2709 size_t nLimitDescendants
= GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT
);
2710 size_t nLimitDescendantSize
= GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT
)*1000;
2711 std::string errString
;
2712 if (!mempool
.CalculateMemPoolAncestors(entry
, setAncestors
, nLimitAncestors
, nLimitAncestorSize
, nLimitDescendants
, nLimitDescendantSize
, errString
)) {
2713 strFailReason
= _("Transaction has too long of a mempool chain");
2721 * Call after CreateTransaction unless you want to abort
2723 bool CWallet::CommitTransaction(CWalletTx
& wtxNew
, CReserveKey
& reservekey
, CConnman
* connman
, CValidationState
& state
)
2726 LOCK2(cs_main
, cs_wallet
);
2727 LogPrintf("CommitTransaction:\n%s", wtxNew
.tx
->ToString());
2729 // Take key pair from key pool so it won't be used again
2730 reservekey
.KeepKey();
2732 // Add tx to wallet, because if it has change it's also ours,
2733 // otherwise just for transaction history.
2734 AddToWallet(wtxNew
);
2736 // Notify that old coins are spent
2737 BOOST_FOREACH(const CTxIn
& txin
, wtxNew
.tx
->vin
)
2739 CWalletTx
&coin
= mapWallet
[txin
.prevout
.hash
];
2740 coin
.BindWallet(this);
2741 NotifyTransactionChanged(this, coin
.GetHash(), CT_UPDATED
);
2745 // Track how many getdata requests our transaction gets
2746 mapRequestCount
[wtxNew
.GetHash()] = 0;
2748 if (fBroadcastTransactions
)
2751 if (!wtxNew
.AcceptToMemoryPool(maxTxFee
, state
)) {
2752 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state
.GetRejectReason());
2753 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2755 wtxNew
.RelayWalletTransaction(connman
);
2762 void CWallet::ListAccountCreditDebit(const std::string
& strAccount
, std::list
<CAccountingEntry
>& entries
) {
2763 CWalletDB
walletdb(strWalletFile
);
2764 return walletdb
.ListAccountCreditDebit(strAccount
, entries
);
2767 bool CWallet::AddAccountingEntry(const CAccountingEntry
& acentry
)
2769 CWalletDB
walletdb(strWalletFile
);
2771 return AddAccountingEntry(acentry
, &walletdb
);
2774 bool CWallet::AddAccountingEntry(const CAccountingEntry
& acentry
, CWalletDB
*pwalletdb
)
2776 if (!pwalletdb
->WriteAccountingEntry_Backend(acentry
))
2779 laccentries
.push_back(acentry
);
2780 CAccountingEntry
& entry
= laccentries
.back();
2781 wtxOrdered
.insert(make_pair(entry
.nOrderPos
, TxPair((CWalletTx
*)0, &entry
)));
2786 CAmount
CWallet::GetRequiredFee(unsigned int nTxBytes
)
2788 return std::max(minTxFee
.GetFee(nTxBytes
), ::minRelayTxFee
.GetFee(nTxBytes
));
2791 CAmount
CWallet::GetMinimumFee(unsigned int nTxBytes
, unsigned int nConfirmTarget
, const CTxMemPool
& pool
)
2793 // payTxFee is the user-set global for desired feerate
2794 return GetMinimumFee(nTxBytes
, nConfirmTarget
, pool
, payTxFee
.GetFee(nTxBytes
));
2797 CAmount
CWallet::GetMinimumFee(unsigned int nTxBytes
, unsigned int nConfirmTarget
, const CTxMemPool
& pool
, CAmount targetFee
)
2799 CAmount nFeeNeeded
= targetFee
;
2800 // User didn't set: use -txconfirmtarget to estimate...
2801 if (nFeeNeeded
== 0) {
2802 int estimateFoundTarget
= nConfirmTarget
;
2803 nFeeNeeded
= pool
.estimateSmartFee(nConfirmTarget
, &estimateFoundTarget
).GetFee(nTxBytes
);
2804 // ... unless we don't have enough mempool data for estimatefee, then use fallbackFee
2805 if (nFeeNeeded
== 0)
2806 nFeeNeeded
= fallbackFee
.GetFee(nTxBytes
);
2808 // prevent user from paying a fee below minRelayTxFee or minTxFee
2809 nFeeNeeded
= std::max(nFeeNeeded
, GetRequiredFee(nTxBytes
));
2810 // But always obey the maximum
2811 if (nFeeNeeded
> maxTxFee
)
2812 nFeeNeeded
= maxTxFee
;
2819 DBErrors
CWallet::LoadWallet(bool& fFirstRunRet
)
2823 fFirstRunRet
= false;
2824 DBErrors nLoadWalletRet
= CWalletDB(strWalletFile
,"cr+").LoadWallet(this);
2825 if (nLoadWalletRet
== DB_NEED_REWRITE
)
2827 if (CDB::Rewrite(strWalletFile
, "\x04pool"))
2831 // Note: can't top-up keypool here, because wallet is locked.
2832 // User will be prompted to unlock wallet the next operation
2833 // that requires a new key.
2837 if (nLoadWalletRet
!= DB_LOAD_OK
)
2838 return nLoadWalletRet
;
2839 fFirstRunRet
= !vchDefaultKey
.IsValid();
2841 uiInterface
.LoadWallet(this);
2846 DBErrors
CWallet::ZapSelectTx(vector
<uint256
>& vHashIn
, vector
<uint256
>& vHashOut
)
2850 DBErrors nZapSelectTxRet
= CWalletDB(strWalletFile
,"cr+").ZapSelectTx(this, vHashIn
, vHashOut
);
2851 if (nZapSelectTxRet
== DB_NEED_REWRITE
)
2853 if (CDB::Rewrite(strWalletFile
, "\x04pool"))
2857 // Note: can't top-up keypool here, because wallet is locked.
2858 // User will be prompted to unlock wallet the next operation
2859 // that requires a new key.
2863 if (nZapSelectTxRet
!= DB_LOAD_OK
)
2864 return nZapSelectTxRet
;
2872 DBErrors
CWallet::ZapWalletTx(std::vector
<CWalletTx
>& vWtx
)
2876 DBErrors nZapWalletTxRet
= CWalletDB(strWalletFile
,"cr+").ZapWalletTx(this, vWtx
);
2877 if (nZapWalletTxRet
== DB_NEED_REWRITE
)
2879 if (CDB::Rewrite(strWalletFile
, "\x04pool"))
2883 // Note: can't top-up keypool here, because wallet is locked.
2884 // User will be prompted to unlock wallet the next operation
2885 // that requires a new key.
2889 if (nZapWalletTxRet
!= DB_LOAD_OK
)
2890 return nZapWalletTxRet
;
2896 bool CWallet::SetAddressBook(const CTxDestination
& address
, const string
& strName
, const string
& strPurpose
)
2898 bool fUpdated
= false;
2900 LOCK(cs_wallet
); // mapAddressBook
2901 std::map
<CTxDestination
, CAddressBookData
>::iterator mi
= mapAddressBook
.find(address
);
2902 fUpdated
= mi
!= mapAddressBook
.end();
2903 mapAddressBook
[address
].name
= strName
;
2904 if (!strPurpose
.empty()) /* update purpose only if requested */
2905 mapAddressBook
[address
].purpose
= strPurpose
;
2907 NotifyAddressBookChanged(this, address
, strName
, ::IsMine(*this, address
) != ISMINE_NO
,
2908 strPurpose
, (fUpdated
? CT_UPDATED
: CT_NEW
) );
2911 if (!strPurpose
.empty() && !CWalletDB(strWalletFile
).WritePurpose(CBitcoinAddress(address
).ToString(), strPurpose
))
2913 return CWalletDB(strWalletFile
).WriteName(CBitcoinAddress(address
).ToString(), strName
);
2916 bool CWallet::DelAddressBook(const CTxDestination
& address
)
2919 LOCK(cs_wallet
); // mapAddressBook
2923 // Delete destdata tuples associated with address
2924 std::string strAddress
= CBitcoinAddress(address
).ToString();
2925 BOOST_FOREACH(const PAIRTYPE(string
, string
) &item
, mapAddressBook
[address
].destdata
)
2927 CWalletDB(strWalletFile
).EraseDestData(strAddress
, item
.first
);
2930 mapAddressBook
.erase(address
);
2933 NotifyAddressBookChanged(this, address
, "", ::IsMine(*this, address
) != ISMINE_NO
, "", CT_DELETED
);
2937 CWalletDB(strWalletFile
).ErasePurpose(CBitcoinAddress(address
).ToString());
2938 return CWalletDB(strWalletFile
).EraseName(CBitcoinAddress(address
).ToString());
2941 bool CWallet::SetDefaultKey(const CPubKey
&vchPubKey
)
2945 if (!CWalletDB(strWalletFile
).WriteDefaultKey(vchPubKey
))
2948 vchDefaultKey
= vchPubKey
;
2953 * Mark old keypool keys as used,
2954 * and generate all new keys
2956 bool CWallet::NewKeyPool()
2960 CWalletDB
walletdb(strWalletFile
);
2961 BOOST_FOREACH(int64_t nIndex
, setKeyPool
)
2962 walletdb
.ErasePool(nIndex
);
2968 int64_t nKeys
= max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE
), (int64_t)0);
2969 for (int i
= 0; i
< nKeys
; i
++)
2971 int64_t nIndex
= i
+1;
2972 walletdb
.WritePool(nIndex
, CKeyPool(GenerateNewKey()));
2973 setKeyPool
.insert(nIndex
);
2975 LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys
);
2980 bool CWallet::TopUpKeyPool(unsigned int kpSize
)
2988 CWalletDB
walletdb(strWalletFile
);
2991 unsigned int nTargetSize
;
2993 nTargetSize
= kpSize
;
2995 nTargetSize
= max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE
), (int64_t) 0);
2997 while (setKeyPool
.size() < (nTargetSize
+ 1))
3000 if (!setKeyPool
.empty())
3001 nEnd
= *(--setKeyPool
.end()) + 1;
3002 if (!walletdb
.WritePool(nEnd
, CKeyPool(GenerateNewKey())))
3003 throw runtime_error(std::string(__func__
) + ": writing generated key failed");
3004 setKeyPool
.insert(nEnd
);
3005 LogPrintf("keypool added key %d, size=%u\n", nEnd
, setKeyPool
.size());
3011 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex
, CKeyPool
& keypool
)
3014 keypool
.vchPubKey
= CPubKey();
3021 // Get the oldest key
3022 if(setKeyPool
.empty())
3025 CWalletDB
walletdb(strWalletFile
);
3027 nIndex
= *(setKeyPool
.begin());
3028 setKeyPool
.erase(setKeyPool
.begin());
3029 if (!walletdb
.ReadPool(nIndex
, keypool
))
3030 throw runtime_error(std::string(__func__
) + ": read failed");
3031 if (!HaveKey(keypool
.vchPubKey
.GetID()))
3032 throw runtime_error(std::string(__func__
) + ": unknown key in key pool");
3033 assert(keypool
.vchPubKey
.IsValid());
3034 LogPrintf("keypool reserve %d\n", nIndex
);
3038 void CWallet::KeepKey(int64_t nIndex
)
3040 // Remove from key pool
3043 CWalletDB
walletdb(strWalletFile
);
3044 walletdb
.ErasePool(nIndex
);
3046 LogPrintf("keypool keep %d\n", nIndex
);
3049 void CWallet::ReturnKey(int64_t nIndex
)
3051 // Return to key pool
3054 setKeyPool
.insert(nIndex
);
3056 LogPrintf("keypool return %d\n", nIndex
);
3059 bool CWallet::GetKeyFromPool(CPubKey
& result
)
3065 ReserveKeyFromKeyPool(nIndex
, keypool
);
3068 if (IsLocked()) return false;
3069 result
= GenerateNewKey();
3073 result
= keypool
.vchPubKey
;
3078 int64_t CWallet::GetOldestKeyPoolTime()
3082 // if the keypool is empty, return <NOW>
3083 if (setKeyPool
.empty())
3086 // load oldest key from keypool, get time and return
3088 CWalletDB
walletdb(strWalletFile
);
3089 int64_t nIndex
= *(setKeyPool
.begin());
3090 if (!walletdb
.ReadPool(nIndex
, keypool
))
3091 throw runtime_error(std::string(__func__
) + ": read oldest key in keypool failed");
3092 assert(keypool
.vchPubKey
.IsValid());
3093 return keypool
.nTime
;
3096 std::map
<CTxDestination
, CAmount
> CWallet::GetAddressBalances()
3098 map
<CTxDestination
, CAmount
> balances
;
3102 BOOST_FOREACH(PAIRTYPE(uint256
, CWalletTx
) walletEntry
, mapWallet
)
3104 CWalletTx
*pcoin
= &walletEntry
.second
;
3106 if (!pcoin
->IsTrusted())
3109 if (pcoin
->IsCoinBase() && pcoin
->GetBlocksToMaturity() > 0)
3112 int nDepth
= pcoin
->GetDepthInMainChain();
3113 if (nDepth
< (pcoin
->IsFromMe(ISMINE_ALL
) ? 0 : 1))
3116 for (unsigned int i
= 0; i
< pcoin
->tx
->vout
.size(); i
++)
3118 CTxDestination addr
;
3119 if (!IsMine(pcoin
->tx
->vout
[i
]))
3121 if(!ExtractDestination(pcoin
->tx
->vout
[i
].scriptPubKey
, addr
))
3124 CAmount n
= IsSpent(walletEntry
.first
, i
) ? 0 : pcoin
->tx
->vout
[i
].nValue
;
3126 if (!balances
.count(addr
))
3128 balances
[addr
] += n
;
3136 set
< set
<CTxDestination
> > CWallet::GetAddressGroupings()
3138 AssertLockHeld(cs_wallet
); // mapWallet
3139 set
< set
<CTxDestination
> > groupings
;
3140 set
<CTxDestination
> grouping
;
3142 BOOST_FOREACH(PAIRTYPE(uint256
, CWalletTx
) walletEntry
, mapWallet
)
3144 CWalletTx
*pcoin
= &walletEntry
.second
;
3146 if (pcoin
->tx
->vin
.size() > 0)
3148 bool any_mine
= false;
3149 // group all input addresses with each other
3150 BOOST_FOREACH(CTxIn txin
, pcoin
->tx
->vin
)
3152 CTxDestination address
;
3153 if(!IsMine(txin
)) /* If this input isn't mine, ignore it */
3155 if(!ExtractDestination(mapWallet
[txin
.prevout
.hash
].tx
->vout
[txin
.prevout
.n
].scriptPubKey
, address
))
3157 grouping
.insert(address
);
3161 // group change with input addresses
3164 BOOST_FOREACH(CTxOut txout
, pcoin
->tx
->vout
)
3165 if (IsChange(txout
))
3167 CTxDestination txoutAddr
;
3168 if(!ExtractDestination(txout
.scriptPubKey
, txoutAddr
))
3170 grouping
.insert(txoutAddr
);
3173 if (grouping
.size() > 0)
3175 groupings
.insert(grouping
);
3180 // group lone addrs by themselves
3181 for (unsigned int i
= 0; i
< pcoin
->tx
->vout
.size(); i
++)
3182 if (IsMine(pcoin
->tx
->vout
[i
]))
3184 CTxDestination address
;
3185 if(!ExtractDestination(pcoin
->tx
->vout
[i
].scriptPubKey
, address
))
3187 grouping
.insert(address
);
3188 groupings
.insert(grouping
);
3193 set
< set
<CTxDestination
>* > uniqueGroupings
; // a set of pointers to groups of addresses
3194 map
< CTxDestination
, set
<CTxDestination
>* > setmap
; // map addresses to the unique group containing it
3195 BOOST_FOREACH(set
<CTxDestination
> _grouping
, groupings
)
3197 // make a set of all the groups hit by this new group
3198 set
< set
<CTxDestination
>* > hits
;
3199 map
< CTxDestination
, set
<CTxDestination
>* >::iterator it
;
3200 BOOST_FOREACH(CTxDestination address
, _grouping
)
3201 if ((it
= setmap
.find(address
)) != setmap
.end())
3202 hits
.insert((*it
).second
);
3204 // merge all hit groups into a new single group and delete old groups
3205 set
<CTxDestination
>* merged
= new set
<CTxDestination
>(_grouping
);
3206 BOOST_FOREACH(set
<CTxDestination
>* hit
, hits
)
3208 merged
->insert(hit
->begin(), hit
->end());
3209 uniqueGroupings
.erase(hit
);
3212 uniqueGroupings
.insert(merged
);
3215 BOOST_FOREACH(CTxDestination element
, *merged
)
3216 setmap
[element
] = merged
;
3219 set
< set
<CTxDestination
> > ret
;
3220 BOOST_FOREACH(set
<CTxDestination
>* uniqueGrouping
, uniqueGroupings
)
3222 ret
.insert(*uniqueGrouping
);
3223 delete uniqueGrouping
;
3229 CAmount
CWallet::GetAccountBalance(const std::string
& strAccount
, int nMinDepth
, const isminefilter
& filter
)
3231 CWalletDB
walletdb(strWalletFile
);
3232 return GetAccountBalance(walletdb
, strAccount
, nMinDepth
, filter
);
3235 CAmount
CWallet::GetAccountBalance(CWalletDB
& walletdb
, const std::string
& strAccount
, int nMinDepth
, const isminefilter
& filter
)
3237 CAmount nBalance
= 0;
3239 // Tally wallet transactions
3240 for (map
<uint256
, CWalletTx
>::iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
3242 const CWalletTx
& wtx
= (*it
).second
;
3243 if (!CheckFinalTx(wtx
) || wtx
.GetBlocksToMaturity() > 0 || wtx
.GetDepthInMainChain() < 0)
3246 CAmount nReceived
, nSent
, nFee
;
3247 wtx
.GetAccountAmounts(strAccount
, nReceived
, nSent
, nFee
, filter
);
3249 if (nReceived
!= 0 && wtx
.GetDepthInMainChain() >= nMinDepth
)
3250 nBalance
+= nReceived
;
3251 nBalance
-= nSent
+ nFee
;
3254 // Tally internal accounting entries
3255 nBalance
+= walletdb
.GetAccountCreditDebit(strAccount
);
3260 std::set
<CTxDestination
> CWallet::GetAccountAddresses(const std::string
& strAccount
) const
3263 set
<CTxDestination
> result
;
3264 BOOST_FOREACH(const PAIRTYPE(CTxDestination
, CAddressBookData
)& item
, mapAddressBook
)
3266 const CTxDestination
& address
= item
.first
;
3267 const string
& strName
= item
.second
.name
;
3268 if (strName
== strAccount
)
3269 result
.insert(address
);
3274 bool CReserveKey::GetReservedKey(CPubKey
& pubkey
)
3279 pwallet
->ReserveKeyFromKeyPool(nIndex
, keypool
);
3281 vchPubKey
= keypool
.vchPubKey
;
3286 assert(vchPubKey
.IsValid());
3291 void CReserveKey::KeepKey()
3294 pwallet
->KeepKey(nIndex
);
3296 vchPubKey
= CPubKey();
3299 void CReserveKey::ReturnKey()
3302 pwallet
->ReturnKey(nIndex
);
3304 vchPubKey
= CPubKey();
3307 void CWallet::GetAllReserveKeys(set
<CKeyID
>& setAddress
) const
3311 CWalletDB
walletdb(strWalletFile
);
3313 LOCK2(cs_main
, cs_wallet
);
3314 BOOST_FOREACH(const int64_t& id
, setKeyPool
)
3317 if (!walletdb
.ReadPool(id
, keypool
))
3318 throw runtime_error(std::string(__func__
) + ": read failed");
3319 assert(keypool
.vchPubKey
.IsValid());
3320 CKeyID keyID
= keypool
.vchPubKey
.GetID();
3321 if (!HaveKey(keyID
))
3322 throw runtime_error(std::string(__func__
) + ": unknown key in key pool");
3323 setAddress
.insert(keyID
);
3327 void CWallet::UpdatedTransaction(const uint256
&hashTx
)
3331 // Only notify UI if this transaction is in this wallet
3332 map
<uint256
, CWalletTx
>::const_iterator mi
= mapWallet
.find(hashTx
);
3333 if (mi
!= mapWallet
.end())
3334 NotifyTransactionChanged(this, hashTx
, CT_UPDATED
);
3338 void CWallet::GetScriptForMining(boost::shared_ptr
<CReserveScript
> &script
)
3340 boost::shared_ptr
<CReserveKey
> rKey(new CReserveKey(this));
3342 if (!rKey
->GetReservedKey(pubkey
))
3346 script
->reserveScript
= CScript() << ToByteVector(pubkey
) << OP_CHECKSIG
;
3349 void CWallet::LockCoin(const COutPoint
& output
)
3351 AssertLockHeld(cs_wallet
); // setLockedCoins
3352 setLockedCoins
.insert(output
);
3355 void CWallet::UnlockCoin(const COutPoint
& output
)
3357 AssertLockHeld(cs_wallet
); // setLockedCoins
3358 setLockedCoins
.erase(output
);
3361 void CWallet::UnlockAllCoins()
3363 AssertLockHeld(cs_wallet
); // setLockedCoins
3364 setLockedCoins
.clear();
3367 bool CWallet::IsLockedCoin(uint256 hash
, unsigned int n
) const
3369 AssertLockHeld(cs_wallet
); // setLockedCoins
3370 COutPoint
outpt(hash
, n
);
3372 return (setLockedCoins
.count(outpt
) > 0);
3375 void CWallet::ListLockedCoins(std::vector
<COutPoint
>& vOutpts
)
3377 AssertLockHeld(cs_wallet
); // setLockedCoins
3378 for (std::set
<COutPoint
>::iterator it
= setLockedCoins
.begin();
3379 it
!= setLockedCoins
.end(); it
++) {
3380 COutPoint outpt
= (*it
);
3381 vOutpts
.push_back(outpt
);
3385 /** @} */ // end of Actions
3387 class CAffectedKeysVisitor
: public boost::static_visitor
<void> {
3389 const CKeyStore
&keystore
;
3390 std::vector
<CKeyID
> &vKeys
;
3393 CAffectedKeysVisitor(const CKeyStore
&keystoreIn
, std::vector
<CKeyID
> &vKeysIn
) : keystore(keystoreIn
), vKeys(vKeysIn
) {}
3395 void Process(const CScript
&script
) {
3397 std::vector
<CTxDestination
> vDest
;
3399 if (ExtractDestinations(script
, type
, vDest
, nRequired
)) {
3400 BOOST_FOREACH(const CTxDestination
&dest
, vDest
)
3401 boost::apply_visitor(*this, dest
);
3405 void operator()(const CKeyID
&keyId
) {
3406 if (keystore
.HaveKey(keyId
))
3407 vKeys
.push_back(keyId
);
3410 void operator()(const CScriptID
&scriptId
) {
3412 if (keystore
.GetCScript(scriptId
, script
))
3416 void operator()(const CNoDestination
&none
) {}
3419 void CWallet::GetKeyBirthTimes(std::map
<CKeyID
, int64_t> &mapKeyBirth
) const {
3420 AssertLockHeld(cs_wallet
); // mapKeyMetadata
3421 mapKeyBirth
.clear();
3423 // get birth times for keys with metadata
3424 for (std::map
<CKeyID
, CKeyMetadata
>::const_iterator it
= mapKeyMetadata
.begin(); it
!= mapKeyMetadata
.end(); it
++)
3425 if (it
->second
.nCreateTime
)
3426 mapKeyBirth
[it
->first
] = it
->second
.nCreateTime
;
3428 // map in which we'll infer heights of other keys
3429 CBlockIndex
*pindexMax
= chainActive
[std::max(0, chainActive
.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3430 std::map
<CKeyID
, CBlockIndex
*> mapKeyFirstBlock
;
3431 std::set
<CKeyID
> setKeys
;
3433 BOOST_FOREACH(const CKeyID
&keyid
, setKeys
) {
3434 if (mapKeyBirth
.count(keyid
) == 0)
3435 mapKeyFirstBlock
[keyid
] = pindexMax
;
3439 // if there are no such keys, we're done
3440 if (mapKeyFirstBlock
.empty())
3443 // find first block that affects those keys, if there are any left
3444 std::vector
<CKeyID
> vAffected
;
3445 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); it
++) {
3446 // iterate over all wallet transactions...
3447 const CWalletTx
&wtx
= (*it
).second
;
3448 BlockMap::const_iterator blit
= mapBlockIndex
.find(wtx
.hashBlock
);
3449 if (blit
!= mapBlockIndex
.end() && chainActive
.Contains(blit
->second
)) {
3450 // ... which are already in a block
3451 int nHeight
= blit
->second
->nHeight
;
3452 BOOST_FOREACH(const CTxOut
&txout
, wtx
.tx
->vout
) {
3453 // iterate over all their outputs
3454 CAffectedKeysVisitor(*this, vAffected
).Process(txout
.scriptPubKey
);
3455 BOOST_FOREACH(const CKeyID
&keyid
, vAffected
) {
3456 // ... and all their affected keys
3457 std::map
<CKeyID
, CBlockIndex
*>::iterator rit
= mapKeyFirstBlock
.find(keyid
);
3458 if (rit
!= mapKeyFirstBlock
.end() && nHeight
< rit
->second
->nHeight
)
3459 rit
->second
= blit
->second
;
3466 // Extract block timestamps for those keys
3467 for (std::map
<CKeyID
, CBlockIndex
*>::const_iterator it
= mapKeyFirstBlock
.begin(); it
!= mapKeyFirstBlock
.end(); it
++)
3468 mapKeyBirth
[it
->first
] = it
->second
->GetBlockTime() - 7200; // block times can be 2h off
3471 bool CWallet::AddDestData(const CTxDestination
&dest
, const std::string
&key
, const std::string
&value
)
3473 if (boost::get
<CNoDestination
>(&dest
))
3476 mapAddressBook
[dest
].destdata
.insert(std::make_pair(key
, value
));
3479 return CWalletDB(strWalletFile
).WriteDestData(CBitcoinAddress(dest
).ToString(), key
, value
);
3482 bool CWallet::EraseDestData(const CTxDestination
&dest
, const std::string
&key
)
3484 if (!mapAddressBook
[dest
].destdata
.erase(key
))
3488 return CWalletDB(strWalletFile
).EraseDestData(CBitcoinAddress(dest
).ToString(), key
);
3491 bool CWallet::LoadDestData(const CTxDestination
&dest
, const std::string
&key
, const std::string
&value
)
3493 mapAddressBook
[dest
].destdata
.insert(std::make_pair(key
, value
));
3497 bool CWallet::GetDestData(const CTxDestination
&dest
, const std::string
&key
, std::string
*value
) const
3499 std::map
<CTxDestination
, CAddressBookData
>::const_iterator i
= mapAddressBook
.find(dest
);
3500 if(i
!= mapAddressBook
.end())
3502 CAddressBookData::StringMap::const_iterator j
= i
->second
.destdata
.find(key
);
3503 if(j
!= i
->second
.destdata
.end())
3513 std::string
CWallet::GetWalletHelpString(bool showDebug
)
3515 std::string strUsage
= HelpMessageGroup(_("Wallet options:"));
3516 strUsage
+= HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
3517 strUsage
+= HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE
));
3518 strUsage
+= HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
3519 CURRENCY_UNIT
, FormatMoney(DEFAULT_FALLBACK_FEE
)));
3520 strUsage
+= HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
3521 CURRENCY_UNIT
, FormatMoney(DEFAULT_TRANSACTION_MINFEE
)));
3522 strUsage
+= HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
3523 CURRENCY_UNIT
, FormatMoney(payTxFee
.GetFeePerK())));
3524 strUsage
+= HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
3525 strUsage
+= HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup"));
3527 strUsage
+= HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), DEFAULT_SEND_FREE_TRANSACTIONS
));
3528 strUsage
+= HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE
));
3529 strUsage
+= HelpMessageOpt("-txconfirmtarget=<n>", strprintf(_("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)"), DEFAULT_TX_CONFIRM_TARGET
));
3530 strUsage
+= HelpMessageOpt("-usehd", _("Use hierarchical deterministic key generation (HD) after BIP32. Only has effect during wallet creation/first start") + " " + strprintf(_("(default: %u)"), DEFAULT_USE_HD_WALLET
));
3531 strUsage
+= HelpMessageOpt("-walletrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (default: %u)"), DEFAULT_WALLET_RBF
));
3532 strUsage
+= HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
3533 strUsage
+= HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT
));
3534 strUsage
+= HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST
));
3535 strUsage
+= HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
3536 strUsage
+= HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
3537 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
3541 strUsage
+= HelpMessageGroup(_("Wallet debugging/testing options:"));
3543 strUsage
+= HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE
));
3544 strUsage
+= HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET
));
3545 strUsage
+= HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB
));
3546 strUsage
+= HelpMessageOpt("-walletrejectlongchains", strprintf(_("Wallet will not create transactions that violate mempool chain limits (default: %u)"), DEFAULT_WALLET_REJECT_LONG_CHAINS
));
3552 CWallet
* CWallet::CreateWalletFromFile(const std::string walletFile
)
3554 // needed to restore wallet transaction meta data after -zapwallettxes
3555 std::vector
<CWalletTx
> vWtx
;
3557 if (GetBoolArg("-zapwallettxes", false)) {
3558 uiInterface
.InitMessage(_("Zapping all transactions from wallet..."));
3560 CWallet
*tempWallet
= new CWallet(walletFile
);
3561 DBErrors nZapWalletRet
= tempWallet
->ZapWalletTx(vWtx
);
3562 if (nZapWalletRet
!= DB_LOAD_OK
) {
3563 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile
));
3571 uiInterface
.InitMessage(_("Loading wallet..."));
3573 int64_t nStart
= GetTimeMillis();
3574 bool fFirstRun
= true;
3575 CWallet
*walletInstance
= new CWallet(walletFile
);
3576 DBErrors nLoadWalletRet
= walletInstance
->LoadWallet(fFirstRun
);
3577 if (nLoadWalletRet
!= DB_LOAD_OK
)
3579 if (nLoadWalletRet
== DB_CORRUPT
) {
3580 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile
));
3583 else if (nLoadWalletRet
== DB_NONCRITICAL_ERROR
)
3585 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3586 " or address book entries might be missing or incorrect."),
3589 else if (nLoadWalletRet
== DB_TOO_NEW
) {
3590 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile
, _(PACKAGE_NAME
)));
3593 else if (nLoadWalletRet
== DB_NEED_REWRITE
)
3595 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME
)));
3599 InitError(strprintf(_("Error loading %s"), walletFile
));
3604 if (GetBoolArg("-upgradewallet", fFirstRun
))
3606 int nMaxVersion
= GetArg("-upgradewallet", 0);
3607 if (nMaxVersion
== 0) // the -upgradewallet without argument case
3609 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST
);
3610 nMaxVersion
= CLIENT_VERSION
;
3611 walletInstance
->SetMinVersion(FEATURE_LATEST
); // permanently upgrade the wallet immediately
3614 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion
);
3615 if (nMaxVersion
< walletInstance
->GetVersion())
3617 InitError(_("Cannot downgrade wallet"));
3620 walletInstance
->SetMaxVersion(nMaxVersion
);
3625 // Create new keyUser and set as default key
3626 if (GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET
) && !walletInstance
->IsHDEnabled()) {
3627 // generate a new master key
3628 CPubKey masterPubKey
= walletInstance
->GenerateNewHDMasterKey();
3629 if (!walletInstance
->SetHDMasterKey(masterPubKey
))
3630 throw std::runtime_error(std::string(__func__
) + ": Storing master key failed");
3632 CPubKey newDefaultKey
;
3633 if (walletInstance
->GetKeyFromPool(newDefaultKey
)) {
3634 walletInstance
->SetDefaultKey(newDefaultKey
);
3635 if (!walletInstance
->SetAddressBook(walletInstance
->vchDefaultKey
.GetID(), "", "receive")) {
3636 InitError(_("Cannot write default address") += "\n");
3641 walletInstance
->SetBestChain(chainActive
.GetLocator());
3643 else if (IsArgSet("-usehd")) {
3644 bool useHD
= GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET
);
3645 if (walletInstance
->IsHDEnabled() && !useHD
) {
3646 InitError(strprintf(_("Error loading %s: You can't disable HD on a already existing HD wallet"), walletFile
));
3649 if (!walletInstance
->IsHDEnabled() && useHD
) {
3650 InitError(strprintf(_("Error loading %s: You can't enable HD on a already existing non-HD wallet"), walletFile
));
3655 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart
);
3657 RegisterValidationInterface(walletInstance
);
3659 CBlockIndex
*pindexRescan
= chainActive
.Tip();
3660 if (GetBoolArg("-rescan", false))
3661 pindexRescan
= chainActive
.Genesis();
3664 CWalletDB
walletdb(walletFile
);
3665 CBlockLocator locator
;
3666 if (walletdb
.ReadBestBlock(locator
))
3667 pindexRescan
= FindForkInGlobalIndex(chainActive
, locator
);
3669 pindexRescan
= chainActive
.Genesis();
3671 if (chainActive
.Tip() && chainActive
.Tip() != pindexRescan
)
3673 //We can't rescan beyond non-pruned blocks, stop and throw an error
3674 //this might happen if a user uses a old wallet within a pruned node
3675 // or if he ran -disablewallet for a longer time, then decided to re-enable
3678 CBlockIndex
*block
= chainActive
.Tip();
3679 while (block
&& block
->pprev
&& (block
->pprev
->nStatus
& BLOCK_HAVE_DATA
) && block
->pprev
->nTx
> 0 && pindexRescan
!= block
)
3680 block
= block
->pprev
;
3682 if (pindexRescan
!= block
) {
3683 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3688 uiInterface
.InitMessage(_("Rescanning..."));
3689 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive
.Height() - pindexRescan
->nHeight
, pindexRescan
->nHeight
);
3690 nStart
= GetTimeMillis();
3691 walletInstance
->ScanForWalletTransactions(pindexRescan
, true);
3692 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart
);
3693 walletInstance
->SetBestChain(chainActive
.GetLocator());
3696 // Restore wallet transaction metadata after -zapwallettxes=1
3697 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
3699 CWalletDB
walletdb(walletFile
);
3701 BOOST_FOREACH(const CWalletTx
& wtxOld
, vWtx
)
3703 uint256 hash
= wtxOld
.GetHash();
3704 std::map
<uint256
, CWalletTx
>::iterator mi
= walletInstance
->mapWallet
.find(hash
);
3705 if (mi
!= walletInstance
->mapWallet
.end())
3707 const CWalletTx
* copyFrom
= &wtxOld
;
3708 CWalletTx
* copyTo
= &mi
->second
;
3709 copyTo
->mapValue
= copyFrom
->mapValue
;
3710 copyTo
->vOrderForm
= copyFrom
->vOrderForm
;
3711 copyTo
->nTimeReceived
= copyFrom
->nTimeReceived
;
3712 copyTo
->nTimeSmart
= copyFrom
->nTimeSmart
;
3713 copyTo
->fFromMe
= copyFrom
->fFromMe
;
3714 copyTo
->strFromAccount
= copyFrom
->strFromAccount
;
3715 copyTo
->nOrderPos
= copyFrom
->nOrderPos
;
3716 walletdb
.WriteTx(*copyTo
);
3721 walletInstance
->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST
));
3724 LOCK(walletInstance
->cs_wallet
);
3725 LogPrintf("setKeyPool.size() = %u\n", walletInstance
->GetKeyPoolSize());
3726 LogPrintf("mapWallet.size() = %u\n", walletInstance
->mapWallet
.size());
3727 LogPrintf("mapAddressBook.size() = %u\n", walletInstance
->mapAddressBook
.size());
3730 return walletInstance
;
3733 bool CWallet::InitLoadWallet()
3735 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET
)) {
3737 LogPrintf("Wallet disabled!\n");
3741 std::string walletFile
= GetArg("-wallet", DEFAULT_WALLET_DAT
);
3743 CWallet
* const pwallet
= CreateWalletFromFile(walletFile
);
3747 pwalletMain
= pwallet
;
3752 std::atomic
<bool> CWallet::fFlushThreadRunning(false);
3754 void CWallet::postInitProcess(boost::thread_group
& threadGroup
)
3756 // Add wallet transactions that aren't already in a block to mempool
3757 // Do this here as mempool requires genesis block to be loaded
3758 ReacceptWalletTransactions();
3760 // Run a thread to flush wallet periodically
3761 if (!CWallet::fFlushThreadRunning
.exchange(true)) {
3762 threadGroup
.create_thread(ThreadFlushWalletDB
);
3766 bool CWallet::ParameterInteraction()
3768 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET
))
3771 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY
) && SoftSetBoolArg("-walletbroadcast", false)) {
3772 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__
);
3775 if (GetBoolArg("-salvagewallet", false) && SoftSetBoolArg("-rescan", true)) {
3776 // Rewrite just private keys: rescan to find transactions
3777 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__
);
3780 // -zapwallettx implies a rescan
3781 if (GetBoolArg("-zapwallettxes", false) && SoftSetBoolArg("-rescan", true)) {
3782 LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__
);
3785 if (GetBoolArg("-sysperms", false))
3786 return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
3787 if (GetArg("-prune", 0) && GetBoolArg("-rescan", false))
3788 return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
3790 if (::minRelayTxFee
.GetFeePerK() > HIGH_TX_FEE_PER_KB
)
3791 InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
3792 _("The wallet will avoid paying less than the minimum relay fee."));
3794 if (IsArgSet("-mintxfee"))
3797 if (!ParseMoney(GetArg("-mintxfee", ""), n
) || 0 == n
)
3798 return InitError(AmountErrMsg("mintxfee", GetArg("-mintxfee", "")));
3799 if (n
> HIGH_TX_FEE_PER_KB
)
3800 InitWarning(AmountHighWarn("-mintxfee") + " " +
3801 _("This is the minimum transaction fee you pay on every transaction."));
3802 CWallet::minTxFee
= CFeeRate(n
);
3804 if (IsArgSet("-fallbackfee"))
3806 CAmount nFeePerK
= 0;
3807 if (!ParseMoney(GetArg("-fallbackfee", ""), nFeePerK
))
3808 return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), GetArg("-fallbackfee", "")));
3809 if (nFeePerK
> HIGH_TX_FEE_PER_KB
)
3810 InitWarning(AmountHighWarn("-fallbackfee") + " " +
3811 _("This is the transaction fee you may pay when fee estimates are not available."));
3812 CWallet::fallbackFee
= CFeeRate(nFeePerK
);
3814 if (IsArgSet("-paytxfee"))
3816 CAmount nFeePerK
= 0;
3817 if (!ParseMoney(GetArg("-paytxfee", ""), nFeePerK
))
3818 return InitError(AmountErrMsg("paytxfee", GetArg("-paytxfee", "")));
3819 if (nFeePerK
> HIGH_TX_FEE_PER_KB
)
3820 InitWarning(AmountHighWarn("-paytxfee") + " " +
3821 _("This is the transaction fee you will pay if you send a transaction."));
3823 payTxFee
= CFeeRate(nFeePerK
, 1000);
3824 if (payTxFee
< ::minRelayTxFee
)
3826 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
3827 GetArg("-paytxfee", ""), ::minRelayTxFee
.ToString()));
3830 if (IsArgSet("-maxtxfee"))
3832 CAmount nMaxFee
= 0;
3833 if (!ParseMoney(GetArg("-maxtxfee", ""), nMaxFee
))
3834 return InitError(AmountErrMsg("maxtxfee", GetArg("-maxtxfee", "")));
3835 if (nMaxFee
> HIGH_MAX_TX_FEE
)
3836 InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
3838 if (CFeeRate(maxTxFee
, 1000) < ::minRelayTxFee
)
3840 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
3841 GetArg("-maxtxfee", ""), ::minRelayTxFee
.ToString()));
3844 nTxConfirmTarget
= GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET
);
3845 bSpendZeroConfChange
= GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE
);
3846 fSendFreeTransactions
= GetBoolArg("-sendfreetransactions", DEFAULT_SEND_FREE_TRANSACTIONS
);
3847 fWalletRbf
= GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF
);
3849 if (fSendFreeTransactions
&& GetArg("-limitfreerelay", DEFAULT_LIMITFREERELAY
) <= 0)
3850 return InitError("Creation of free transactions with their relay disabled is not supported.");
3855 bool CWallet::BackupWallet(const std::string
& strDest
)
3863 if (!bitdb
.mapFileUseCount
.count(strWalletFile
) || bitdb
.mapFileUseCount
[strWalletFile
] == 0)
3865 // Flush log data to the dat file
3866 bitdb
.CloseDb(strWalletFile
);
3867 bitdb
.CheckpointLSN(strWalletFile
);
3868 bitdb
.mapFileUseCount
.erase(strWalletFile
);
3871 boost::filesystem::path pathSrc
= GetDataDir() / strWalletFile
;
3872 boost::filesystem::path
pathDest(strDest
);
3873 if (boost::filesystem::is_directory(pathDest
))
3874 pathDest
/= strWalletFile
;
3877 #if BOOST_VERSION >= 104000
3878 boost::filesystem::copy_file(pathSrc
, pathDest
, boost::filesystem::copy_option::overwrite_if_exists
);
3880 boost::filesystem::copy_file(pathSrc
, pathDest
);
3882 LogPrintf("copied %s to %s\n", strWalletFile
, pathDest
.string());
3884 } catch (const boost::filesystem::filesystem_error
& e
) {
3885 LogPrintf("error copying %s to %s - %s\n", strWalletFile
, pathDest
.string(), e
.what());
3895 CKeyPool::CKeyPool()
3900 CKeyPool::CKeyPool(const CPubKey
& vchPubKeyIn
)
3903 vchPubKey
= vchPubKeyIn
;
3906 CWalletKey::CWalletKey(int64_t nExpires
)
3908 nTimeCreated
= (nExpires
? GetTime() : 0);
3909 nTimeExpires
= nExpires
;
3912 void CMerkleTx::SetMerkleBranch(const CBlockIndex
* pindex
, int posInBlock
)
3914 // Update the tx's hashBlock
3915 hashBlock
= pindex
->GetBlockHash();
3917 // set the position of the transaction in the block
3918 nIndex
= posInBlock
;
3921 int CMerkleTx::GetDepthInMainChain(const CBlockIndex
* &pindexRet
) const
3926 AssertLockHeld(cs_main
);
3928 // Find the block it claims to be in
3929 BlockMap::iterator mi
= mapBlockIndex
.find(hashBlock
);
3930 if (mi
== mapBlockIndex
.end())
3932 CBlockIndex
* pindex
= (*mi
).second
;
3933 if (!pindex
|| !chainActive
.Contains(pindex
))
3937 return ((nIndex
== -1) ? (-1) : 1) * (chainActive
.Height() - pindex
->nHeight
+ 1);
3940 int CMerkleTx::GetBlocksToMaturity() const
3944 return max(0, (COINBASE_MATURITY
+1) - GetDepthInMainChain());
3948 bool CMerkleTx::AcceptToMemoryPool(const CAmount
& nAbsurdFee
, CValidationState
& state
)
3950 return ::AcceptToMemoryPool(mempool
, state
, tx
, true, NULL
, NULL
, false, nAbsurdFee
);