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 UpdateTimeFirstKey(nCreationTime
);
118 if (!AddKeyPubKey(secret
, pubkey
))
119 throw std::runtime_error(std::string(__func__
) + ": AddKey failed");
123 void CWallet::DeriveNewChildKey(CKeyMetadata
& metadata
, CKey
& secret
)
125 // for now we use a fixed keypath scheme of m/0'/0'/k
126 CKey key
; //master key seed (256bit)
127 CExtKey masterKey
; //hd master key
128 CExtKey accountKey
; //key at m/0'
129 CExtKey externalChainChildKey
; //key at m/0'/0'
130 CExtKey childKey
; //key at m/0'/0'/<n>'
132 // try to get the master key
133 if (!GetKey(hdChain
.masterKeyID
, key
))
134 throw std::runtime_error(std::string(__func__
) + ": Master key not found");
136 masterKey
.SetMaster(key
.begin(), key
.size());
139 // use hardened derivation (child keys >= 0x80000000 are hardened after bip32)
140 masterKey
.Derive(accountKey
, BIP32_HARDENED_KEY_LIMIT
);
143 accountKey
.Derive(externalChainChildKey
, BIP32_HARDENED_KEY_LIMIT
);
145 // derive child key at next index, skip keys already known to the wallet
147 // always derive hardened keys
148 // childIndex | BIP32_HARDENED_KEY_LIMIT = derive childIndex in hardened child-index-range
149 // example: 1 | BIP32_HARDENED_KEY_LIMIT == 0x80000001 == 2147483649
150 externalChainChildKey
.Derive(childKey
, hdChain
.nExternalChainCounter
| BIP32_HARDENED_KEY_LIMIT
);
151 metadata
.hdKeypath
= "m/0'/0'/" + std::to_string(hdChain
.nExternalChainCounter
) + "'";
152 metadata
.hdMasterKeyID
= hdChain
.masterKeyID
;
153 // increment childkey index
154 hdChain
.nExternalChainCounter
++;
155 } while (HaveKey(childKey
.key
.GetPubKey().GetID()));
156 secret
= childKey
.key
;
158 // update the chain model in the database
159 if (!CWalletDB(strWalletFile
).WriteHDChain(hdChain
))
160 throw std::runtime_error(std::string(__func__
) + ": Writing HD chain model failed");
163 bool CWallet::AddKeyPubKey(const CKey
& secret
, const CPubKey
&pubkey
)
165 AssertLockHeld(cs_wallet
); // mapKeyMetadata
166 if (!CCryptoKeyStore::AddKeyPubKey(secret
, pubkey
))
169 // check if we need to remove from watch-only
171 script
= GetScriptForDestination(pubkey
.GetID());
172 if (HaveWatchOnly(script
))
173 RemoveWatchOnly(script
);
174 script
= GetScriptForRawPubKey(pubkey
);
175 if (HaveWatchOnly(script
))
176 RemoveWatchOnly(script
);
181 return CWalletDB(strWalletFile
).WriteKey(pubkey
,
183 mapKeyMetadata
[pubkey
.GetID()]);
188 bool CWallet::AddCryptedKey(const CPubKey
&vchPubKey
,
189 const vector
<unsigned char> &vchCryptedSecret
)
191 if (!CCryptoKeyStore::AddCryptedKey(vchPubKey
, vchCryptedSecret
))
197 if (pwalletdbEncryption
)
198 return pwalletdbEncryption
->WriteCryptedKey(vchPubKey
,
200 mapKeyMetadata
[vchPubKey
.GetID()]);
202 return CWalletDB(strWalletFile
).WriteCryptedKey(vchPubKey
,
204 mapKeyMetadata
[vchPubKey
.GetID()]);
209 bool CWallet::LoadKeyMetadata(const CTxDestination
& keyID
, const CKeyMetadata
&meta
)
211 AssertLockHeld(cs_wallet
); // mapKeyMetadata
212 UpdateTimeFirstKey(meta
.nCreateTime
);
213 mapKeyMetadata
[keyID
] = meta
;
217 bool CWallet::LoadCryptedKey(const CPubKey
&vchPubKey
, const std::vector
<unsigned char> &vchCryptedSecret
)
219 return CCryptoKeyStore::AddCryptedKey(vchPubKey
, vchCryptedSecret
);
222 void CWallet::UpdateTimeFirstKey(int64_t nCreateTime
)
224 AssertLockHeld(cs_wallet
);
225 if (nCreateTime
<= 1) {
226 // Cannot determine birthday information, so set the wallet birthday to
227 // the beginning of time.
229 } else if (!nTimeFirstKey
|| nCreateTime
< nTimeFirstKey
) {
230 nTimeFirstKey
= nCreateTime
;
234 bool CWallet::AddCScript(const CScript
& redeemScript
)
236 if (!CCryptoKeyStore::AddCScript(redeemScript
))
240 return CWalletDB(strWalletFile
).WriteCScript(Hash160(redeemScript
), redeemScript
);
243 bool CWallet::LoadCScript(const CScript
& redeemScript
)
245 /* A sanity check was added in pull #3843 to avoid adding redeemScripts
246 * that never can be redeemed. However, old wallets may still contain
247 * these. Do not add them to the wallet and warn. */
248 if (redeemScript
.size() > MAX_SCRIPT_ELEMENT_SIZE
)
250 std::string strAddr
= CBitcoinAddress(CScriptID(redeemScript
)).ToString();
251 LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n",
252 __func__
, redeemScript
.size(), MAX_SCRIPT_ELEMENT_SIZE
, strAddr
);
256 return CCryptoKeyStore::AddCScript(redeemScript
);
259 bool CWallet::AddWatchOnly(const CScript
& dest
)
261 if (!CCryptoKeyStore::AddWatchOnly(dest
))
263 const CKeyMetadata
& meta
= mapKeyMetadata
[CScriptID(dest
)];
264 UpdateTimeFirstKey(meta
.nCreateTime
);
265 NotifyWatchonlyChanged(true);
268 return CWalletDB(strWalletFile
).WriteWatchOnly(dest
, meta
);
271 bool CWallet::AddWatchOnly(const CScript
& dest
, int64_t nCreateTime
)
273 mapKeyMetadata
[CScriptID(dest
)].nCreateTime
= nCreateTime
;
274 return AddWatchOnly(dest
);
277 bool CWallet::RemoveWatchOnly(const CScript
&dest
)
279 AssertLockHeld(cs_wallet
);
280 if (!CCryptoKeyStore::RemoveWatchOnly(dest
))
282 if (!HaveWatchOnly())
283 NotifyWatchonlyChanged(false);
285 if (!CWalletDB(strWalletFile
).EraseWatchOnly(dest
))
291 bool CWallet::LoadWatchOnly(const CScript
&dest
)
293 return CCryptoKeyStore::AddWatchOnly(dest
);
296 bool CWallet::Unlock(const SecureString
& strWalletPassphrase
)
299 CKeyingMaterial _vMasterKey
;
303 BOOST_FOREACH(const MasterKeyMap::value_type
& pMasterKey
, mapMasterKeys
)
305 if(!crypter
.SetKeyFromPassphrase(strWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
))
307 if (!crypter
.Decrypt(pMasterKey
.second
.vchCryptedKey
, _vMasterKey
))
308 continue; // try another master key
309 if (CCryptoKeyStore::Unlock(_vMasterKey
))
316 bool CWallet::ChangeWalletPassphrase(const SecureString
& strOldWalletPassphrase
, const SecureString
& strNewWalletPassphrase
)
318 bool fWasLocked
= IsLocked();
325 CKeyingMaterial _vMasterKey
;
326 BOOST_FOREACH(MasterKeyMap::value_type
& pMasterKey
, mapMasterKeys
)
328 if(!crypter
.SetKeyFromPassphrase(strOldWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
))
330 if (!crypter
.Decrypt(pMasterKey
.second
.vchCryptedKey
, _vMasterKey
))
332 if (CCryptoKeyStore::Unlock(_vMasterKey
))
334 int64_t nStartTime
= GetTimeMillis();
335 crypter
.SetKeyFromPassphrase(strNewWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
);
336 pMasterKey
.second
.nDeriveIterations
= pMasterKey
.second
.nDeriveIterations
* (100 / ((double)(GetTimeMillis() - nStartTime
)));
338 nStartTime
= GetTimeMillis();
339 crypter
.SetKeyFromPassphrase(strNewWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
);
340 pMasterKey
.second
.nDeriveIterations
= (pMasterKey
.second
.nDeriveIterations
+ pMasterKey
.second
.nDeriveIterations
* 100 / ((double)(GetTimeMillis() - nStartTime
))) / 2;
342 if (pMasterKey
.second
.nDeriveIterations
< 25000)
343 pMasterKey
.second
.nDeriveIterations
= 25000;
345 LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey
.second
.nDeriveIterations
);
347 if (!crypter
.SetKeyFromPassphrase(strNewWalletPassphrase
, pMasterKey
.second
.vchSalt
, pMasterKey
.second
.nDeriveIterations
, pMasterKey
.second
.nDerivationMethod
))
349 if (!crypter
.Encrypt(_vMasterKey
, pMasterKey
.second
.vchCryptedKey
))
351 CWalletDB(strWalletFile
).WriteMasterKey(pMasterKey
.first
, pMasterKey
.second
);
362 void CWallet::SetBestChain(const CBlockLocator
& loc
)
364 CWalletDB
walletdb(strWalletFile
);
365 walletdb
.WriteBestBlock(loc
);
368 bool CWallet::SetMinVersion(enum WalletFeature nVersion
, CWalletDB
* pwalletdbIn
, bool fExplicit
)
370 LOCK(cs_wallet
); // nWalletVersion
371 if (nWalletVersion
>= nVersion
)
374 // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way
375 if (fExplicit
&& nVersion
> nWalletMaxVersion
)
376 nVersion
= FEATURE_LATEST
;
378 nWalletVersion
= nVersion
;
380 if (nVersion
> nWalletMaxVersion
)
381 nWalletMaxVersion
= nVersion
;
385 CWalletDB
* pwalletdb
= pwalletdbIn
? pwalletdbIn
: new CWalletDB(strWalletFile
);
386 if (nWalletVersion
> 40000)
387 pwalletdb
->WriteMinVersion(nWalletVersion
);
395 bool CWallet::SetMaxVersion(int nVersion
)
397 LOCK(cs_wallet
); // nWalletVersion, nWalletMaxVersion
398 // cannot downgrade below current version
399 if (nWalletVersion
> nVersion
)
402 nWalletMaxVersion
= nVersion
;
407 set
<uint256
> CWallet::GetConflicts(const uint256
& txid
) const
410 AssertLockHeld(cs_wallet
);
412 std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.find(txid
);
413 if (it
== mapWallet
.end())
415 const CWalletTx
& wtx
= it
->second
;
417 std::pair
<TxSpends::const_iterator
, TxSpends::const_iterator
> range
;
419 BOOST_FOREACH(const CTxIn
& txin
, wtx
.tx
->vin
)
421 if (mapTxSpends
.count(txin
.prevout
) <= 1)
422 continue; // No conflict if zero or one spends
423 range
= mapTxSpends
.equal_range(txin
.prevout
);
424 for (TxSpends::const_iterator _it
= range
.first
; _it
!= range
.second
; ++_it
)
425 result
.insert(_it
->second
);
430 bool CWallet::HasWalletSpend(const uint256
& txid
) const
432 AssertLockHeld(cs_wallet
);
433 auto iter
= mapTxSpends
.lower_bound(COutPoint(txid
, 0));
434 return (iter
!= mapTxSpends
.end() && iter
->first
.hash
== txid
);
437 void CWallet::Flush(bool shutdown
)
439 bitdb
.Flush(shutdown
);
442 bool CWallet::Verify()
444 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET
))
447 LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
448 std::string walletFile
= GetArg("-wallet", DEFAULT_WALLET_DAT
);
450 LogPrintf("Using wallet %s\n", walletFile
);
451 uiInterface
.InitMessage(_("Verifying wallet..."));
453 // Wallet file must be a plain filename without a directory
454 if (walletFile
!= boost::filesystem::basename(walletFile
) + boost::filesystem::extension(walletFile
))
455 return InitError(strprintf(_("Wallet %s resides outside data directory %s"), walletFile
, GetDataDir().string()));
457 if (!bitdb
.Open(GetDataDir()))
459 // try moving the database env out of the way
460 boost::filesystem::path pathDatabase
= GetDataDir() / "database";
461 boost::filesystem::path pathDatabaseBak
= GetDataDir() / strprintf("database.%d.bak", GetTime());
463 boost::filesystem::rename(pathDatabase
, pathDatabaseBak
);
464 LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase
.string(), pathDatabaseBak
.string());
465 } catch (const boost::filesystem::filesystem_error
&) {
466 // failure is ok (well, not really, but it's not worse than what we started with)
470 if (!bitdb
.Open(GetDataDir())) {
471 // if it still fails, it probably means we can't even create the database env
472 return InitError(strprintf(_("Error initializing wallet database environment %s!"), GetDataDir()));
476 if (GetBoolArg("-salvagewallet", false))
478 // Recover readable keypairs:
479 if (!CWalletDB::Recover(bitdb
, walletFile
, true))
483 if (boost::filesystem::exists(GetDataDir() / walletFile
))
485 CDBEnv::VerifyResult r
= bitdb
.Verify(walletFile
, CWalletDB::Recover
);
486 if (r
== CDBEnv::RECOVER_OK
)
488 InitWarning(strprintf(_("Warning: Wallet file corrupt, data salvaged!"
489 " Original %s saved as %s in %s; if"
490 " your balance or transactions are incorrect you should"
491 " restore from a backup."),
492 walletFile
, "wallet.{timestamp}.bak", GetDataDir()));
494 if (r
== CDBEnv::RECOVER_FAIL
)
495 return InitError(strprintf(_("%s corrupt, salvage failed"), walletFile
));
501 void CWallet::SyncMetaData(pair
<TxSpends::iterator
, TxSpends::iterator
> range
)
503 // We want all the wallet transactions in range to have the same metadata as
504 // the oldest (smallest nOrderPos).
505 // So: find smallest nOrderPos:
507 int nMinOrderPos
= std::numeric_limits
<int>::max();
508 const CWalletTx
* copyFrom
= NULL
;
509 for (TxSpends::iterator it
= range
.first
; it
!= range
.second
; ++it
)
511 const uint256
& hash
= it
->second
;
512 int n
= mapWallet
[hash
].nOrderPos
;
513 if (n
< nMinOrderPos
)
516 copyFrom
= &mapWallet
[hash
];
519 // Now copy data from copyFrom to rest:
520 for (TxSpends::iterator it
= range
.first
; it
!= range
.second
; ++it
)
522 const uint256
& hash
= it
->second
;
523 CWalletTx
* copyTo
= &mapWallet
[hash
];
524 if (copyFrom
== copyTo
) continue;
525 if (!copyFrom
->IsEquivalentTo(*copyTo
)) continue;
526 copyTo
->mapValue
= copyFrom
->mapValue
;
527 copyTo
->vOrderForm
= copyFrom
->vOrderForm
;
528 // fTimeReceivedIsTxTime not copied on purpose
529 // nTimeReceived not copied on purpose
530 copyTo
->nTimeSmart
= copyFrom
->nTimeSmart
;
531 copyTo
->fFromMe
= copyFrom
->fFromMe
;
532 copyTo
->strFromAccount
= copyFrom
->strFromAccount
;
533 // nOrderPos not copied on purpose
534 // cached members not copied on purpose
539 * Outpoint is spent if any non-conflicted transaction
542 bool CWallet::IsSpent(const uint256
& hash
, unsigned int n
) const
544 const COutPoint
outpoint(hash
, n
);
545 pair
<TxSpends::const_iterator
, TxSpends::const_iterator
> range
;
546 range
= mapTxSpends
.equal_range(outpoint
);
548 for (TxSpends::const_iterator it
= range
.first
; it
!= range
.second
; ++it
)
550 const uint256
& wtxid
= it
->second
;
551 std::map
<uint256
, CWalletTx
>::const_iterator mit
= mapWallet
.find(wtxid
);
552 if (mit
!= mapWallet
.end()) {
553 int depth
= mit
->second
.GetDepthInMainChain();
554 if (depth
> 0 || (depth
== 0 && !mit
->second
.isAbandoned()))
555 return true; // Spent
561 void CWallet::AddToSpends(const COutPoint
& outpoint
, const uint256
& wtxid
)
563 mapTxSpends
.insert(make_pair(outpoint
, wtxid
));
565 pair
<TxSpends::iterator
, TxSpends::iterator
> range
;
566 range
= mapTxSpends
.equal_range(outpoint
);
571 void CWallet::AddToSpends(const uint256
& wtxid
)
573 assert(mapWallet
.count(wtxid
));
574 CWalletTx
& thisTx
= mapWallet
[wtxid
];
575 if (thisTx
.IsCoinBase()) // Coinbases don't spend anything!
578 BOOST_FOREACH(const CTxIn
& txin
, thisTx
.tx
->vin
)
579 AddToSpends(txin
.prevout
, wtxid
);
582 bool CWallet::EncryptWallet(const SecureString
& strWalletPassphrase
)
587 CKeyingMaterial _vMasterKey
;
589 _vMasterKey
.resize(WALLET_CRYPTO_KEY_SIZE
);
590 GetStrongRandBytes(&_vMasterKey
[0], WALLET_CRYPTO_KEY_SIZE
);
592 CMasterKey kMasterKey
;
594 kMasterKey
.vchSalt
.resize(WALLET_CRYPTO_SALT_SIZE
);
595 GetStrongRandBytes(&kMasterKey
.vchSalt
[0], WALLET_CRYPTO_SALT_SIZE
);
598 int64_t nStartTime
= GetTimeMillis();
599 crypter
.SetKeyFromPassphrase(strWalletPassphrase
, kMasterKey
.vchSalt
, 25000, kMasterKey
.nDerivationMethod
);
600 kMasterKey
.nDeriveIterations
= 2500000 / ((double)(GetTimeMillis() - nStartTime
));
602 nStartTime
= GetTimeMillis();
603 crypter
.SetKeyFromPassphrase(strWalletPassphrase
, kMasterKey
.vchSalt
, kMasterKey
.nDeriveIterations
, kMasterKey
.nDerivationMethod
);
604 kMasterKey
.nDeriveIterations
= (kMasterKey
.nDeriveIterations
+ kMasterKey
.nDeriveIterations
* 100 / ((double)(GetTimeMillis() - nStartTime
))) / 2;
606 if (kMasterKey
.nDeriveIterations
< 25000)
607 kMasterKey
.nDeriveIterations
= 25000;
609 LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey
.nDeriveIterations
);
611 if (!crypter
.SetKeyFromPassphrase(strWalletPassphrase
, kMasterKey
.vchSalt
, kMasterKey
.nDeriveIterations
, kMasterKey
.nDerivationMethod
))
613 if (!crypter
.Encrypt(_vMasterKey
, kMasterKey
.vchCryptedKey
))
618 mapMasterKeys
[++nMasterKeyMaxID
] = kMasterKey
;
621 assert(!pwalletdbEncryption
);
622 pwalletdbEncryption
= new CWalletDB(strWalletFile
);
623 if (!pwalletdbEncryption
->TxnBegin()) {
624 delete pwalletdbEncryption
;
625 pwalletdbEncryption
= NULL
;
628 pwalletdbEncryption
->WriteMasterKey(nMasterKeyMaxID
, kMasterKey
);
631 if (!EncryptKeys(_vMasterKey
))
634 pwalletdbEncryption
->TxnAbort();
635 delete pwalletdbEncryption
;
637 // We now probably have half of our keys encrypted in memory, and half not...
638 // die and let the user reload the unencrypted wallet.
642 // Encryption was introduced in version 0.4.0
643 SetMinVersion(FEATURE_WALLETCRYPT
, pwalletdbEncryption
, true);
647 if (!pwalletdbEncryption
->TxnCommit()) {
648 delete pwalletdbEncryption
;
649 // We now have keys encrypted in memory, but not on disk...
650 // die to avoid confusion and let the user reload the unencrypted wallet.
654 delete pwalletdbEncryption
;
655 pwalletdbEncryption
= NULL
;
659 Unlock(strWalletPassphrase
);
661 // if we are using HD, replace the HD master key (seed) with a new one
664 CPubKey masterPubKey
= GenerateNewHDMasterKey();
665 if (!SetHDMasterKey(masterPubKey
))
672 // Need to completely rewrite the wallet file; if we don't, bdb might keep
673 // bits of the unencrypted private key in slack space in the database file.
674 CDB::Rewrite(strWalletFile
);
677 NotifyStatusChanged(this);
682 DBErrors
CWallet::ReorderTransactions()
685 CWalletDB
walletdb(strWalletFile
);
687 // Old wallets didn't have any defined order for transactions
688 // Probably a bad idea to change the output of this
690 // First: get all CWalletTx and CAccountingEntry into a sorted-by-time multimap.
691 typedef pair
<CWalletTx
*, CAccountingEntry
*> TxPair
;
692 typedef multimap
<int64_t, TxPair
> TxItems
;
695 for (map
<uint256
, CWalletTx
>::iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
697 CWalletTx
* wtx
= &((*it
).second
);
698 txByTime
.insert(make_pair(wtx
->nTimeReceived
, TxPair(wtx
, (CAccountingEntry
*)0)));
700 list
<CAccountingEntry
> acentries
;
701 walletdb
.ListAccountCreditDebit("", acentries
);
702 BOOST_FOREACH(CAccountingEntry
& entry
, acentries
)
704 txByTime
.insert(make_pair(entry
.nTime
, TxPair((CWalletTx
*)0, &entry
)));
708 std::vector
<int64_t> nOrderPosOffsets
;
709 for (TxItems::iterator it
= txByTime
.begin(); it
!= txByTime
.end(); ++it
)
711 CWalletTx
*const pwtx
= (*it
).second
.first
;
712 CAccountingEntry
*const pacentry
= (*it
).second
.second
;
713 int64_t& nOrderPos
= (pwtx
!= 0) ? pwtx
->nOrderPos
: pacentry
->nOrderPos
;
717 nOrderPos
= nOrderPosNext
++;
718 nOrderPosOffsets
.push_back(nOrderPos
);
722 if (!walletdb
.WriteTx(*pwtx
))
726 if (!walletdb
.WriteAccountingEntry(pacentry
->nEntryNo
, *pacentry
))
731 int64_t nOrderPosOff
= 0;
732 BOOST_FOREACH(const int64_t& nOffsetStart
, nOrderPosOffsets
)
734 if (nOrderPos
>= nOffsetStart
)
737 nOrderPos
+= nOrderPosOff
;
738 nOrderPosNext
= std::max(nOrderPosNext
, nOrderPos
+ 1);
743 // Since we're changing the order, write it back
746 if (!walletdb
.WriteTx(*pwtx
))
750 if (!walletdb
.WriteAccountingEntry(pacentry
->nEntryNo
, *pacentry
))
754 walletdb
.WriteOrderPosNext(nOrderPosNext
);
759 int64_t CWallet::IncOrderPosNext(CWalletDB
*pwalletdb
)
761 AssertLockHeld(cs_wallet
); // nOrderPosNext
762 int64_t nRet
= nOrderPosNext
++;
764 pwalletdb
->WriteOrderPosNext(nOrderPosNext
);
766 CWalletDB(strWalletFile
).WriteOrderPosNext(nOrderPosNext
);
771 bool CWallet::AccountMove(std::string strFrom
, std::string strTo
, CAmount nAmount
, std::string strComment
)
773 CWalletDB
walletdb(strWalletFile
);
774 if (!walletdb
.TxnBegin())
777 int64_t nNow
= GetAdjustedTime();
780 CAccountingEntry debit
;
781 debit
.nOrderPos
= IncOrderPosNext(&walletdb
);
782 debit
.strAccount
= strFrom
;
783 debit
.nCreditDebit
= -nAmount
;
785 debit
.strOtherAccount
= strTo
;
786 debit
.strComment
= strComment
;
787 AddAccountingEntry(debit
, &walletdb
);
790 CAccountingEntry credit
;
791 credit
.nOrderPos
= IncOrderPosNext(&walletdb
);
792 credit
.strAccount
= strTo
;
793 credit
.nCreditDebit
= nAmount
;
795 credit
.strOtherAccount
= strFrom
;
796 credit
.strComment
= strComment
;
797 AddAccountingEntry(credit
, &walletdb
);
799 if (!walletdb
.TxnCommit())
805 bool CWallet::GetAccountPubkey(CPubKey
&pubKey
, std::string strAccount
, bool bForceNew
)
807 CWalletDB
walletdb(strWalletFile
);
810 walletdb
.ReadAccount(strAccount
, account
);
813 if (!account
.vchPubKey
.IsValid())
816 // Check if the current key has been used
817 CScript scriptPubKey
= GetScriptForDestination(account
.vchPubKey
.GetID());
818 for (map
<uint256
, CWalletTx
>::iterator it
= mapWallet
.begin();
819 it
!= mapWallet
.end() && account
.vchPubKey
.IsValid();
821 BOOST_FOREACH(const CTxOut
& txout
, (*it
).second
.tx
->vout
)
822 if (txout
.scriptPubKey
== scriptPubKey
) {
829 // Generate a new key
831 if (!GetKeyFromPool(account
.vchPubKey
))
834 SetAddressBook(account
.vchPubKey
.GetID(), strAccount
, "receive");
835 walletdb
.WriteAccount(strAccount
, account
);
838 pubKey
= account
.vchPubKey
;
843 void CWallet::MarkDirty()
847 BOOST_FOREACH(PAIRTYPE(const uint256
, CWalletTx
)& item
, mapWallet
)
848 item
.second
.MarkDirty();
852 bool CWallet::MarkReplaced(const uint256
& originalHash
, const uint256
& newHash
)
856 auto mi
= mapWallet
.find(originalHash
);
858 // There is a bug if MarkReplaced is not called on an existing wallet transaction.
859 assert(mi
!= mapWallet
.end());
861 CWalletTx
& wtx
= (*mi
).second
;
863 // Ensure for now that we're not overwriting data
864 assert(wtx
.mapValue
.count("replaced_by_txid") == 0);
866 wtx
.mapValue
["replaced_by_txid"] = newHash
.ToString();
868 CWalletDB
walletdb(strWalletFile
, "r+");
871 if (!walletdb
.WriteTx(wtx
)) {
872 LogPrintf("%s: Updating walletdb tx %s failed", __func__
, wtx
.GetHash().ToString());
876 NotifyTransactionChanged(this, originalHash
, CT_UPDATED
);
881 bool CWallet::AddToWallet(const CWalletTx
& wtxIn
, bool fFlushOnClose
)
885 CWalletDB
walletdb(strWalletFile
, "r+", fFlushOnClose
);
887 uint256 hash
= wtxIn
.GetHash();
889 // Inserts only if not already there, returns tx inserted or tx found
890 pair
<map
<uint256
, CWalletTx
>::iterator
, bool> ret
= mapWallet
.insert(make_pair(hash
, wtxIn
));
891 CWalletTx
& wtx
= (*ret
.first
).second
;
892 wtx
.BindWallet(this);
893 bool fInsertedNew
= ret
.second
;
896 wtx
.nTimeReceived
= GetAdjustedTime();
897 wtx
.nOrderPos
= IncOrderPosNext(&walletdb
);
898 wtxOrdered
.insert(make_pair(wtx
.nOrderPos
, TxPair(&wtx
, (CAccountingEntry
*)0)));
900 wtx
.nTimeSmart
= wtx
.nTimeReceived
;
901 if (!wtxIn
.hashUnset())
903 if (mapBlockIndex
.count(wtxIn
.hashBlock
))
905 int64_t latestNow
= wtx
.nTimeReceived
;
906 int64_t latestEntry
= 0;
908 // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future
909 int64_t latestTolerated
= latestNow
+ 300;
910 const TxItems
& txOrdered
= wtxOrdered
;
911 for (TxItems::const_reverse_iterator it
= txOrdered
.rbegin(); it
!= txOrdered
.rend(); ++it
)
913 CWalletTx
*const pwtx
= (*it
).second
.first
;
916 CAccountingEntry
*const pacentry
= (*it
).second
.second
;
920 nSmartTime
= pwtx
->nTimeSmart
;
922 nSmartTime
= pwtx
->nTimeReceived
;
925 nSmartTime
= pacentry
->nTime
;
926 if (nSmartTime
<= latestTolerated
)
928 latestEntry
= nSmartTime
;
929 if (nSmartTime
> latestNow
)
930 latestNow
= nSmartTime
;
936 int64_t blocktime
= mapBlockIndex
[wtxIn
.hashBlock
]->GetBlockTime();
937 wtx
.nTimeSmart
= std::max(latestEntry
, std::min(blocktime
, latestNow
));
940 LogPrintf("AddToWallet(): found %s in block %s not in index\n",
941 wtxIn
.GetHash().ToString(),
942 wtxIn
.hashBlock
.ToString());
947 bool fUpdated
= false;
951 if (!wtxIn
.hashUnset() && wtxIn
.hashBlock
!= wtx
.hashBlock
)
953 wtx
.hashBlock
= wtxIn
.hashBlock
;
956 // If no longer abandoned, update
957 if (wtxIn
.hashBlock
.IsNull() && wtx
.isAbandoned())
959 wtx
.hashBlock
= wtxIn
.hashBlock
;
962 if (wtxIn
.nIndex
!= -1 && (wtxIn
.nIndex
!= wtx
.nIndex
))
964 wtx
.nIndex
= wtxIn
.nIndex
;
967 if (wtxIn
.fFromMe
&& wtxIn
.fFromMe
!= wtx
.fFromMe
)
969 wtx
.fFromMe
= wtxIn
.fFromMe
;
975 LogPrintf("AddToWallet %s %s%s\n", wtxIn
.GetHash().ToString(), (fInsertedNew
? "new" : ""), (fUpdated
? "update" : ""));
978 if (fInsertedNew
|| fUpdated
)
979 if (!walletdb
.WriteTx(wtx
))
982 // Break debit/credit balance caches:
985 // Notify UI of new or updated transaction
986 NotifyTransactionChanged(this, hash
, fInsertedNew
? CT_NEW
: CT_UPDATED
);
988 // notify an external script when a wallet transaction comes in or is updated
989 std::string strCmd
= GetArg("-walletnotify", "");
991 if ( !strCmd
.empty())
993 boost::replace_all(strCmd
, "%s", wtxIn
.GetHash().GetHex());
994 boost::thread
t(runCommand
, strCmd
); // thread runs free
1000 bool CWallet::LoadToWallet(const CWalletTx
& wtxIn
)
1002 uint256 hash
= wtxIn
.GetHash();
1004 mapWallet
[hash
] = wtxIn
;
1005 CWalletTx
& wtx
= mapWallet
[hash
];
1006 wtx
.BindWallet(this);
1007 wtxOrdered
.insert(make_pair(wtx
.nOrderPos
, TxPair(&wtx
, (CAccountingEntry
*)0)));
1009 BOOST_FOREACH(const CTxIn
& txin
, wtx
.tx
->vin
) {
1010 if (mapWallet
.count(txin
.prevout
.hash
)) {
1011 CWalletTx
& prevtx
= mapWallet
[txin
.prevout
.hash
];
1012 if (prevtx
.nIndex
== -1 && !prevtx
.hashUnset()) {
1013 MarkConflicted(prevtx
.hashBlock
, wtx
.GetHash());
1022 * Add a transaction to the wallet, or update it. pIndex and posInBlock should
1023 * be set when the transaction was known to be included in a block. When
1024 * posInBlock = SYNC_TRANSACTION_NOT_IN_BLOCK (-1) , then wallet state is not
1025 * updated in AddToWallet, but notifications happen and cached balances are
1027 * If fUpdate is true, existing transactions will be updated.
1028 * TODO: One exception to this is that the abandoned state is cleared under the
1029 * assumption that any further notification of a transaction that was considered
1030 * abandoned is an indication that it is not safe to be considered abandoned.
1031 * Abandoned state should probably be more carefully tracked via different
1032 * posInBlock signals or by checking mempool presence when necessary.
1034 bool CWallet::AddToWalletIfInvolvingMe(const CTransaction
& tx
, const CBlockIndex
* pIndex
, int posInBlock
, bool fUpdate
)
1037 AssertLockHeld(cs_wallet
);
1039 if (posInBlock
!= -1) {
1040 BOOST_FOREACH(const CTxIn
& txin
, tx
.vin
) {
1041 std::pair
<TxSpends::const_iterator
, TxSpends::const_iterator
> range
= mapTxSpends
.equal_range(txin
.prevout
);
1042 while (range
.first
!= range
.second
) {
1043 if (range
.first
->second
!= tx
.GetHash()) {
1044 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
);
1045 MarkConflicted(pIndex
->GetBlockHash(), range
.first
->second
);
1052 bool fExisted
= mapWallet
.count(tx
.GetHash()) != 0;
1053 if (fExisted
&& !fUpdate
) return false;
1054 if (fExisted
|| IsMine(tx
) || IsFromMe(tx
))
1056 CWalletTx
wtx(this, MakeTransactionRef(tx
));
1058 // Get merkle branch if transaction was found in a block
1059 if (posInBlock
!= -1)
1060 wtx
.SetMerkleBranch(pIndex
, posInBlock
);
1062 return AddToWallet(wtx
, false);
1068 bool CWallet::AbandonTransaction(const uint256
& hashTx
)
1070 LOCK2(cs_main
, cs_wallet
);
1072 CWalletDB
walletdb(strWalletFile
, "r+");
1074 std::set
<uint256
> todo
;
1075 std::set
<uint256
> done
;
1077 // Can't mark abandoned if confirmed or in mempool
1078 assert(mapWallet
.count(hashTx
));
1079 CWalletTx
& origtx
= mapWallet
[hashTx
];
1080 if (origtx
.GetDepthInMainChain() > 0 || origtx
.InMempool()) {
1084 todo
.insert(hashTx
);
1086 while (!todo
.empty()) {
1087 uint256 now
= *todo
.begin();
1090 assert(mapWallet
.count(now
));
1091 CWalletTx
& wtx
= mapWallet
[now
];
1092 int currentconfirm
= wtx
.GetDepthInMainChain();
1093 // If the orig tx was not in block, none of its spends can be
1094 assert(currentconfirm
<= 0);
1095 // if (currentconfirm < 0) {Tx and spends are already conflicted, no need to abandon}
1096 if (currentconfirm
== 0 && !wtx
.isAbandoned()) {
1097 // If the orig tx was not in block/mempool, none of its spends can be in mempool
1098 assert(!wtx
.InMempool());
1102 walletdb
.WriteTx(wtx
);
1103 NotifyTransactionChanged(this, wtx
.GetHash(), CT_UPDATED
);
1104 // Iterate over all its outputs, and mark transactions in the wallet that spend them abandoned too
1105 TxSpends::const_iterator iter
= mapTxSpends
.lower_bound(COutPoint(hashTx
, 0));
1106 while (iter
!= mapTxSpends
.end() && iter
->first
.hash
== now
) {
1107 if (!done
.count(iter
->second
)) {
1108 todo
.insert(iter
->second
);
1112 // If a transaction changes 'conflicted' state, that changes the balance
1113 // available of the outputs it spends. So force those to be recomputed
1114 BOOST_FOREACH(const CTxIn
& txin
, wtx
.tx
->vin
)
1116 if (mapWallet
.count(txin
.prevout
.hash
))
1117 mapWallet
[txin
.prevout
.hash
].MarkDirty();
1125 void CWallet::MarkConflicted(const uint256
& hashBlock
, const uint256
& hashTx
)
1127 LOCK2(cs_main
, cs_wallet
);
1129 int conflictconfirms
= 0;
1130 if (mapBlockIndex
.count(hashBlock
)) {
1131 CBlockIndex
* pindex
= mapBlockIndex
[hashBlock
];
1132 if (chainActive
.Contains(pindex
)) {
1133 conflictconfirms
= -(chainActive
.Height() - pindex
->nHeight
+ 1);
1136 // If number of conflict confirms cannot be determined, this means
1137 // that the block is still unknown or not yet part of the main chain,
1138 // for example when loading the wallet during a reindex. Do nothing in that
1140 if (conflictconfirms
>= 0)
1143 // Do not flush the wallet here for performance reasons
1144 CWalletDB
walletdb(strWalletFile
, "r+", false);
1146 std::set
<uint256
> todo
;
1147 std::set
<uint256
> done
;
1149 todo
.insert(hashTx
);
1151 while (!todo
.empty()) {
1152 uint256 now
= *todo
.begin();
1155 assert(mapWallet
.count(now
));
1156 CWalletTx
& wtx
= mapWallet
[now
];
1157 int currentconfirm
= wtx
.GetDepthInMainChain();
1158 if (conflictconfirms
< currentconfirm
) {
1159 // Block is 'more conflicted' than current confirm; update.
1160 // Mark transaction as conflicted with this block.
1162 wtx
.hashBlock
= hashBlock
;
1164 walletdb
.WriteTx(wtx
);
1165 // Iterate over all its outputs, and mark transactions in the wallet that spend them conflicted too
1166 TxSpends::const_iterator iter
= mapTxSpends
.lower_bound(COutPoint(now
, 0));
1167 while (iter
!= mapTxSpends
.end() && iter
->first
.hash
== now
) {
1168 if (!done
.count(iter
->second
)) {
1169 todo
.insert(iter
->second
);
1173 // If a transaction changes 'conflicted' state, that changes the balance
1174 // available of the outputs it spends. So force those to be recomputed
1175 BOOST_FOREACH(const CTxIn
& txin
, wtx
.tx
->vin
)
1177 if (mapWallet
.count(txin
.prevout
.hash
))
1178 mapWallet
[txin
.prevout
.hash
].MarkDirty();
1184 void CWallet::SyncTransaction(const CTransaction
& tx
, const CBlockIndex
*pindex
, int posInBlock
)
1186 LOCK2(cs_main
, cs_wallet
);
1188 if (!AddToWalletIfInvolvingMe(tx
, pindex
, posInBlock
, true))
1189 return; // Not one of ours
1191 // If a transaction changes 'conflicted' state, that changes the balance
1192 // available of the outputs it spends. So force those to be
1193 // recomputed, also:
1194 BOOST_FOREACH(const CTxIn
& txin
, tx
.vin
)
1196 if (mapWallet
.count(txin
.prevout
.hash
))
1197 mapWallet
[txin
.prevout
.hash
].MarkDirty();
1202 isminetype
CWallet::IsMine(const CTxIn
&txin
) const
1206 map
<uint256
, CWalletTx
>::const_iterator mi
= mapWallet
.find(txin
.prevout
.hash
);
1207 if (mi
!= mapWallet
.end())
1209 const CWalletTx
& prev
= (*mi
).second
;
1210 if (txin
.prevout
.n
< prev
.tx
->vout
.size())
1211 return IsMine(prev
.tx
->vout
[txin
.prevout
.n
]);
1217 // Note that this function doesn't distinguish between a 0-valued input,
1218 // and a not-"is mine" (according to the filter) input.
1219 CAmount
CWallet::GetDebit(const CTxIn
&txin
, const isminefilter
& filter
) const
1223 map
<uint256
, CWalletTx
>::const_iterator mi
= mapWallet
.find(txin
.prevout
.hash
);
1224 if (mi
!= mapWallet
.end())
1226 const CWalletTx
& prev
= (*mi
).second
;
1227 if (txin
.prevout
.n
< prev
.tx
->vout
.size())
1228 if (IsMine(prev
.tx
->vout
[txin
.prevout
.n
]) & filter
)
1229 return prev
.tx
->vout
[txin
.prevout
.n
].nValue
;
1235 isminetype
CWallet::IsMine(const CTxOut
& txout
) const
1237 return ::IsMine(*this, txout
.scriptPubKey
);
1240 CAmount
CWallet::GetCredit(const CTxOut
& txout
, const isminefilter
& filter
) const
1242 if (!MoneyRange(txout
.nValue
))
1243 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1244 return ((IsMine(txout
) & filter
) ? txout
.nValue
: 0);
1247 bool CWallet::IsChange(const CTxOut
& txout
) const
1249 // TODO: fix handling of 'change' outputs. The assumption is that any
1250 // payment to a script that is ours, but is not in the address book
1251 // is change. That assumption is likely to break when we implement multisignature
1252 // wallets that return change back into a multi-signature-protected address;
1253 // a better way of identifying which outputs are 'the send' and which are
1254 // 'the change' will need to be implemented (maybe extend CWalletTx to remember
1255 // which output, if any, was change).
1256 if (::IsMine(*this, txout
.scriptPubKey
))
1258 CTxDestination address
;
1259 if (!ExtractDestination(txout
.scriptPubKey
, address
))
1263 if (!mapAddressBook
.count(address
))
1269 CAmount
CWallet::GetChange(const CTxOut
& txout
) const
1271 if (!MoneyRange(txout
.nValue
))
1272 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1273 return (IsChange(txout
) ? txout
.nValue
: 0);
1276 bool CWallet::IsMine(const CTransaction
& tx
) const
1278 BOOST_FOREACH(const CTxOut
& txout
, tx
.vout
)
1284 bool CWallet::IsFromMe(const CTransaction
& tx
) const
1286 return (GetDebit(tx
, ISMINE_ALL
) > 0);
1289 CAmount
CWallet::GetDebit(const CTransaction
& tx
, const isminefilter
& filter
) const
1292 BOOST_FOREACH(const CTxIn
& txin
, tx
.vin
)
1294 nDebit
+= GetDebit(txin
, filter
);
1295 if (!MoneyRange(nDebit
))
1296 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1301 bool CWallet::IsAllFromMe(const CTransaction
& tx
, const isminefilter
& filter
) const
1305 BOOST_FOREACH(const CTxIn
& txin
, tx
.vin
)
1307 auto mi
= mapWallet
.find(txin
.prevout
.hash
);
1308 if (mi
== mapWallet
.end())
1309 return false; // any unknown inputs can't be from us
1311 const CWalletTx
& prev
= (*mi
).second
;
1313 if (txin
.prevout
.n
>= prev
.tx
->vout
.size())
1314 return false; // invalid input!
1316 if (!(IsMine(prev
.tx
->vout
[txin
.prevout
.n
]) & filter
))
1322 CAmount
CWallet::GetCredit(const CTransaction
& tx
, const isminefilter
& filter
) const
1324 CAmount nCredit
= 0;
1325 BOOST_FOREACH(const CTxOut
& txout
, tx
.vout
)
1327 nCredit
+= GetCredit(txout
, filter
);
1328 if (!MoneyRange(nCredit
))
1329 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1334 CAmount
CWallet::GetChange(const CTransaction
& tx
) const
1336 CAmount nChange
= 0;
1337 BOOST_FOREACH(const CTxOut
& txout
, tx
.vout
)
1339 nChange
+= GetChange(txout
);
1340 if (!MoneyRange(nChange
))
1341 throw std::runtime_error(std::string(__func__
) + ": value out of range");
1346 CPubKey
CWallet::GenerateNewHDMasterKey()
1349 key
.MakeNewKey(true);
1351 int64_t nCreationTime
= GetTime();
1352 CKeyMetadata
metadata(nCreationTime
);
1354 // calculate the pubkey
1355 CPubKey pubkey
= key
.GetPubKey();
1356 assert(key
.VerifyPubKey(pubkey
));
1358 // set the hd keypath to "m" -> Master, refers the masterkeyid to itself
1359 metadata
.hdKeypath
= "m";
1360 metadata
.hdMasterKeyID
= pubkey
.GetID();
1365 // mem store the metadata
1366 mapKeyMetadata
[pubkey
.GetID()] = metadata
;
1368 // write the key&metadata to the database
1369 if (!AddKeyPubKey(key
, pubkey
))
1370 throw std::runtime_error(std::string(__func__
) + ": AddKeyPubKey failed");
1376 bool CWallet::SetHDMasterKey(const CPubKey
& pubkey
)
1380 // ensure this wallet.dat can only be opened by clients supporting HD
1381 SetMinVersion(FEATURE_HD
);
1383 // store the keyid (hash160) together with
1384 // the child index counter in the database
1385 // as a hdchain object
1386 CHDChain newHdChain
;
1387 newHdChain
.masterKeyID
= pubkey
.GetID();
1388 SetHDChain(newHdChain
, false);
1393 bool CWallet::SetHDChain(const CHDChain
& chain
, bool memonly
)
1396 if (!memonly
&& !CWalletDB(strWalletFile
).WriteHDChain(chain
))
1397 throw runtime_error(std::string(__func__
) + ": writing chain failed");
1403 bool CWallet::IsHDEnabled()
1405 return !hdChain
.masterKeyID
.IsNull();
1408 int64_t CWalletTx::GetTxTime() const
1410 int64_t n
= nTimeSmart
;
1411 return n
? n
: nTimeReceived
;
1414 int CWalletTx::GetRequestCount() const
1416 // Returns -1 if it wasn't being tracked
1419 LOCK(pwallet
->cs_wallet
);
1425 map
<uint256
, int>::const_iterator mi
= pwallet
->mapRequestCount
.find(hashBlock
);
1426 if (mi
!= pwallet
->mapRequestCount
.end())
1427 nRequests
= (*mi
).second
;
1432 // Did anyone request this transaction?
1433 map
<uint256
, int>::const_iterator mi
= pwallet
->mapRequestCount
.find(GetHash());
1434 if (mi
!= pwallet
->mapRequestCount
.end())
1436 nRequests
= (*mi
).second
;
1438 // How about the block it's in?
1439 if (nRequests
== 0 && !hashUnset())
1441 map
<uint256
, int>::const_iterator _mi
= pwallet
->mapRequestCount
.find(hashBlock
);
1442 if (_mi
!= pwallet
->mapRequestCount
.end())
1443 nRequests
= (*_mi
).second
;
1445 nRequests
= 1; // If it's in someone else's block it must have got out
1453 void CWalletTx::GetAmounts(list
<COutputEntry
>& listReceived
,
1454 list
<COutputEntry
>& listSent
, CAmount
& nFee
, string
& strSentAccount
, const isminefilter
& filter
) const
1457 listReceived
.clear();
1459 strSentAccount
= strFromAccount
;
1462 CAmount nDebit
= GetDebit(filter
);
1463 if (nDebit
> 0) // debit>0 means we signed/sent this transaction
1465 CAmount nValueOut
= tx
->GetValueOut();
1466 nFee
= nDebit
- nValueOut
;
1470 for (unsigned int i
= 0; i
< tx
->vout
.size(); ++i
)
1472 const CTxOut
& txout
= tx
->vout
[i
];
1473 isminetype fIsMine
= pwallet
->IsMine(txout
);
1474 // Only need to handle txouts if AT LEAST one of these is true:
1475 // 1) they debit from us (sent)
1476 // 2) the output is to us (received)
1479 // Don't report 'change' txouts
1480 if (pwallet
->IsChange(txout
))
1483 else if (!(fIsMine
& filter
))
1486 // In either case, we need to get the destination address
1487 CTxDestination address
;
1489 if (!ExtractDestination(txout
.scriptPubKey
, address
) && !txout
.scriptPubKey
.IsUnspendable())
1491 LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n",
1492 this->GetHash().ToString());
1493 address
= CNoDestination();
1496 COutputEntry output
= {address
, txout
.nValue
, (int)i
};
1498 // If we are debited by the transaction, add the output as a "sent" entry
1500 listSent
.push_back(output
);
1502 // If we are receiving the output, add it as a "received" entry
1503 if (fIsMine
& filter
)
1504 listReceived
.push_back(output
);
1509 void CWalletTx::GetAccountAmounts(const string
& strAccount
, CAmount
& nReceived
,
1510 CAmount
& nSent
, CAmount
& nFee
, const isminefilter
& filter
) const
1512 nReceived
= nSent
= nFee
= 0;
1515 string strSentAccount
;
1516 list
<COutputEntry
> listReceived
;
1517 list
<COutputEntry
> listSent
;
1518 GetAmounts(listReceived
, listSent
, allFee
, strSentAccount
, filter
);
1520 if (strAccount
== strSentAccount
)
1522 BOOST_FOREACH(const COutputEntry
& s
, listSent
)
1527 LOCK(pwallet
->cs_wallet
);
1528 BOOST_FOREACH(const COutputEntry
& r
, listReceived
)
1530 if (pwallet
->mapAddressBook
.count(r
.destination
))
1532 map
<CTxDestination
, CAddressBookData
>::const_iterator mi
= pwallet
->mapAddressBook
.find(r
.destination
);
1533 if (mi
!= pwallet
->mapAddressBook
.end() && (*mi
).second
.name
== strAccount
)
1534 nReceived
+= r
.amount
;
1536 else if (strAccount
.empty())
1538 nReceived
+= r
.amount
;
1545 * Scan the block chain (starting in pindexStart) for transactions
1546 * from or to us. If fUpdate is true, found transactions that already
1547 * exist in the wallet will be updated.
1549 * Returns pointer to the first block in the last contiguous range that was
1550 * successfully scanned.
1553 CBlockIndex
* CWallet::ScanForWalletTransactions(CBlockIndex
* pindexStart
, bool fUpdate
)
1555 CBlockIndex
* ret
= nullptr;
1556 int64_t nNow
= GetTime();
1557 const CChainParams
& chainParams
= Params();
1559 CBlockIndex
* pindex
= pindexStart
;
1561 LOCK2(cs_main
, cs_wallet
);
1563 // no need to read and scan block, if block was created before
1564 // our wallet birthday (as adjusted for block time variability)
1565 while (pindex
&& nTimeFirstKey
&& (pindex
->GetBlockTime() < (nTimeFirstKey
- 7200)))
1566 pindex
= chainActive
.Next(pindex
);
1568 ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup
1569 double dProgressStart
= GuessVerificationProgress(chainParams
.TxData(), pindex
);
1570 double dProgressTip
= GuessVerificationProgress(chainParams
.TxData(), chainActive
.Tip());
1573 if (pindex
->nHeight
% 100 == 0 && dProgressTip
- dProgressStart
> 0.0)
1574 ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((GuessVerificationProgress(chainParams
.TxData(), pindex
) - dProgressStart
) / (dProgressTip
- dProgressStart
) * 100))));
1577 if (ReadBlockFromDisk(block
, pindex
, Params().GetConsensus())) {
1578 for (size_t posInBlock
= 0; posInBlock
< block
.vtx
.size(); ++posInBlock
) {
1579 AddToWalletIfInvolvingMe(*block
.vtx
[posInBlock
], pindex
, posInBlock
, fUpdate
);
1587 pindex
= chainActive
.Next(pindex
);
1588 if (GetTime() >= nNow
+ 60) {
1590 LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex
->nHeight
, GuessVerificationProgress(chainParams
.TxData(), pindex
));
1593 ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI
1598 void CWallet::ReacceptWalletTransactions()
1600 // If transactions aren't being broadcasted, don't let them into local mempool either
1601 if (!fBroadcastTransactions
)
1603 LOCK2(cs_main
, cs_wallet
);
1604 std::map
<int64_t, CWalletTx
*> mapSorted
;
1606 // Sort pending wallet transactions based on their initial wallet insertion order
1607 BOOST_FOREACH(PAIRTYPE(const uint256
, CWalletTx
)& item
, mapWallet
)
1609 const uint256
& wtxid
= item
.first
;
1610 CWalletTx
& wtx
= item
.second
;
1611 assert(wtx
.GetHash() == wtxid
);
1613 int nDepth
= wtx
.GetDepthInMainChain();
1615 if (!wtx
.IsCoinBase() && (nDepth
== 0 && !wtx
.isAbandoned())) {
1616 mapSorted
.insert(std::make_pair(wtx
.nOrderPos
, &wtx
));
1620 // Try to add wallet transactions to memory pool
1621 BOOST_FOREACH(PAIRTYPE(const int64_t, CWalletTx
*)& item
, mapSorted
)
1623 CWalletTx
& wtx
= *(item
.second
);
1626 CValidationState state
;
1627 wtx
.AcceptToMemoryPool(maxTxFee
, state
);
1631 bool CWalletTx::RelayWalletTransaction(CConnman
* connman
)
1633 assert(pwallet
->GetBroadcastTransactions());
1634 if (!IsCoinBase() && !isAbandoned() && GetDepthInMainChain() == 0)
1636 CValidationState state
;
1637 /* GetDepthInMainChain already catches known conflicts. */
1638 if (InMempool() || AcceptToMemoryPool(maxTxFee
, state
)) {
1639 LogPrintf("Relaying wtx %s\n", GetHash().ToString());
1641 CInv
inv(MSG_TX
, GetHash());
1642 connman
->ForEachNode([&inv
](CNode
* pnode
)
1644 pnode
->PushInventory(inv
);
1653 set
<uint256
> CWalletTx::GetConflicts() const
1655 set
<uint256
> result
;
1656 if (pwallet
!= NULL
)
1658 uint256 myHash
= GetHash();
1659 result
= pwallet
->GetConflicts(myHash
);
1660 result
.erase(myHash
);
1665 CAmount
CWalletTx::GetDebit(const isminefilter
& filter
) const
1667 if (tx
->vin
.empty())
1671 if(filter
& ISMINE_SPENDABLE
)
1674 debit
+= nDebitCached
;
1677 nDebitCached
= pwallet
->GetDebit(*this, ISMINE_SPENDABLE
);
1678 fDebitCached
= true;
1679 debit
+= nDebitCached
;
1682 if(filter
& ISMINE_WATCH_ONLY
)
1684 if(fWatchDebitCached
)
1685 debit
+= nWatchDebitCached
;
1688 nWatchDebitCached
= pwallet
->GetDebit(*this, ISMINE_WATCH_ONLY
);
1689 fWatchDebitCached
= true;
1690 debit
+= nWatchDebitCached
;
1696 CAmount
CWalletTx::GetCredit(const isminefilter
& filter
) const
1698 // Must wait until coinbase is safely deep enough in the chain before valuing it
1699 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1703 if (filter
& ISMINE_SPENDABLE
)
1705 // GetBalance can assume transactions in mapWallet won't change
1707 credit
+= nCreditCached
;
1710 nCreditCached
= pwallet
->GetCredit(*this, ISMINE_SPENDABLE
);
1711 fCreditCached
= true;
1712 credit
+= nCreditCached
;
1715 if (filter
& ISMINE_WATCH_ONLY
)
1717 if (fWatchCreditCached
)
1718 credit
+= nWatchCreditCached
;
1721 nWatchCreditCached
= pwallet
->GetCredit(*this, ISMINE_WATCH_ONLY
);
1722 fWatchCreditCached
= true;
1723 credit
+= nWatchCreditCached
;
1729 CAmount
CWalletTx::GetImmatureCredit(bool fUseCache
) const
1731 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1733 if (fUseCache
&& fImmatureCreditCached
)
1734 return nImmatureCreditCached
;
1735 nImmatureCreditCached
= pwallet
->GetCredit(*this, ISMINE_SPENDABLE
);
1736 fImmatureCreditCached
= true;
1737 return nImmatureCreditCached
;
1743 CAmount
CWalletTx::GetAvailableCredit(bool fUseCache
) const
1748 // Must wait until coinbase is safely deep enough in the chain before valuing it
1749 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1752 if (fUseCache
&& fAvailableCreditCached
)
1753 return nAvailableCreditCached
;
1755 CAmount nCredit
= 0;
1756 uint256 hashTx
= GetHash();
1757 for (unsigned int i
= 0; i
< tx
->vout
.size(); i
++)
1759 if (!pwallet
->IsSpent(hashTx
, i
))
1761 const CTxOut
&txout
= tx
->vout
[i
];
1762 nCredit
+= pwallet
->GetCredit(txout
, ISMINE_SPENDABLE
);
1763 if (!MoneyRange(nCredit
))
1764 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1768 nAvailableCreditCached
= nCredit
;
1769 fAvailableCreditCached
= true;
1773 CAmount
CWalletTx::GetImmatureWatchOnlyCredit(const bool& fUseCache
) const
1775 if (IsCoinBase() && GetBlocksToMaturity() > 0 && IsInMainChain())
1777 if (fUseCache
&& fImmatureWatchCreditCached
)
1778 return nImmatureWatchCreditCached
;
1779 nImmatureWatchCreditCached
= pwallet
->GetCredit(*this, ISMINE_WATCH_ONLY
);
1780 fImmatureWatchCreditCached
= true;
1781 return nImmatureWatchCreditCached
;
1787 CAmount
CWalletTx::GetAvailableWatchOnlyCredit(const bool& fUseCache
) const
1792 // Must wait until coinbase is safely deep enough in the chain before valuing it
1793 if (IsCoinBase() && GetBlocksToMaturity() > 0)
1796 if (fUseCache
&& fAvailableWatchCreditCached
)
1797 return nAvailableWatchCreditCached
;
1799 CAmount nCredit
= 0;
1800 for (unsigned int i
= 0; i
< tx
->vout
.size(); i
++)
1802 if (!pwallet
->IsSpent(GetHash(), i
))
1804 const CTxOut
&txout
= tx
->vout
[i
];
1805 nCredit
+= pwallet
->GetCredit(txout
, ISMINE_WATCH_ONLY
);
1806 if (!MoneyRange(nCredit
))
1807 throw std::runtime_error("CWalletTx::GetAvailableCredit() : value out of range");
1811 nAvailableWatchCreditCached
= nCredit
;
1812 fAvailableWatchCreditCached
= true;
1816 CAmount
CWalletTx::GetChange() const
1819 return nChangeCached
;
1820 nChangeCached
= pwallet
->GetChange(*this);
1821 fChangeCached
= true;
1822 return nChangeCached
;
1825 bool CWalletTx::InMempool() const
1828 if (mempool
.exists(GetHash())) {
1834 bool CWalletTx::IsTrusted() const
1836 // Quick answer in most cases
1837 if (!CheckFinalTx(*this))
1839 int nDepth
= GetDepthInMainChain();
1844 if (!bSpendZeroConfChange
|| !IsFromMe(ISMINE_ALL
)) // using wtx's cached debit
1847 // Don't trust unconfirmed transactions from us unless they are in the mempool.
1851 // Trusted if all inputs are from us and are in the mempool:
1852 BOOST_FOREACH(const CTxIn
& txin
, tx
->vin
)
1854 // Transactions not sent by us: not trusted
1855 const CWalletTx
* parent
= pwallet
->GetWalletTx(txin
.prevout
.hash
);
1858 const CTxOut
& parentOut
= parent
->tx
->vout
[txin
.prevout
.n
];
1859 if (pwallet
->IsMine(parentOut
) != ISMINE_SPENDABLE
)
1865 bool CWalletTx::IsEquivalentTo(const CWalletTx
& _tx
) const
1867 CMutableTransaction tx1
= *this->tx
;
1868 CMutableTransaction tx2
= *_tx
.tx
;
1869 for (unsigned int i
= 0; i
< tx1
.vin
.size(); i
++) tx1
.vin
[i
].scriptSig
= CScript();
1870 for (unsigned int i
= 0; i
< tx2
.vin
.size(); i
++) tx2
.vin
[i
].scriptSig
= CScript();
1871 return CTransaction(tx1
) == CTransaction(tx2
);
1874 std::vector
<uint256
> CWallet::ResendWalletTransactionsBefore(int64_t nTime
, CConnman
* connman
)
1876 std::vector
<uint256
> result
;
1879 // Sort them in chronological order
1880 multimap
<unsigned int, CWalletTx
*> mapSorted
;
1881 BOOST_FOREACH(PAIRTYPE(const uint256
, CWalletTx
)& item
, mapWallet
)
1883 CWalletTx
& wtx
= item
.second
;
1884 // Don't rebroadcast if newer than nTime:
1885 if (wtx
.nTimeReceived
> nTime
)
1887 mapSorted
.insert(make_pair(wtx
.nTimeReceived
, &wtx
));
1889 BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx
*)& item
, mapSorted
)
1891 CWalletTx
& wtx
= *item
.second
;
1892 if (wtx
.RelayWalletTransaction(connman
))
1893 result
.push_back(wtx
.GetHash());
1898 void CWallet::ResendWalletTransactions(int64_t nBestBlockTime
, CConnman
* connman
)
1900 // Do this infrequently and randomly to avoid giving away
1901 // that these are our transactions.
1902 if (GetTime() < nNextResend
|| !fBroadcastTransactions
)
1904 bool fFirst
= (nNextResend
== 0);
1905 nNextResend
= GetTime() + GetRand(30 * 60);
1909 // Only do it if there's been a new block since last time
1910 if (nBestBlockTime
< nLastResend
)
1912 nLastResend
= GetTime();
1914 // Rebroadcast unconfirmed txes older than 5 minutes before the last
1916 std::vector
<uint256
> relayed
= ResendWalletTransactionsBefore(nBestBlockTime
-5*60, connman
);
1917 if (!relayed
.empty())
1918 LogPrintf("%s: rebroadcast %u unconfirmed transactions\n", __func__
, relayed
.size());
1921 /** @} */ // end of mapWallet
1926 /** @defgroup Actions
1932 CAmount
CWallet::GetBalance() const
1936 LOCK2(cs_main
, cs_wallet
);
1937 for (map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
1939 const CWalletTx
* pcoin
= &(*it
).second
;
1940 if (pcoin
->IsTrusted())
1941 nTotal
+= pcoin
->GetAvailableCredit();
1948 CAmount
CWallet::GetUnconfirmedBalance() const
1952 LOCK2(cs_main
, cs_wallet
);
1953 for (map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
1955 const CWalletTx
* pcoin
= &(*it
).second
;
1956 if (!pcoin
->IsTrusted() && pcoin
->GetDepthInMainChain() == 0 && pcoin
->InMempool())
1957 nTotal
+= pcoin
->GetAvailableCredit();
1963 CAmount
CWallet::GetImmatureBalance() const
1967 LOCK2(cs_main
, cs_wallet
);
1968 for (map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
1970 const CWalletTx
* pcoin
= &(*it
).second
;
1971 nTotal
+= pcoin
->GetImmatureCredit();
1977 CAmount
CWallet::GetWatchOnlyBalance() const
1981 LOCK2(cs_main
, cs_wallet
);
1982 for (map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
1984 const CWalletTx
* pcoin
= &(*it
).second
;
1985 if (pcoin
->IsTrusted())
1986 nTotal
+= pcoin
->GetAvailableWatchOnlyCredit();
1993 CAmount
CWallet::GetUnconfirmedWatchOnlyBalance() const
1997 LOCK2(cs_main
, cs_wallet
);
1998 for (map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
2000 const CWalletTx
* pcoin
= &(*it
).second
;
2001 if (!pcoin
->IsTrusted() && pcoin
->GetDepthInMainChain() == 0 && pcoin
->InMempool())
2002 nTotal
+= pcoin
->GetAvailableWatchOnlyCredit();
2008 CAmount
CWallet::GetImmatureWatchOnlyBalance() const
2012 LOCK2(cs_main
, cs_wallet
);
2013 for (map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
2015 const CWalletTx
* pcoin
= &(*it
).second
;
2016 nTotal
+= pcoin
->GetImmatureWatchOnlyCredit();
2022 void CWallet::AvailableCoins(vector
<COutput
>& vCoins
, bool fOnlyConfirmed
, const CCoinControl
*coinControl
, bool fIncludeZeroValue
) const
2027 LOCK2(cs_main
, cs_wallet
);
2028 for (map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
2030 const uint256
& wtxid
= it
->first
;
2031 const CWalletTx
* pcoin
= &(*it
).second
;
2033 if (!CheckFinalTx(*pcoin
))
2036 if (fOnlyConfirmed
&& !pcoin
->IsTrusted())
2039 if (pcoin
->IsCoinBase() && pcoin
->GetBlocksToMaturity() > 0)
2042 int nDepth
= pcoin
->GetDepthInMainChain();
2046 // We should not consider coins which aren't at least in our mempool
2047 // It's possible for these to be conflicted via ancestors which we may never be able to detect
2048 if (nDepth
== 0 && !pcoin
->InMempool())
2051 // We should not consider coins from transactions that are replacing
2052 // other transactions.
2054 // Example: There is a transaction A which is replaced by bumpfee
2055 // transaction B. In this case, we want to prevent creation of
2056 // a transaction B' which spends an output of B.
2058 // Reason: If transaction A were initially confirmed, transactions B
2059 // and B' would no longer be valid, so the user would have to create
2060 // a new transaction C to replace B'. However, in the case of a
2061 // one-block reorg, transactions B' and C might BOTH be accepted,
2062 // when the user only wanted one of them. Specifically, there could
2063 // be a 1-block reorg away from the chain where transactions A and C
2064 // were accepted to another chain where B, B', and C were all
2066 if (nDepth
== 0 && fOnlyConfirmed
&& pcoin
->mapValue
.count("replaces_txid")) {
2070 // Similarly, we should not consider coins from transactions that
2071 // have been replaced. In the example above, we would want to prevent
2072 // creation of a transaction A' spending an output of A, because if
2073 // transaction B were initially confirmed, conflicting with A and
2074 // A', we wouldn't want to the user to create a transaction D
2075 // intending to replace A', but potentially resulting in a scenario
2076 // where A, A', and D could all be accepted (instead of just B and
2077 // D, or just A and A' like the user would want).
2078 if (nDepth
== 0 && fOnlyConfirmed
&& pcoin
->mapValue
.count("replaced_by_txid")) {
2082 for (unsigned int i
= 0; i
< pcoin
->tx
->vout
.size(); i
++) {
2083 isminetype mine
= IsMine(pcoin
->tx
->vout
[i
]);
2084 if (!(IsSpent(wtxid
, i
)) && mine
!= ISMINE_NO
&&
2085 !IsLockedCoin((*it
).first
, i
) && (pcoin
->tx
->vout
[i
].nValue
> 0 || fIncludeZeroValue
) &&
2086 (!coinControl
|| !coinControl
->HasSelected() || coinControl
->fAllowOtherInputs
|| coinControl
->IsSelected(COutPoint((*it
).first
, i
))))
2087 vCoins
.push_back(COutput(pcoin
, i
, nDepth
,
2088 ((mine
& ISMINE_SPENDABLE
) != ISMINE_NO
) ||
2089 (coinControl
&& coinControl
->fAllowWatchOnly
&& (mine
& ISMINE_WATCH_SOLVABLE
) != ISMINE_NO
),
2090 (mine
& (ISMINE_SPENDABLE
| ISMINE_WATCH_SOLVABLE
)) != ISMINE_NO
));
2096 static void ApproximateBestSubset(vector
<pair
<CAmount
, pair
<const CWalletTx
*,unsigned int> > >vValue
, const CAmount
& nTotalLower
, const CAmount
& nTargetValue
,
2097 vector
<char>& vfBest
, CAmount
& nBest
, int iterations
= 1000)
2099 vector
<char> vfIncluded
;
2101 vfBest
.assign(vValue
.size(), true);
2102 nBest
= nTotalLower
;
2104 FastRandomContext insecure_rand
;
2106 for (int nRep
= 0; nRep
< iterations
&& nBest
!= nTargetValue
; nRep
++)
2108 vfIncluded
.assign(vValue
.size(), false);
2110 bool fReachedTarget
= false;
2111 for (int nPass
= 0; nPass
< 2 && !fReachedTarget
; nPass
++)
2113 for (unsigned int i
= 0; i
< vValue
.size(); i
++)
2115 //The solver here uses a randomized algorithm,
2116 //the randomness serves no real security purpose but is just
2117 //needed to prevent degenerate behavior and it is important
2118 //that the rng is fast. We do not use a constant random sequence,
2119 //because there may be some privacy improvement by making
2120 //the selection random.
2121 if (nPass
== 0 ? insecure_rand
.rand32()&1 : !vfIncluded
[i
])
2123 nTotal
+= vValue
[i
].first
;
2124 vfIncluded
[i
] = true;
2125 if (nTotal
>= nTargetValue
)
2127 fReachedTarget
= true;
2131 vfBest
= vfIncluded
;
2133 nTotal
-= vValue
[i
].first
;
2134 vfIncluded
[i
] = false;
2142 bool CWallet::SelectCoinsMinConf(const CAmount
& nTargetValue
, const int nConfMine
, const int nConfTheirs
, const uint64_t nMaxAncestors
, vector
<COutput
> vCoins
,
2143 set
<pair
<const CWalletTx
*,unsigned int> >& setCoinsRet
, CAmount
& nValueRet
) const
2145 setCoinsRet
.clear();
2148 // List of values less than target
2149 pair
<CAmount
, pair
<const CWalletTx
*,unsigned int> > coinLowestLarger
;
2150 coinLowestLarger
.first
= std::numeric_limits
<CAmount
>::max();
2151 coinLowestLarger
.second
.first
= NULL
;
2152 vector
<pair
<CAmount
, pair
<const CWalletTx
*,unsigned int> > > vValue
;
2153 CAmount nTotalLower
= 0;
2155 random_shuffle(vCoins
.begin(), vCoins
.end(), GetRandInt
);
2157 BOOST_FOREACH(const COutput
&output
, vCoins
)
2159 if (!output
.fSpendable
)
2162 const CWalletTx
*pcoin
= output
.tx
;
2164 if (output
.nDepth
< (pcoin
->IsFromMe(ISMINE_ALL
) ? nConfMine
: nConfTheirs
))
2167 if (!mempool
.TransactionWithinChainLimit(pcoin
->GetHash(), nMaxAncestors
))
2171 CAmount n
= pcoin
->tx
->vout
[i
].nValue
;
2173 pair
<CAmount
,pair
<const CWalletTx
*,unsigned int> > coin
= make_pair(n
,make_pair(pcoin
, i
));
2175 if (n
== nTargetValue
)
2177 setCoinsRet
.insert(coin
.second
);
2178 nValueRet
+= coin
.first
;
2181 else if (n
< nTargetValue
+ MIN_CHANGE
)
2183 vValue
.push_back(coin
);
2186 else if (n
< coinLowestLarger
.first
)
2188 coinLowestLarger
= coin
;
2192 if (nTotalLower
== nTargetValue
)
2194 for (unsigned int i
= 0; i
< vValue
.size(); ++i
)
2196 setCoinsRet
.insert(vValue
[i
].second
);
2197 nValueRet
+= vValue
[i
].first
;
2202 if (nTotalLower
< nTargetValue
)
2204 if (coinLowestLarger
.second
.first
== NULL
)
2206 setCoinsRet
.insert(coinLowestLarger
.second
);
2207 nValueRet
+= coinLowestLarger
.first
;
2211 // Solve subset sum by stochastic approximation
2212 std::sort(vValue
.begin(), vValue
.end(), CompareValueOnly());
2213 std::reverse(vValue
.begin(), vValue
.end());
2214 vector
<char> vfBest
;
2217 ApproximateBestSubset(vValue
, nTotalLower
, nTargetValue
, vfBest
, nBest
);
2218 if (nBest
!= nTargetValue
&& nTotalLower
>= nTargetValue
+ MIN_CHANGE
)
2219 ApproximateBestSubset(vValue
, nTotalLower
, nTargetValue
+ MIN_CHANGE
, vfBest
, nBest
);
2221 // If we have a bigger coin and (either the stochastic approximation didn't find a good solution,
2222 // or the next bigger coin is closer), return the bigger coin
2223 if (coinLowestLarger
.second
.first
&&
2224 ((nBest
!= nTargetValue
&& nBest
< nTargetValue
+ MIN_CHANGE
) || coinLowestLarger
.first
<= nBest
))
2226 setCoinsRet
.insert(coinLowestLarger
.second
);
2227 nValueRet
+= coinLowestLarger
.first
;
2230 for (unsigned int i
= 0; i
< vValue
.size(); i
++)
2233 setCoinsRet
.insert(vValue
[i
].second
);
2234 nValueRet
+= vValue
[i
].first
;
2237 LogPrint("selectcoins", "SelectCoins() best subset: ");
2238 for (unsigned int i
= 0; i
< vValue
.size(); i
++)
2240 LogPrint("selectcoins", "%s ", FormatMoney(vValue
[i
].first
));
2241 LogPrint("selectcoins", "total %s\n", FormatMoney(nBest
));
2247 bool CWallet::SelectCoins(const vector
<COutput
>& vAvailableCoins
, const CAmount
& nTargetValue
, set
<pair
<const CWalletTx
*,unsigned int> >& setCoinsRet
, CAmount
& nValueRet
, const CCoinControl
* coinControl
) const
2249 vector
<COutput
> vCoins(vAvailableCoins
);
2251 // coin control -> return all selected outputs (we want all selected to go into the transaction for sure)
2252 if (coinControl
&& coinControl
->HasSelected() && !coinControl
->fAllowOtherInputs
)
2254 BOOST_FOREACH(const COutput
& out
, vCoins
)
2256 if (!out
.fSpendable
)
2258 nValueRet
+= out
.tx
->tx
->vout
[out
.i
].nValue
;
2259 setCoinsRet
.insert(make_pair(out
.tx
, out
.i
));
2261 return (nValueRet
>= nTargetValue
);
2264 // calculate value from preset inputs and store them
2265 set
<pair
<const CWalletTx
*, uint32_t> > setPresetCoins
;
2266 CAmount nValueFromPresetInputs
= 0;
2268 std::vector
<COutPoint
> vPresetInputs
;
2270 coinControl
->ListSelected(vPresetInputs
);
2271 BOOST_FOREACH(const COutPoint
& outpoint
, vPresetInputs
)
2273 map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.find(outpoint
.hash
);
2274 if (it
!= mapWallet
.end())
2276 const CWalletTx
* pcoin
= &it
->second
;
2277 // Clearly invalid input, fail
2278 if (pcoin
->tx
->vout
.size() <= outpoint
.n
)
2280 nValueFromPresetInputs
+= pcoin
->tx
->vout
[outpoint
.n
].nValue
;
2281 setPresetCoins
.insert(make_pair(pcoin
, outpoint
.n
));
2283 return false; // TODO: Allow non-wallet inputs
2286 // remove preset inputs from vCoins
2287 for (vector
<COutput
>::iterator it
= vCoins
.begin(); it
!= vCoins
.end() && coinControl
&& coinControl
->HasSelected();)
2289 if (setPresetCoins
.count(make_pair(it
->tx
, it
->i
)))
2290 it
= vCoins
.erase(it
);
2295 size_t nMaxChainLength
= std::min(GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT
), GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT
));
2296 bool fRejectLongChains
= GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS
);
2298 bool res
= nTargetValue
<= nValueFromPresetInputs
||
2299 SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 1, 6, 0, vCoins
, setCoinsRet
, nValueRet
) ||
2300 SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 1, 1, 0, vCoins
, setCoinsRet
, nValueRet
) ||
2301 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, 2, vCoins
, setCoinsRet
, nValueRet
)) ||
2302 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, std::min((size_t)4, nMaxChainLength
/3), vCoins
, setCoinsRet
, nValueRet
)) ||
2303 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, nMaxChainLength
/2, vCoins
, setCoinsRet
, nValueRet
)) ||
2304 (bSpendZeroConfChange
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, nMaxChainLength
, vCoins
, setCoinsRet
, nValueRet
)) ||
2305 (bSpendZeroConfChange
&& !fRejectLongChains
&& SelectCoinsMinConf(nTargetValue
- nValueFromPresetInputs
, 0, 1, std::numeric_limits
<uint64_t>::max(), vCoins
, setCoinsRet
, nValueRet
));
2307 // because SelectCoinsMinConf clears the setCoinsRet, we now add the possible inputs to the coinset
2308 setCoinsRet
.insert(setPresetCoins
.begin(), setPresetCoins
.end());
2310 // add preset inputs to the total value selected
2311 nValueRet
+= nValueFromPresetInputs
;
2316 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
)
2318 vector
<CRecipient
> vecSend
;
2320 // Turn the txout set into a CRecipient vector
2321 for (size_t idx
= 0; idx
< tx
.vout
.size(); idx
++)
2323 const CTxOut
& txOut
= tx
.vout
[idx
];
2324 CRecipient recipient
= {txOut
.scriptPubKey
, txOut
.nValue
, setSubtractFeeFromOutputs
.count(idx
) == 1};
2325 vecSend
.push_back(recipient
);
2328 CCoinControl coinControl
;
2329 coinControl
.destChange
= destChange
;
2330 coinControl
.fAllowOtherInputs
= true;
2331 coinControl
.fAllowWatchOnly
= includeWatching
;
2332 coinControl
.fOverrideFeeRate
= overrideEstimatedFeeRate
;
2333 coinControl
.nFeeRate
= specificFeeRate
;
2335 BOOST_FOREACH(const CTxIn
& txin
, tx
.vin
)
2336 coinControl
.Select(txin
.prevout
);
2338 CReserveKey
reservekey(this);
2340 if (!CreateTransaction(vecSend
, wtx
, reservekey
, nFeeRet
, nChangePosInOut
, strFailReason
, &coinControl
, false))
2343 if (nChangePosInOut
!= -1)
2344 tx
.vout
.insert(tx
.vout
.begin() + nChangePosInOut
, wtx
.tx
->vout
[nChangePosInOut
]);
2346 // Copy output sizes from new transaction; they may have had the fee subtracted from them
2347 for (unsigned int idx
= 0; idx
< tx
.vout
.size(); idx
++)
2348 tx
.vout
[idx
].nValue
= wtx
.tx
->vout
[idx
].nValue
;
2350 // Add new txins (keeping original txin scriptSig/order)
2351 BOOST_FOREACH(const CTxIn
& txin
, wtx
.tx
->vin
)
2353 if (!coinControl
.IsSelected(txin
.prevout
))
2355 tx
.vin
.push_back(txin
);
2359 LOCK2(cs_main
, cs_wallet
);
2360 LockCoin(txin
.prevout
);
2365 // optionally keep the change output key
2367 reservekey
.KeepKey();
2372 bool CWallet::CreateTransaction(const vector
<CRecipient
>& vecSend
, CWalletTx
& wtxNew
, CReserveKey
& reservekey
, CAmount
& nFeeRet
,
2373 int& nChangePosInOut
, std::string
& strFailReason
, const CCoinControl
* coinControl
, bool sign
)
2376 int nChangePosRequest
= nChangePosInOut
;
2377 unsigned int nSubtractFeeFromAmount
= 0;
2378 for (const auto& recipient
: vecSend
)
2380 if (nValue
< 0 || recipient
.nAmount
< 0)
2382 strFailReason
= _("Transaction amounts must not be negative");
2385 nValue
+= recipient
.nAmount
;
2387 if (recipient
.fSubtractFeeFromAmount
)
2388 nSubtractFeeFromAmount
++;
2390 if (vecSend
.empty())
2392 strFailReason
= _("Transaction must have at least one recipient");
2396 wtxNew
.fTimeReceivedIsTxTime
= true;
2397 wtxNew
.BindWallet(this);
2398 CMutableTransaction txNew
;
2400 // Discourage fee sniping.
2402 // For a large miner the value of the transactions in the best block and
2403 // the mempool can exceed the cost of deliberately attempting to mine two
2404 // blocks to orphan the current best block. By setting nLockTime such that
2405 // only the next block can include the transaction, we discourage this
2406 // practice as the height restricted and limited blocksize gives miners
2407 // considering fee sniping fewer options for pulling off this attack.
2409 // A simple way to think about this is from the wallet's point of view we
2410 // always want the blockchain to move forward. By setting nLockTime this
2411 // way we're basically making the statement that we only want this
2412 // transaction to appear in the next block; we don't want to potentially
2413 // encourage reorgs by allowing transactions to appear at lower heights
2414 // than the next block in forks of the best chain.
2416 // Of course, the subsidy is high enough, and transaction volume low
2417 // enough, that fee sniping isn't a problem yet, but by implementing a fix
2418 // now we ensure code won't be written that makes assumptions about
2419 // nLockTime that preclude a fix later.
2420 txNew
.nLockTime
= chainActive
.Height();
2422 // Secondly occasionally randomly pick a nLockTime even further back, so
2423 // that transactions that are delayed after signing for whatever reason,
2424 // e.g. high-latency mix networks and some CoinJoin implementations, have
2426 if (GetRandInt(10) == 0)
2427 txNew
.nLockTime
= std::max(0, (int)txNew
.nLockTime
- GetRandInt(100));
2429 assert(txNew
.nLockTime
<= (unsigned int)chainActive
.Height());
2430 assert(txNew
.nLockTime
< LOCKTIME_THRESHOLD
);
2433 set
<pair
<const CWalletTx
*,unsigned int> > setCoins
;
2434 LOCK2(cs_main
, cs_wallet
);
2436 std::vector
<COutput
> vAvailableCoins
;
2437 AvailableCoins(vAvailableCoins
, true, coinControl
);
2440 // Start with no fee and loop until there is enough fee
2443 nChangePosInOut
= nChangePosRequest
;
2446 wtxNew
.fFromMe
= true;
2449 CAmount nValueToSelect
= nValue
;
2450 if (nSubtractFeeFromAmount
== 0)
2451 nValueToSelect
+= nFeeRet
;
2452 double dPriority
= 0;
2453 // vouts to the payees
2454 for (const auto& recipient
: vecSend
)
2456 CTxOut
txout(recipient
.nAmount
, recipient
.scriptPubKey
);
2458 if (recipient
.fSubtractFeeFromAmount
)
2460 txout
.nValue
-= nFeeRet
/ nSubtractFeeFromAmount
; // Subtract fee equally from each selected recipient
2462 if (fFirst
) // first receiver pays the remainder not divisible by output count
2465 txout
.nValue
-= nFeeRet
% nSubtractFeeFromAmount
;
2469 if (txout
.IsDust(dustRelayFee
))
2471 if (recipient
.fSubtractFeeFromAmount
&& nFeeRet
> 0)
2473 if (txout
.nValue
< 0)
2474 strFailReason
= _("The transaction amount is too small to pay the fee");
2476 strFailReason
= _("The transaction amount is too small to send after the fee has been deducted");
2479 strFailReason
= _("Transaction amount too small");
2482 txNew
.vout
.push_back(txout
);
2485 // Choose coins to use
2486 CAmount nValueIn
= 0;
2488 if (!SelectCoins(vAvailableCoins
, nValueToSelect
, setCoins
, nValueIn
, coinControl
))
2490 strFailReason
= _("Insufficient funds");
2493 for (const auto& pcoin
: setCoins
)
2495 CAmount nCredit
= pcoin
.first
->tx
->vout
[pcoin
.second
].nValue
;
2496 //The coin age after the next block (depth+1) is used instead of the current,
2497 //reflecting an assumption the user would accept a bit more delay for
2498 //a chance at a free transaction.
2499 //But mempool inputs might still be in the mempool, so their age stays 0
2500 int age
= pcoin
.first
->GetDepthInMainChain();
2504 dPriority
+= (double)nCredit
* age
;
2507 const CAmount nChange
= nValueIn
- nValueToSelect
;
2510 // Fill a vout to ourself
2511 // TODO: pass in scriptChange instead of reservekey so
2512 // change transaction isn't always pay-to-bitcoin-address
2513 CScript scriptChange
;
2515 // coin control: send change to custom address
2516 if (coinControl
&& !boost::get
<CNoDestination
>(&coinControl
->destChange
))
2517 scriptChange
= GetScriptForDestination(coinControl
->destChange
);
2519 // no coin control: send change to newly generated address
2522 // Note: We use a new key here to keep it from being obvious which side is the change.
2523 // The drawback is that by not reusing a previous key, the change may be lost if a
2524 // backup is restored, if the backup doesn't have the new private key for the change.
2525 // If we reused the old key, it would be possible to add code to look for and
2526 // rediscover unknown transactions that were written with keys of ours to recover
2527 // post-backup change.
2529 // Reserve a new key pair from key pool
2532 ret
= reservekey
.GetReservedKey(vchPubKey
);
2535 strFailReason
= _("Keypool ran out, please call keypoolrefill first");
2539 scriptChange
= GetScriptForDestination(vchPubKey
.GetID());
2542 CTxOut
newTxOut(nChange
, scriptChange
);
2544 // We do not move dust-change to fees, because the sender would end up paying more than requested.
2545 // This would be against the purpose of the all-inclusive feature.
2546 // So instead we raise the change and deduct from the recipient.
2547 if (nSubtractFeeFromAmount
> 0 && newTxOut
.IsDust(dustRelayFee
))
2549 CAmount nDust
= newTxOut
.GetDustThreshold(dustRelayFee
) - newTxOut
.nValue
;
2550 newTxOut
.nValue
+= nDust
; // raise change until no more dust
2551 for (unsigned int i
= 0; i
< vecSend
.size(); i
++) // subtract from first recipient
2553 if (vecSend
[i
].fSubtractFeeFromAmount
)
2555 txNew
.vout
[i
].nValue
-= nDust
;
2556 if (txNew
.vout
[i
].IsDust(dustRelayFee
))
2558 strFailReason
= _("The transaction amount is too small to send after the fee has been deducted");
2566 // Never create dust outputs; if we would, just
2567 // add the dust to the fee.
2568 if (newTxOut
.IsDust(dustRelayFee
))
2570 nChangePosInOut
= -1;
2572 reservekey
.ReturnKey();
2576 if (nChangePosInOut
== -1)
2578 // Insert change txn at random position:
2579 nChangePosInOut
= GetRandInt(txNew
.vout
.size()+1);
2581 else if ((unsigned int)nChangePosInOut
> txNew
.vout
.size())
2583 strFailReason
= _("Change index out of range");
2587 vector
<CTxOut
>::iterator position
= txNew
.vout
.begin()+nChangePosInOut
;
2588 txNew
.vout
.insert(position
, newTxOut
);
2592 reservekey
.ReturnKey();
2596 // Note how the sequence number is set to non-maxint so that
2597 // the nLockTime set above actually works.
2599 // BIP125 defines opt-in RBF as any nSequence < maxint-1, so
2600 // we use the highest possible value in that range (maxint-2)
2601 // to avoid conflicting with other possible uses of nSequence,
2602 // and in the spirit of "smallest possible change from prior
2604 for (const auto& coin
: setCoins
)
2605 txNew
.vin
.push_back(CTxIn(coin
.first
->GetHash(),coin
.second
,CScript(),
2606 std::numeric_limits
<unsigned int>::max() - (fWalletRbf
? 2 : 1)));
2608 // Fill in dummy signatures for fee calculation.
2609 if (!DummySignTx(txNew
, setCoins
)) {
2610 strFailReason
= _("Signing transaction failed");
2614 unsigned int nBytes
= GetVirtualTransactionSize(txNew
);
2616 CTransaction
txNewConst(txNew
);
2617 dPriority
= txNewConst
.ComputePriority(dPriority
, nBytes
);
2619 // Remove scriptSigs to eliminate the fee calculation dummy signatures
2620 for (auto& vin
: txNew
.vin
) {
2621 vin
.scriptSig
= CScript();
2622 vin
.scriptWitness
.SetNull();
2625 // Allow to override the default confirmation target over the CoinControl instance
2626 int currentConfirmationTarget
= nTxConfirmTarget
;
2627 if (coinControl
&& coinControl
->nConfirmTarget
> 0)
2628 currentConfirmationTarget
= coinControl
->nConfirmTarget
;
2630 // Can we complete this as a free transaction?
2631 if (fSendFreeTransactions
&& nBytes
<= MAX_FREE_TRANSACTION_CREATE_SIZE
)
2633 // Not enough fee: enough priority?
2634 double dPriorityNeeded
= mempool
.estimateSmartPriority(currentConfirmationTarget
);
2635 // Require at least hard-coded AllowFree.
2636 if (dPriority
>= dPriorityNeeded
&& AllowFree(dPriority
))
2640 CAmount nFeeNeeded
= GetMinimumFee(nBytes
, currentConfirmationTarget
, mempool
);
2641 if (coinControl
&& nFeeNeeded
> 0 && coinControl
->nMinimumTotalFee
> nFeeNeeded
) {
2642 nFeeNeeded
= coinControl
->nMinimumTotalFee
;
2644 if (coinControl
&& coinControl
->fOverrideFeeRate
)
2645 nFeeNeeded
= coinControl
->nFeeRate
.GetFee(nBytes
);
2647 // If we made it here and we aren't even able to meet the relay fee on the next pass, give up
2648 // because we must be at the maximum allowed fee.
2649 if (nFeeNeeded
< ::minRelayTxFee
.GetFee(nBytes
))
2651 strFailReason
= _("Transaction too large for fee policy");
2655 if (nFeeRet
>= nFeeNeeded
) {
2656 // Reduce fee to only the needed amount if we have change
2657 // output to increase. This prevents potential overpayment
2658 // in fees if the coins selected to meet nFeeNeeded result
2659 // in a transaction that requires less fee than the prior
2661 // TODO: The case where nSubtractFeeFromAmount > 0 remains
2662 // to be addressed because it requires returning the fee to
2663 // the payees and not the change output.
2664 // TODO: The case where there is no change output remains
2665 // to be addressed so we avoid creating too small an output.
2666 if (nFeeRet
> nFeeNeeded
&& nChangePosInOut
!= -1 && nSubtractFeeFromAmount
== 0) {
2667 CAmount extraFeePaid
= nFeeRet
- nFeeNeeded
;
2668 vector
<CTxOut
>::iterator change_position
= txNew
.vout
.begin()+nChangePosInOut
;
2669 change_position
->nValue
+= extraFeePaid
;
2670 nFeeRet
-= extraFeePaid
;
2672 break; // Done, enough fee included.
2675 // Try to reduce change to include necessary fee
2676 if (nChangePosInOut
!= -1 && nSubtractFeeFromAmount
== 0) {
2677 CAmount additionalFeeNeeded
= nFeeNeeded
- nFeeRet
;
2678 vector
<CTxOut
>::iterator change_position
= txNew
.vout
.begin()+nChangePosInOut
;
2679 // Only reduce change if remaining amount is still a large enough output.
2680 if (change_position
->nValue
>= MIN_FINAL_CHANGE
+ additionalFeeNeeded
) {
2681 change_position
->nValue
-= additionalFeeNeeded
;
2682 nFeeRet
+= additionalFeeNeeded
;
2683 break; // Done, able to increase fee from change
2687 // Include more fee and try again.
2688 nFeeRet
= nFeeNeeded
;
2695 CTransaction
txNewConst(txNew
);
2697 for (const auto& coin
: setCoins
)
2699 const CScript
& scriptPubKey
= coin
.first
->tx
->vout
[coin
.second
].scriptPubKey
;
2700 SignatureData sigdata
;
2702 if (!ProduceSignature(TransactionSignatureCreator(this, &txNewConst
, nIn
, coin
.first
->tx
->vout
[coin
.second
].nValue
, SIGHASH_ALL
), scriptPubKey
, sigdata
))
2704 strFailReason
= _("Signing transaction failed");
2707 UpdateTransaction(txNew
, nIn
, sigdata
);
2714 // Embed the constructed transaction data in wtxNew.
2715 wtxNew
.SetTx(MakeTransactionRef(std::move(txNew
)));
2718 if (GetTransactionWeight(wtxNew
) >= MAX_STANDARD_TX_WEIGHT
)
2720 strFailReason
= _("Transaction too large");
2725 if (GetBoolArg("-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS
)) {
2726 // Lastly, ensure this tx will pass the mempool's chain limits
2728 CTxMemPoolEntry
entry(wtxNew
.tx
, 0, 0, 0, 0, 0, false, 0, lp
);
2729 CTxMemPool::setEntries setAncestors
;
2730 size_t nLimitAncestors
= GetArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT
);
2731 size_t nLimitAncestorSize
= GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT
)*1000;
2732 size_t nLimitDescendants
= GetArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT
);
2733 size_t nLimitDescendantSize
= GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT
)*1000;
2734 std::string errString
;
2735 if (!mempool
.CalculateMemPoolAncestors(entry
, setAncestors
, nLimitAncestors
, nLimitAncestorSize
, nLimitDescendants
, nLimitDescendantSize
, errString
)) {
2736 strFailReason
= _("Transaction has too long of a mempool chain");
2744 * Call after CreateTransaction unless you want to abort
2746 bool CWallet::CommitTransaction(CWalletTx
& wtxNew
, CReserveKey
& reservekey
, CConnman
* connman
, CValidationState
& state
)
2749 LOCK2(cs_main
, cs_wallet
);
2750 LogPrintf("CommitTransaction:\n%s", wtxNew
.tx
->ToString());
2752 // Take key pair from key pool so it won't be used again
2753 reservekey
.KeepKey();
2755 // Add tx to wallet, because if it has change it's also ours,
2756 // otherwise just for transaction history.
2757 AddToWallet(wtxNew
);
2759 // Notify that old coins are spent
2760 BOOST_FOREACH(const CTxIn
& txin
, wtxNew
.tx
->vin
)
2762 CWalletTx
&coin
= mapWallet
[txin
.prevout
.hash
];
2763 coin
.BindWallet(this);
2764 NotifyTransactionChanged(this, coin
.GetHash(), CT_UPDATED
);
2768 // Track how many getdata requests our transaction gets
2769 mapRequestCount
[wtxNew
.GetHash()] = 0;
2771 if (fBroadcastTransactions
)
2774 if (!wtxNew
.AcceptToMemoryPool(maxTxFee
, state
)) {
2775 LogPrintf("CommitTransaction(): Transaction cannot be broadcast immediately, %s\n", state
.GetRejectReason());
2776 // TODO: if we expect the failure to be long term or permanent, instead delete wtx from the wallet and return failure.
2778 wtxNew
.RelayWalletTransaction(connman
);
2785 void CWallet::ListAccountCreditDebit(const std::string
& strAccount
, std::list
<CAccountingEntry
>& entries
) {
2786 CWalletDB
walletdb(strWalletFile
);
2787 return walletdb
.ListAccountCreditDebit(strAccount
, entries
);
2790 bool CWallet::AddAccountingEntry(const CAccountingEntry
& acentry
)
2792 CWalletDB
walletdb(strWalletFile
);
2794 return AddAccountingEntry(acentry
, &walletdb
);
2797 bool CWallet::AddAccountingEntry(const CAccountingEntry
& acentry
, CWalletDB
*pwalletdb
)
2799 if (!pwalletdb
->WriteAccountingEntry_Backend(acentry
))
2802 laccentries
.push_back(acentry
);
2803 CAccountingEntry
& entry
= laccentries
.back();
2804 wtxOrdered
.insert(make_pair(entry
.nOrderPos
, TxPair((CWalletTx
*)0, &entry
)));
2809 CAmount
CWallet::GetRequiredFee(unsigned int nTxBytes
)
2811 return std::max(minTxFee
.GetFee(nTxBytes
), ::minRelayTxFee
.GetFee(nTxBytes
));
2814 CAmount
CWallet::GetMinimumFee(unsigned int nTxBytes
, unsigned int nConfirmTarget
, const CTxMemPool
& pool
)
2816 // payTxFee is the user-set global for desired feerate
2817 return GetMinimumFee(nTxBytes
, nConfirmTarget
, pool
, payTxFee
.GetFee(nTxBytes
));
2820 CAmount
CWallet::GetMinimumFee(unsigned int nTxBytes
, unsigned int nConfirmTarget
, const CTxMemPool
& pool
, CAmount targetFee
)
2822 CAmount nFeeNeeded
= targetFee
;
2823 // User didn't set: use -txconfirmtarget to estimate...
2824 if (nFeeNeeded
== 0) {
2825 int estimateFoundTarget
= nConfirmTarget
;
2826 nFeeNeeded
= pool
.estimateSmartFee(nConfirmTarget
, &estimateFoundTarget
).GetFee(nTxBytes
);
2827 // ... unless we don't have enough mempool data for estimatefee, then use fallbackFee
2828 if (nFeeNeeded
== 0)
2829 nFeeNeeded
= fallbackFee
.GetFee(nTxBytes
);
2831 // prevent user from paying a fee below minRelayTxFee or minTxFee
2832 nFeeNeeded
= std::max(nFeeNeeded
, GetRequiredFee(nTxBytes
));
2833 // But always obey the maximum
2834 if (nFeeNeeded
> maxTxFee
)
2835 nFeeNeeded
= maxTxFee
;
2842 DBErrors
CWallet::LoadWallet(bool& fFirstRunRet
)
2846 fFirstRunRet
= false;
2847 DBErrors nLoadWalletRet
= CWalletDB(strWalletFile
,"cr+").LoadWallet(this);
2848 if (nLoadWalletRet
== DB_NEED_REWRITE
)
2850 if (CDB::Rewrite(strWalletFile
, "\x04pool"))
2854 // Note: can't top-up keypool here, because wallet is locked.
2855 // User will be prompted to unlock wallet the next operation
2856 // that requires a new key.
2860 if (nLoadWalletRet
!= DB_LOAD_OK
)
2861 return nLoadWalletRet
;
2862 fFirstRunRet
= !vchDefaultKey
.IsValid();
2864 uiInterface
.LoadWallet(this);
2869 DBErrors
CWallet::ZapSelectTx(vector
<uint256
>& vHashIn
, vector
<uint256
>& vHashOut
)
2873 AssertLockHeld(cs_wallet
); // mapWallet
2874 vchDefaultKey
= CPubKey();
2875 DBErrors nZapSelectTxRet
= CWalletDB(strWalletFile
,"cr+").ZapSelectTx(vHashIn
, vHashOut
);
2876 for (uint256 hash
: vHashOut
)
2877 mapWallet
.erase(hash
);
2879 if (nZapSelectTxRet
== DB_NEED_REWRITE
)
2881 if (CDB::Rewrite(strWalletFile
, "\x04pool"))
2884 // Note: can't top-up keypool here, because wallet is locked.
2885 // User will be prompted to unlock wallet the next operation
2886 // that requires a new key.
2890 if (nZapSelectTxRet
!= DB_LOAD_OK
)
2891 return nZapSelectTxRet
;
2899 DBErrors
CWallet::ZapWalletTx(std::vector
<CWalletTx
>& vWtx
)
2903 vchDefaultKey
= CPubKey();
2904 DBErrors nZapWalletTxRet
= CWalletDB(strWalletFile
,"cr+").ZapWalletTx(vWtx
);
2905 if (nZapWalletTxRet
== DB_NEED_REWRITE
)
2907 if (CDB::Rewrite(strWalletFile
, "\x04pool"))
2911 // Note: can't top-up keypool here, because wallet is locked.
2912 // User will be prompted to unlock wallet the next operation
2913 // that requires a new key.
2917 if (nZapWalletTxRet
!= DB_LOAD_OK
)
2918 return nZapWalletTxRet
;
2924 bool CWallet::SetAddressBook(const CTxDestination
& address
, const string
& strName
, const string
& strPurpose
)
2926 bool fUpdated
= false;
2928 LOCK(cs_wallet
); // mapAddressBook
2929 std::map
<CTxDestination
, CAddressBookData
>::iterator mi
= mapAddressBook
.find(address
);
2930 fUpdated
= mi
!= mapAddressBook
.end();
2931 mapAddressBook
[address
].name
= strName
;
2932 if (!strPurpose
.empty()) /* update purpose only if requested */
2933 mapAddressBook
[address
].purpose
= strPurpose
;
2935 NotifyAddressBookChanged(this, address
, strName
, ::IsMine(*this, address
) != ISMINE_NO
,
2936 strPurpose
, (fUpdated
? CT_UPDATED
: CT_NEW
) );
2939 if (!strPurpose
.empty() && !CWalletDB(strWalletFile
).WritePurpose(CBitcoinAddress(address
).ToString(), strPurpose
))
2941 return CWalletDB(strWalletFile
).WriteName(CBitcoinAddress(address
).ToString(), strName
);
2944 bool CWallet::DelAddressBook(const CTxDestination
& address
)
2947 LOCK(cs_wallet
); // mapAddressBook
2951 // Delete destdata tuples associated with address
2952 std::string strAddress
= CBitcoinAddress(address
).ToString();
2953 BOOST_FOREACH(const PAIRTYPE(string
, string
) &item
, mapAddressBook
[address
].destdata
)
2955 CWalletDB(strWalletFile
).EraseDestData(strAddress
, item
.first
);
2958 mapAddressBook
.erase(address
);
2961 NotifyAddressBookChanged(this, address
, "", ::IsMine(*this, address
) != ISMINE_NO
, "", CT_DELETED
);
2965 CWalletDB(strWalletFile
).ErasePurpose(CBitcoinAddress(address
).ToString());
2966 return CWalletDB(strWalletFile
).EraseName(CBitcoinAddress(address
).ToString());
2969 bool CWallet::SetDefaultKey(const CPubKey
&vchPubKey
)
2973 if (!CWalletDB(strWalletFile
).WriteDefaultKey(vchPubKey
))
2976 vchDefaultKey
= vchPubKey
;
2981 * Mark old keypool keys as used,
2982 * and generate all new keys
2984 bool CWallet::NewKeyPool()
2988 CWalletDB
walletdb(strWalletFile
);
2989 BOOST_FOREACH(int64_t nIndex
, setKeyPool
)
2990 walletdb
.ErasePool(nIndex
);
2996 int64_t nKeys
= max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE
), (int64_t)0);
2997 for (int i
= 0; i
< nKeys
; i
++)
2999 int64_t nIndex
= i
+1;
3000 walletdb
.WritePool(nIndex
, CKeyPool(GenerateNewKey()));
3001 setKeyPool
.insert(nIndex
);
3003 LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys
);
3008 bool CWallet::TopUpKeyPool(unsigned int kpSize
)
3016 CWalletDB
walletdb(strWalletFile
);
3019 unsigned int nTargetSize
;
3021 nTargetSize
= kpSize
;
3023 nTargetSize
= max(GetArg("-keypool", DEFAULT_KEYPOOL_SIZE
), (int64_t) 0);
3025 while (setKeyPool
.size() < (nTargetSize
+ 1))
3028 if (!setKeyPool
.empty())
3029 nEnd
= *(--setKeyPool
.end()) + 1;
3030 if (!walletdb
.WritePool(nEnd
, CKeyPool(GenerateNewKey())))
3031 throw runtime_error(std::string(__func__
) + ": writing generated key failed");
3032 setKeyPool
.insert(nEnd
);
3033 LogPrintf("keypool added key %d, size=%u\n", nEnd
, setKeyPool
.size());
3039 void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex
, CKeyPool
& keypool
)
3042 keypool
.vchPubKey
= CPubKey();
3049 // Get the oldest key
3050 if(setKeyPool
.empty())
3053 CWalletDB
walletdb(strWalletFile
);
3055 nIndex
= *(setKeyPool
.begin());
3056 setKeyPool
.erase(setKeyPool
.begin());
3057 if (!walletdb
.ReadPool(nIndex
, keypool
))
3058 throw runtime_error(std::string(__func__
) + ": read failed");
3059 if (!HaveKey(keypool
.vchPubKey
.GetID()))
3060 throw runtime_error(std::string(__func__
) + ": unknown key in key pool");
3061 assert(keypool
.vchPubKey
.IsValid());
3062 LogPrintf("keypool reserve %d\n", nIndex
);
3066 void CWallet::KeepKey(int64_t nIndex
)
3068 // Remove from key pool
3071 CWalletDB
walletdb(strWalletFile
);
3072 walletdb
.ErasePool(nIndex
);
3074 LogPrintf("keypool keep %d\n", nIndex
);
3077 void CWallet::ReturnKey(int64_t nIndex
)
3079 // Return to key pool
3082 setKeyPool
.insert(nIndex
);
3084 LogPrintf("keypool return %d\n", nIndex
);
3087 bool CWallet::GetKeyFromPool(CPubKey
& result
)
3093 ReserveKeyFromKeyPool(nIndex
, keypool
);
3096 if (IsLocked()) return false;
3097 result
= GenerateNewKey();
3101 result
= keypool
.vchPubKey
;
3106 int64_t CWallet::GetOldestKeyPoolTime()
3110 // if the keypool is empty, return <NOW>
3111 if (setKeyPool
.empty())
3114 // load oldest key from keypool, get time and return
3116 CWalletDB
walletdb(strWalletFile
);
3117 int64_t nIndex
= *(setKeyPool
.begin());
3118 if (!walletdb
.ReadPool(nIndex
, keypool
))
3119 throw runtime_error(std::string(__func__
) + ": read oldest key in keypool failed");
3120 assert(keypool
.vchPubKey
.IsValid());
3121 return keypool
.nTime
;
3124 std::map
<CTxDestination
, CAmount
> CWallet::GetAddressBalances()
3126 map
<CTxDestination
, CAmount
> balances
;
3130 BOOST_FOREACH(PAIRTYPE(uint256
, CWalletTx
) walletEntry
, mapWallet
)
3132 CWalletTx
*pcoin
= &walletEntry
.second
;
3134 if (!pcoin
->IsTrusted())
3137 if (pcoin
->IsCoinBase() && pcoin
->GetBlocksToMaturity() > 0)
3140 int nDepth
= pcoin
->GetDepthInMainChain();
3141 if (nDepth
< (pcoin
->IsFromMe(ISMINE_ALL
) ? 0 : 1))
3144 for (unsigned int i
= 0; i
< pcoin
->tx
->vout
.size(); i
++)
3146 CTxDestination addr
;
3147 if (!IsMine(pcoin
->tx
->vout
[i
]))
3149 if(!ExtractDestination(pcoin
->tx
->vout
[i
].scriptPubKey
, addr
))
3152 CAmount n
= IsSpent(walletEntry
.first
, i
) ? 0 : pcoin
->tx
->vout
[i
].nValue
;
3154 if (!balances
.count(addr
))
3156 balances
[addr
] += n
;
3164 set
< set
<CTxDestination
> > CWallet::GetAddressGroupings()
3166 AssertLockHeld(cs_wallet
); // mapWallet
3167 set
< set
<CTxDestination
> > groupings
;
3168 set
<CTxDestination
> grouping
;
3170 BOOST_FOREACH(PAIRTYPE(uint256
, CWalletTx
) walletEntry
, mapWallet
)
3172 CWalletTx
*pcoin
= &walletEntry
.second
;
3174 if (pcoin
->tx
->vin
.size() > 0)
3176 bool any_mine
= false;
3177 // group all input addresses with each other
3178 BOOST_FOREACH(CTxIn txin
, pcoin
->tx
->vin
)
3180 CTxDestination address
;
3181 if(!IsMine(txin
)) /* If this input isn't mine, ignore it */
3183 if(!ExtractDestination(mapWallet
[txin
.prevout
.hash
].tx
->vout
[txin
.prevout
.n
].scriptPubKey
, address
))
3185 grouping
.insert(address
);
3189 // group change with input addresses
3192 BOOST_FOREACH(CTxOut txout
, pcoin
->tx
->vout
)
3193 if (IsChange(txout
))
3195 CTxDestination txoutAddr
;
3196 if(!ExtractDestination(txout
.scriptPubKey
, txoutAddr
))
3198 grouping
.insert(txoutAddr
);
3201 if (grouping
.size() > 0)
3203 groupings
.insert(grouping
);
3208 // group lone addrs by themselves
3209 for (unsigned int i
= 0; i
< pcoin
->tx
->vout
.size(); i
++)
3210 if (IsMine(pcoin
->tx
->vout
[i
]))
3212 CTxDestination address
;
3213 if(!ExtractDestination(pcoin
->tx
->vout
[i
].scriptPubKey
, address
))
3215 grouping
.insert(address
);
3216 groupings
.insert(grouping
);
3221 set
< set
<CTxDestination
>* > uniqueGroupings
; // a set of pointers to groups of addresses
3222 map
< CTxDestination
, set
<CTxDestination
>* > setmap
; // map addresses to the unique group containing it
3223 BOOST_FOREACH(set
<CTxDestination
> _grouping
, groupings
)
3225 // make a set of all the groups hit by this new group
3226 set
< set
<CTxDestination
>* > hits
;
3227 map
< CTxDestination
, set
<CTxDestination
>* >::iterator it
;
3228 BOOST_FOREACH(CTxDestination address
, _grouping
)
3229 if ((it
= setmap
.find(address
)) != setmap
.end())
3230 hits
.insert((*it
).second
);
3232 // merge all hit groups into a new single group and delete old groups
3233 set
<CTxDestination
>* merged
= new set
<CTxDestination
>(_grouping
);
3234 BOOST_FOREACH(set
<CTxDestination
>* hit
, hits
)
3236 merged
->insert(hit
->begin(), hit
->end());
3237 uniqueGroupings
.erase(hit
);
3240 uniqueGroupings
.insert(merged
);
3243 BOOST_FOREACH(CTxDestination element
, *merged
)
3244 setmap
[element
] = merged
;
3247 set
< set
<CTxDestination
> > ret
;
3248 BOOST_FOREACH(set
<CTxDestination
>* uniqueGrouping
, uniqueGroupings
)
3250 ret
.insert(*uniqueGrouping
);
3251 delete uniqueGrouping
;
3257 CAmount
CWallet::GetAccountBalance(const std::string
& strAccount
, int nMinDepth
, const isminefilter
& filter
)
3259 CWalletDB
walletdb(strWalletFile
);
3260 return GetAccountBalance(walletdb
, strAccount
, nMinDepth
, filter
);
3263 CAmount
CWallet::GetAccountBalance(CWalletDB
& walletdb
, const std::string
& strAccount
, int nMinDepth
, const isminefilter
& filter
)
3265 CAmount nBalance
= 0;
3267 // Tally wallet transactions
3268 for (map
<uint256
, CWalletTx
>::iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); ++it
)
3270 const CWalletTx
& wtx
= (*it
).second
;
3271 if (!CheckFinalTx(wtx
) || wtx
.GetBlocksToMaturity() > 0 || wtx
.GetDepthInMainChain() < 0)
3274 CAmount nReceived
, nSent
, nFee
;
3275 wtx
.GetAccountAmounts(strAccount
, nReceived
, nSent
, nFee
, filter
);
3277 if (nReceived
!= 0 && wtx
.GetDepthInMainChain() >= nMinDepth
)
3278 nBalance
+= nReceived
;
3279 nBalance
-= nSent
+ nFee
;
3282 // Tally internal accounting entries
3283 nBalance
+= walletdb
.GetAccountCreditDebit(strAccount
);
3288 std::set
<CTxDestination
> CWallet::GetAccountAddresses(const std::string
& strAccount
) const
3291 set
<CTxDestination
> result
;
3292 BOOST_FOREACH(const PAIRTYPE(CTxDestination
, CAddressBookData
)& item
, mapAddressBook
)
3294 const CTxDestination
& address
= item
.first
;
3295 const string
& strName
= item
.second
.name
;
3296 if (strName
== strAccount
)
3297 result
.insert(address
);
3302 bool CReserveKey::GetReservedKey(CPubKey
& pubkey
)
3307 pwallet
->ReserveKeyFromKeyPool(nIndex
, keypool
);
3309 vchPubKey
= keypool
.vchPubKey
;
3314 assert(vchPubKey
.IsValid());
3319 void CReserveKey::KeepKey()
3322 pwallet
->KeepKey(nIndex
);
3324 vchPubKey
= CPubKey();
3327 void CReserveKey::ReturnKey()
3330 pwallet
->ReturnKey(nIndex
);
3332 vchPubKey
= CPubKey();
3335 void CWallet::GetAllReserveKeys(set
<CKeyID
>& setAddress
) const
3339 CWalletDB
walletdb(strWalletFile
);
3341 LOCK2(cs_main
, cs_wallet
);
3342 BOOST_FOREACH(const int64_t& id
, setKeyPool
)
3345 if (!walletdb
.ReadPool(id
, keypool
))
3346 throw runtime_error(std::string(__func__
) + ": read failed");
3347 assert(keypool
.vchPubKey
.IsValid());
3348 CKeyID keyID
= keypool
.vchPubKey
.GetID();
3349 if (!HaveKey(keyID
))
3350 throw runtime_error(std::string(__func__
) + ": unknown key in key pool");
3351 setAddress
.insert(keyID
);
3355 void CWallet::UpdatedTransaction(const uint256
&hashTx
)
3359 // Only notify UI if this transaction is in this wallet
3360 map
<uint256
, CWalletTx
>::const_iterator mi
= mapWallet
.find(hashTx
);
3361 if (mi
!= mapWallet
.end())
3362 NotifyTransactionChanged(this, hashTx
, CT_UPDATED
);
3366 void CWallet::GetScriptForMining(boost::shared_ptr
<CReserveScript
> &script
)
3368 boost::shared_ptr
<CReserveKey
> rKey(new CReserveKey(this));
3370 if (!rKey
->GetReservedKey(pubkey
))
3374 script
->reserveScript
= CScript() << ToByteVector(pubkey
) << OP_CHECKSIG
;
3377 void CWallet::LockCoin(const COutPoint
& output
)
3379 AssertLockHeld(cs_wallet
); // setLockedCoins
3380 setLockedCoins
.insert(output
);
3383 void CWallet::UnlockCoin(const COutPoint
& output
)
3385 AssertLockHeld(cs_wallet
); // setLockedCoins
3386 setLockedCoins
.erase(output
);
3389 void CWallet::UnlockAllCoins()
3391 AssertLockHeld(cs_wallet
); // setLockedCoins
3392 setLockedCoins
.clear();
3395 bool CWallet::IsLockedCoin(uint256 hash
, unsigned int n
) const
3397 AssertLockHeld(cs_wallet
); // setLockedCoins
3398 COutPoint
outpt(hash
, n
);
3400 return (setLockedCoins
.count(outpt
) > 0);
3403 void CWallet::ListLockedCoins(std::vector
<COutPoint
>& vOutpts
)
3405 AssertLockHeld(cs_wallet
); // setLockedCoins
3406 for (std::set
<COutPoint
>::iterator it
= setLockedCoins
.begin();
3407 it
!= setLockedCoins
.end(); it
++) {
3408 COutPoint outpt
= (*it
);
3409 vOutpts
.push_back(outpt
);
3413 /** @} */ // end of Actions
3415 class CAffectedKeysVisitor
: public boost::static_visitor
<void> {
3417 const CKeyStore
&keystore
;
3418 std::vector
<CKeyID
> &vKeys
;
3421 CAffectedKeysVisitor(const CKeyStore
&keystoreIn
, std::vector
<CKeyID
> &vKeysIn
) : keystore(keystoreIn
), vKeys(vKeysIn
) {}
3423 void Process(const CScript
&script
) {
3425 std::vector
<CTxDestination
> vDest
;
3427 if (ExtractDestinations(script
, type
, vDest
, nRequired
)) {
3428 BOOST_FOREACH(const CTxDestination
&dest
, vDest
)
3429 boost::apply_visitor(*this, dest
);
3433 void operator()(const CKeyID
&keyId
) {
3434 if (keystore
.HaveKey(keyId
))
3435 vKeys
.push_back(keyId
);
3438 void operator()(const CScriptID
&scriptId
) {
3440 if (keystore
.GetCScript(scriptId
, script
))
3444 void operator()(const CNoDestination
&none
) {}
3447 void CWallet::GetKeyBirthTimes(std::map
<CTxDestination
, int64_t> &mapKeyBirth
) const {
3448 AssertLockHeld(cs_wallet
); // mapKeyMetadata
3449 mapKeyBirth
.clear();
3451 // get birth times for keys with metadata
3452 for (const auto& entry
: mapKeyMetadata
) {
3453 if (entry
.second
.nCreateTime
) {
3454 mapKeyBirth
[entry
.first
] = entry
.second
.nCreateTime
;
3458 // map in which we'll infer heights of other keys
3459 CBlockIndex
*pindexMax
= chainActive
[std::max(0, chainActive
.Height() - 144)]; // the tip can be reorganized; use a 144-block safety margin
3460 std::map
<CKeyID
, CBlockIndex
*> mapKeyFirstBlock
;
3461 std::set
<CKeyID
> setKeys
;
3463 BOOST_FOREACH(const CKeyID
&keyid
, setKeys
) {
3464 if (mapKeyBirth
.count(keyid
) == 0)
3465 mapKeyFirstBlock
[keyid
] = pindexMax
;
3469 // if there are no such keys, we're done
3470 if (mapKeyFirstBlock
.empty())
3473 // find first block that affects those keys, if there are any left
3474 std::vector
<CKeyID
> vAffected
;
3475 for (std::map
<uint256
, CWalletTx
>::const_iterator it
= mapWallet
.begin(); it
!= mapWallet
.end(); it
++) {
3476 // iterate over all wallet transactions...
3477 const CWalletTx
&wtx
= (*it
).second
;
3478 BlockMap::const_iterator blit
= mapBlockIndex
.find(wtx
.hashBlock
);
3479 if (blit
!= mapBlockIndex
.end() && chainActive
.Contains(blit
->second
)) {
3480 // ... which are already in a block
3481 int nHeight
= blit
->second
->nHeight
;
3482 BOOST_FOREACH(const CTxOut
&txout
, wtx
.tx
->vout
) {
3483 // iterate over all their outputs
3484 CAffectedKeysVisitor(*this, vAffected
).Process(txout
.scriptPubKey
);
3485 BOOST_FOREACH(const CKeyID
&keyid
, vAffected
) {
3486 // ... and all their affected keys
3487 std::map
<CKeyID
, CBlockIndex
*>::iterator rit
= mapKeyFirstBlock
.find(keyid
);
3488 if (rit
!= mapKeyFirstBlock
.end() && nHeight
< rit
->second
->nHeight
)
3489 rit
->second
= blit
->second
;
3496 // Extract block timestamps for those keys
3497 for (std::map
<CKeyID
, CBlockIndex
*>::const_iterator it
= mapKeyFirstBlock
.begin(); it
!= mapKeyFirstBlock
.end(); it
++)
3498 mapKeyBirth
[it
->first
] = it
->second
->GetBlockTime() - 7200; // block times can be 2h off
3501 bool CWallet::AddDestData(const CTxDestination
&dest
, const std::string
&key
, const std::string
&value
)
3503 if (boost::get
<CNoDestination
>(&dest
))
3506 mapAddressBook
[dest
].destdata
.insert(std::make_pair(key
, value
));
3509 return CWalletDB(strWalletFile
).WriteDestData(CBitcoinAddress(dest
).ToString(), key
, value
);
3512 bool CWallet::EraseDestData(const CTxDestination
&dest
, const std::string
&key
)
3514 if (!mapAddressBook
[dest
].destdata
.erase(key
))
3518 return CWalletDB(strWalletFile
).EraseDestData(CBitcoinAddress(dest
).ToString(), key
);
3521 bool CWallet::LoadDestData(const CTxDestination
&dest
, const std::string
&key
, const std::string
&value
)
3523 mapAddressBook
[dest
].destdata
.insert(std::make_pair(key
, value
));
3527 bool CWallet::GetDestData(const CTxDestination
&dest
, const std::string
&key
, std::string
*value
) const
3529 std::map
<CTxDestination
, CAddressBookData
>::const_iterator i
= mapAddressBook
.find(dest
);
3530 if(i
!= mapAddressBook
.end())
3532 CAddressBookData::StringMap::const_iterator j
= i
->second
.destdata
.find(key
);
3533 if(j
!= i
->second
.destdata
.end())
3543 std::string
CWallet::GetWalletHelpString(bool showDebug
)
3545 std::string strUsage
= HelpMessageGroup(_("Wallet options:"));
3546 strUsage
+= HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
3547 strUsage
+= HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE
));
3548 strUsage
+= HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
3549 CURRENCY_UNIT
, FormatMoney(DEFAULT_FALLBACK_FEE
)));
3550 strUsage
+= HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
3551 CURRENCY_UNIT
, FormatMoney(DEFAULT_TRANSACTION_MINFEE
)));
3552 strUsage
+= HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
3553 CURRENCY_UNIT
, FormatMoney(payTxFee
.GetFeePerK())));
3554 strUsage
+= HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
3555 strUsage
+= HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup"));
3557 strUsage
+= HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), DEFAULT_SEND_FREE_TRANSACTIONS
));
3558 strUsage
+= HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE
));
3559 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
));
3560 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
));
3561 strUsage
+= HelpMessageOpt("-walletrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (default: %u)"), DEFAULT_WALLET_RBF
));
3562 strUsage
+= HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
3563 strUsage
+= HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT
));
3564 strUsage
+= HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST
));
3565 strUsage
+= HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
3566 strUsage
+= HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
3567 " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
3571 strUsage
+= HelpMessageGroup(_("Wallet debugging/testing options:"));
3573 strUsage
+= HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE
));
3574 strUsage
+= HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET
));
3575 strUsage
+= HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB
));
3576 strUsage
+= HelpMessageOpt("-walletrejectlongchains", strprintf(_("Wallet will not create transactions that violate mempool chain limits (default: %u)"), DEFAULT_WALLET_REJECT_LONG_CHAINS
));
3582 CWallet
* CWallet::CreateWalletFromFile(const std::string walletFile
)
3584 // needed to restore wallet transaction meta data after -zapwallettxes
3585 std::vector
<CWalletTx
> vWtx
;
3587 if (GetBoolArg("-zapwallettxes", false)) {
3588 uiInterface
.InitMessage(_("Zapping all transactions from wallet..."));
3590 CWallet
*tempWallet
= new CWallet(walletFile
);
3591 DBErrors nZapWalletRet
= tempWallet
->ZapWalletTx(vWtx
);
3592 if (nZapWalletRet
!= DB_LOAD_OK
) {
3593 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile
));
3601 uiInterface
.InitMessage(_("Loading wallet..."));
3603 int64_t nStart
= GetTimeMillis();
3604 bool fFirstRun
= true;
3605 CWallet
*walletInstance
= new CWallet(walletFile
);
3606 DBErrors nLoadWalletRet
= walletInstance
->LoadWallet(fFirstRun
);
3607 if (nLoadWalletRet
!= DB_LOAD_OK
)
3609 if (nLoadWalletRet
== DB_CORRUPT
) {
3610 InitError(strprintf(_("Error loading %s: Wallet corrupted"), walletFile
));
3613 else if (nLoadWalletRet
== DB_NONCRITICAL_ERROR
)
3615 InitWarning(strprintf(_("Error reading %s! All keys read correctly, but transaction data"
3616 " or address book entries might be missing or incorrect."),
3619 else if (nLoadWalletRet
== DB_TOO_NEW
) {
3620 InitError(strprintf(_("Error loading %s: Wallet requires newer version of %s"), walletFile
, _(PACKAGE_NAME
)));
3623 else if (nLoadWalletRet
== DB_NEED_REWRITE
)
3625 InitError(strprintf(_("Wallet needed to be rewritten: restart %s to complete"), _(PACKAGE_NAME
)));
3629 InitError(strprintf(_("Error loading %s"), walletFile
));
3634 if (GetBoolArg("-upgradewallet", fFirstRun
))
3636 int nMaxVersion
= GetArg("-upgradewallet", 0);
3637 if (nMaxVersion
== 0) // the -upgradewallet without argument case
3639 LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST
);
3640 nMaxVersion
= CLIENT_VERSION
;
3641 walletInstance
->SetMinVersion(FEATURE_LATEST
); // permanently upgrade the wallet immediately
3644 LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion
);
3645 if (nMaxVersion
< walletInstance
->GetVersion())
3647 InitError(_("Cannot downgrade wallet"));
3650 walletInstance
->SetMaxVersion(nMaxVersion
);
3655 // Create new keyUser and set as default key
3656 if (GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET
) && !walletInstance
->IsHDEnabled()) {
3657 // generate a new master key
3658 CPubKey masterPubKey
= walletInstance
->GenerateNewHDMasterKey();
3659 if (!walletInstance
->SetHDMasterKey(masterPubKey
))
3660 throw std::runtime_error(std::string(__func__
) + ": Storing master key failed");
3662 CPubKey newDefaultKey
;
3663 if (walletInstance
->GetKeyFromPool(newDefaultKey
)) {
3664 walletInstance
->SetDefaultKey(newDefaultKey
);
3665 if (!walletInstance
->SetAddressBook(walletInstance
->vchDefaultKey
.GetID(), "", "receive")) {
3666 InitError(_("Cannot write default address") += "\n");
3671 walletInstance
->SetBestChain(chainActive
.GetLocator());
3673 else if (IsArgSet("-usehd")) {
3674 bool useHD
= GetBoolArg("-usehd", DEFAULT_USE_HD_WALLET
);
3675 if (walletInstance
->IsHDEnabled() && !useHD
) {
3676 InitError(strprintf(_("Error loading %s: You can't disable HD on a already existing HD wallet"), walletFile
));
3679 if (!walletInstance
->IsHDEnabled() && useHD
) {
3680 InitError(strprintf(_("Error loading %s: You can't enable HD on a already existing non-HD wallet"), walletFile
));
3685 LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart
);
3687 RegisterValidationInterface(walletInstance
);
3689 CBlockIndex
*pindexRescan
= chainActive
.Tip();
3690 if (GetBoolArg("-rescan", false))
3691 pindexRescan
= chainActive
.Genesis();
3694 CWalletDB
walletdb(walletFile
);
3695 CBlockLocator locator
;
3696 if (walletdb
.ReadBestBlock(locator
))
3697 pindexRescan
= FindForkInGlobalIndex(chainActive
, locator
);
3699 pindexRescan
= chainActive
.Genesis();
3701 if (chainActive
.Tip() && chainActive
.Tip() != pindexRescan
)
3703 //We can't rescan beyond non-pruned blocks, stop and throw an error
3704 //this might happen if a user uses a old wallet within a pruned node
3705 // or if he ran -disablewallet for a longer time, then decided to re-enable
3708 CBlockIndex
*block
= chainActive
.Tip();
3709 while (block
&& block
->pprev
&& (block
->pprev
->nStatus
& BLOCK_HAVE_DATA
) && block
->pprev
->nTx
> 0 && pindexRescan
!= block
)
3710 block
= block
->pprev
;
3712 if (pindexRescan
!= block
) {
3713 InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
3718 uiInterface
.InitMessage(_("Rescanning..."));
3719 LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive
.Height() - pindexRescan
->nHeight
, pindexRescan
->nHeight
);
3720 nStart
= GetTimeMillis();
3721 walletInstance
->ScanForWalletTransactions(pindexRescan
, true);
3722 LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart
);
3723 walletInstance
->SetBestChain(chainActive
.GetLocator());
3724 CWalletDB::IncrementUpdateCounter();
3726 // Restore wallet transaction metadata after -zapwallettxes=1
3727 if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
3729 CWalletDB
walletdb(walletFile
);
3731 BOOST_FOREACH(const CWalletTx
& wtxOld
, vWtx
)
3733 uint256 hash
= wtxOld
.GetHash();
3734 std::map
<uint256
, CWalletTx
>::iterator mi
= walletInstance
->mapWallet
.find(hash
);
3735 if (mi
!= walletInstance
->mapWallet
.end())
3737 const CWalletTx
* copyFrom
= &wtxOld
;
3738 CWalletTx
* copyTo
= &mi
->second
;
3739 copyTo
->mapValue
= copyFrom
->mapValue
;
3740 copyTo
->vOrderForm
= copyFrom
->vOrderForm
;
3741 copyTo
->nTimeReceived
= copyFrom
->nTimeReceived
;
3742 copyTo
->nTimeSmart
= copyFrom
->nTimeSmart
;
3743 copyTo
->fFromMe
= copyFrom
->fFromMe
;
3744 copyTo
->strFromAccount
= copyFrom
->strFromAccount
;
3745 copyTo
->nOrderPos
= copyFrom
->nOrderPos
;
3746 walletdb
.WriteTx(*copyTo
);
3751 walletInstance
->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST
));
3754 LOCK(walletInstance
->cs_wallet
);
3755 LogPrintf("setKeyPool.size() = %u\n", walletInstance
->GetKeyPoolSize());
3756 LogPrintf("mapWallet.size() = %u\n", walletInstance
->mapWallet
.size());
3757 LogPrintf("mapAddressBook.size() = %u\n", walletInstance
->mapAddressBook
.size());
3760 return walletInstance
;
3763 bool CWallet::InitLoadWallet()
3765 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET
)) {
3767 LogPrintf("Wallet disabled!\n");
3771 std::string walletFile
= GetArg("-wallet", DEFAULT_WALLET_DAT
);
3773 if (walletFile
.find_first_of("/\\") != std::string::npos
) {
3774 return InitError(_("-wallet parameter must only specify a filename (not a path)"));
3775 } else if (SanitizeString(walletFile
, SAFE_CHARS_FILENAME
) != walletFile
) {
3776 return InitError(_("Invalid characters in -wallet filename"));
3779 CWallet
* const pwallet
= CreateWalletFromFile(walletFile
);
3783 pwalletMain
= pwallet
;
3788 std::atomic
<bool> CWallet::fFlushThreadRunning(false);
3790 void CWallet::postInitProcess(boost::thread_group
& threadGroup
)
3792 // Add wallet transactions that aren't already in a block to mempool
3793 // Do this here as mempool requires genesis block to be loaded
3794 ReacceptWalletTransactions();
3796 // Run a thread to flush wallet periodically
3797 if (!CWallet::fFlushThreadRunning
.exchange(true)) {
3798 threadGroup
.create_thread(ThreadFlushWalletDB
);
3802 bool CWallet::ParameterInteraction()
3804 if (GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET
))
3807 if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY
) && SoftSetBoolArg("-walletbroadcast", false)) {
3808 LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__
);
3811 if (GetBoolArg("-salvagewallet", false) && SoftSetBoolArg("-rescan", true)) {
3812 // Rewrite just private keys: rescan to find transactions
3813 LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__
);
3816 // -zapwallettx implies a rescan
3817 if (GetBoolArg("-zapwallettxes", false) && SoftSetBoolArg("-rescan", true)) {
3818 LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__
);
3821 if (GetBoolArg("-sysperms", false))
3822 return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
3823 if (GetArg("-prune", 0) && GetBoolArg("-rescan", false))
3824 return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
3826 if (::minRelayTxFee
.GetFeePerK() > HIGH_TX_FEE_PER_KB
)
3827 InitWarning(AmountHighWarn("-minrelaytxfee") + " " +
3828 _("The wallet will avoid paying less than the minimum relay fee."));
3830 if (IsArgSet("-mintxfee"))
3833 if (!ParseMoney(GetArg("-mintxfee", ""), n
) || 0 == n
)
3834 return InitError(AmountErrMsg("mintxfee", GetArg("-mintxfee", "")));
3835 if (n
> HIGH_TX_FEE_PER_KB
)
3836 InitWarning(AmountHighWarn("-mintxfee") + " " +
3837 _("This is the minimum transaction fee you pay on every transaction."));
3838 CWallet::minTxFee
= CFeeRate(n
);
3840 if (IsArgSet("-fallbackfee"))
3842 CAmount nFeePerK
= 0;
3843 if (!ParseMoney(GetArg("-fallbackfee", ""), nFeePerK
))
3844 return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), GetArg("-fallbackfee", "")));
3845 if (nFeePerK
> HIGH_TX_FEE_PER_KB
)
3846 InitWarning(AmountHighWarn("-fallbackfee") + " " +
3847 _("This is the transaction fee you may pay when fee estimates are not available."));
3848 CWallet::fallbackFee
= CFeeRate(nFeePerK
);
3850 if (IsArgSet("-paytxfee"))
3852 CAmount nFeePerK
= 0;
3853 if (!ParseMoney(GetArg("-paytxfee", ""), nFeePerK
))
3854 return InitError(AmountErrMsg("paytxfee", GetArg("-paytxfee", "")));
3855 if (nFeePerK
> HIGH_TX_FEE_PER_KB
)
3856 InitWarning(AmountHighWarn("-paytxfee") + " " +
3857 _("This is the transaction fee you will pay if you send a transaction."));
3859 payTxFee
= CFeeRate(nFeePerK
, 1000);
3860 if (payTxFee
< ::minRelayTxFee
)
3862 return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
3863 GetArg("-paytxfee", ""), ::minRelayTxFee
.ToString()));
3866 if (IsArgSet("-maxtxfee"))
3868 CAmount nMaxFee
= 0;
3869 if (!ParseMoney(GetArg("-maxtxfee", ""), nMaxFee
))
3870 return InitError(AmountErrMsg("maxtxfee", GetArg("-maxtxfee", "")));
3871 if (nMaxFee
> HIGH_MAX_TX_FEE
)
3872 InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
3874 if (CFeeRate(maxTxFee
, 1000) < ::minRelayTxFee
)
3876 return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
3877 GetArg("-maxtxfee", ""), ::minRelayTxFee
.ToString()));
3880 nTxConfirmTarget
= GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET
);
3881 bSpendZeroConfChange
= GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE
);
3882 fSendFreeTransactions
= GetBoolArg("-sendfreetransactions", DEFAULT_SEND_FREE_TRANSACTIONS
);
3883 fWalletRbf
= GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF
);
3885 if (fSendFreeTransactions
&& GetArg("-limitfreerelay", DEFAULT_LIMITFREERELAY
) <= 0)
3886 return InitError("Creation of free transactions with their relay disabled is not supported.");
3891 bool CWallet::BackupWallet(const std::string
& strDest
)
3899 if (!bitdb
.mapFileUseCount
.count(strWalletFile
) || bitdb
.mapFileUseCount
[strWalletFile
] == 0)
3901 // Flush log data to the dat file
3902 bitdb
.CloseDb(strWalletFile
);
3903 bitdb
.CheckpointLSN(strWalletFile
);
3904 bitdb
.mapFileUseCount
.erase(strWalletFile
);
3907 boost::filesystem::path pathSrc
= GetDataDir() / strWalletFile
;
3908 boost::filesystem::path
pathDest(strDest
);
3909 if (boost::filesystem::is_directory(pathDest
))
3910 pathDest
/= strWalletFile
;
3913 boost::filesystem::copy_file(pathSrc
, pathDest
, boost::filesystem::copy_option::overwrite_if_exists
);
3914 LogPrintf("copied %s to %s\n", strWalletFile
, pathDest
.string());
3916 } catch (const boost::filesystem::filesystem_error
& e
) {
3917 LogPrintf("error copying %s to %s - %s\n", strWalletFile
, pathDest
.string(), e
.what());
3927 CKeyPool::CKeyPool()
3932 CKeyPool::CKeyPool(const CPubKey
& vchPubKeyIn
)
3935 vchPubKey
= vchPubKeyIn
;
3938 CWalletKey::CWalletKey(int64_t nExpires
)
3940 nTimeCreated
= (nExpires
? GetTime() : 0);
3941 nTimeExpires
= nExpires
;
3944 void CMerkleTx::SetMerkleBranch(const CBlockIndex
* pindex
, int posInBlock
)
3946 // Update the tx's hashBlock
3947 hashBlock
= pindex
->GetBlockHash();
3949 // set the position of the transaction in the block
3950 nIndex
= posInBlock
;
3953 int CMerkleTx::GetDepthInMainChain(const CBlockIndex
* &pindexRet
) const
3958 AssertLockHeld(cs_main
);
3960 // Find the block it claims to be in
3961 BlockMap::iterator mi
= mapBlockIndex
.find(hashBlock
);
3962 if (mi
== mapBlockIndex
.end())
3964 CBlockIndex
* pindex
= (*mi
).second
;
3965 if (!pindex
|| !chainActive
.Contains(pindex
))
3969 return ((nIndex
== -1) ? (-1) : 1) * (chainActive
.Height() - pindex
->nHeight
+ 1);
3972 int CMerkleTx::GetBlocksToMaturity() const
3976 return max(0, (COINBASE_MATURITY
+1) - GetDepthInMainChain());
3980 bool CMerkleTx::AcceptToMemoryPool(const CAmount
& nAbsurdFee
, CValidationState
& state
)
3982 return ::AcceptToMemoryPool(mempool
, state
, tx
, true, NULL
, NULL
, false, nAbsurdFee
);