36 #include <boost/algorithm/string/replace.hpp> 38 static const size_t OUTPUT_GROUP_MAX_ENTRIES = 10;
43 bool AddWallet(
const std::shared_ptr<CWallet>& wallet)
47 std::vector<std::shared_ptr<CWallet>>::const_iterator i = std::find(vpwallets.begin(), vpwallets.end(), wallet);
48 if (i != vpwallets.end())
return false;
49 vpwallets.push_back(wallet);
57 std::vector<std::shared_ptr<CWallet>>::iterator i = std::find(vpwallets.begin(), vpwallets.end(), wallet);
58 if (i == vpwallets.end())
return false;
66 return !vpwallets.empty();
78 for (
const std::shared_ptr<CWallet>& wallet : vpwallets) {
79 if (wallet->GetName() ==
name)
return wallet;
85 static void ReleaseWallet(
CWallet* wallet)
128 std::vector<CTxDestination> vDest;
132 boost::apply_visitor(*
this, dest);
138 vKeys.push_back(keyId);
172 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash);
173 if (it == mapWallet.end())
175 return &(it->second);
187 int64_t nCreationTime =
GetTime();
205 mapKeyMetadata[pubkey.
GetID()] = metadata;
209 throw std::runtime_error(std::string(__func__) +
": AddKey failed");
225 throw std::runtime_error(std::string(__func__) +
": seed not found");
253 secret = childKey.
key;
257 throw std::runtime_error(std::string(__func__) +
": Writing HD chain model failed");
267 bool needsDB = !encrypted_batch;
269 encrypted_batch = &batch;
272 if (needsDB) encrypted_batch =
nullptr;
275 if (needsDB) encrypted_batch =
nullptr;
291 mapKeyMetadata[pubkey.
GetID()]);
303 const std::vector<unsigned char> &vchCryptedSecret)
310 return encrypted_batch->WriteCryptedKey(vchPubKey,
312 mapKeyMetadata[vchPubKey.
GetID()]);
316 mapKeyMetadata[vchPubKey.
GetID()]);
324 mapKeyMetadata[keyID] = meta;
331 m_script_metadata[script_id] = meta;
346 if (nCreateTime <= 1) {
350 }
else if (!nTimeFirstKey || nCreateTime < nTimeFirstKey) {
351 nTimeFirstKey = nCreateTime;
367 if (redeemScript.
size() > MAX_SCRIPT_ELEMENT_SIZE)
370 WalletLogPrintf(
"%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", __func__, redeemScript.
size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
389 m_script_metadata[
CScriptID(dest)].nCreateTime = nCreateTime;
418 for (
const MasterKeyMap::value_type& pMasterKey :
mapMasterKeys)
420 if(!crypter.
SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
422 if (!crypter.
Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
443 if(!crypter.
SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
445 if (!crypter.
Decrypt(pMasterKey.second.vchCryptedKey, _vMasterKey))
450 crypter.
SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
451 pMasterKey.second.nDeriveIterations =
static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * (100 / ((double)(
GetTimeMillis() - nStartTime))));
454 crypter.
SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
455 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations +
static_cast<unsigned int>(pMasterKey.second.nDeriveIterations * 100 / ((double)(
GetTimeMillis() - nStartTime)))) / 2;
457 if (pMasterKey.second.nDeriveIterations < 25000)
458 pMasterKey.second.nDeriveIterations = 25000;
460 WalletLogPrintf(
"Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
462 if (!crypter.
SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
464 if (!crypter.
Encrypt(_vMasterKey, pMasterKey.second.vchCryptedKey))
490 if (fExplicit && nVersion > nWalletMaxVersion)
495 if (nVersion > nWalletMaxVersion)
496 nWalletMaxVersion = nVersion;
514 nWalletMaxVersion = nVersion;
521 std::set<uint256> result;
524 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid);
525 if (it == mapWallet.end())
529 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
531 for (
const CTxIn& txin : wtx.
tx->vin)
533 if (mapTxSpends.count(txin.
prevout) <= 1)
535 range = mapTxSpends.equal_range(txin.
prevout);
536 for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
537 result.insert(_it->second);
545 auto iter = mapTxSpends.lower_bound(
COutPoint(txid, 0));
546 return (iter != mapTxSpends.end() && iter->first.hash == txid);
560 int nMinOrderPos = std::numeric_limits<int>::max();
562 for (TxSpends::iterator it = range.first; it != range.second; ++it) {
563 const CWalletTx* wtx = &mapWallet.at(it->second);
575 for (TxSpends::iterator it = range.first; it != range.second; ++it)
577 const uint256& hash = it->second;
579 if (copyFrom == copyTo)
continue;
580 assert(copyFrom &&
"Oldest wallet transaction in range assumed to have been found.");
600 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
601 range = mapTxSpends.equal_range(outpoint);
603 for (TxSpends::const_iterator it = range.first; it != range.second; ++it)
605 const uint256& wtxid = it->second;
606 std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid);
607 if (mit != mapWallet.end()) {
608 int depth = mit->second.GetDepthInMainChain();
609 if (depth > 0 || (depth == 0 && !mit->second.isAbandoned()))
618 mapTxSpends.insert(std::make_pair(outpoint, wtxid));
620 setLockedCoins.erase(outpoint);
622 std::pair<TxSpends::iterator, TxSpends::iterator> range;
623 range = mapTxSpends.equal_range(outpoint);
630 auto it = mapWallet.find(wtxid);
631 assert(it != mapWallet.end());
633 if (thisTx.IsCoinBase())
636 for (
const CTxIn& txin : thisTx.tx->vin)
677 assert(!encrypted_batch);
679 if (!encrypted_batch->TxnBegin()) {
680 delete encrypted_batch;
681 encrypted_batch =
nullptr;
688 encrypted_batch->TxnAbort();
689 delete encrypted_batch;
690 encrypted_batch =
nullptr;
699 if (!encrypted_batch->TxnCommit()) {
700 delete encrypted_batch;
701 encrypted_batch =
nullptr;
707 delete encrypted_batch;
708 encrypted_batch =
nullptr;
711 Unlock(strWalletPassphrase);
745 typedef std::multimap<int64_t, CWalletTx*>
TxItems;
748 for (
auto& entry : mapWallet)
755 std::vector<int64_t> nOrderPosOffsets;
756 for (TxItems::iterator it = txByTime.begin(); it != txByTime.end(); ++it)
763 nOrderPos = nOrderPosNext++;
764 nOrderPosOffsets.push_back(nOrderPos);
771 int64_t nOrderPosOff = 0;
772 for (
const int64_t& nOffsetStart : nOrderPosOffsets)
774 if (nOrderPos >= nOffsetStart)
777 nOrderPos += nOrderPosOff;
778 nOrderPosNext = std::max(nOrderPosNext, nOrderPos + 1);
796 int64_t nRet = nOrderPosNext++;
809 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
810 item.second.MarkDirty();
818 auto mi = mapWallet.find(originalHash);
821 assert(mi != mapWallet.end());
826 assert(wtx.mapValue.count(
"replaced_by_txid") == 0);
834 WalletLogPrintf(
"%s: Updating batch tx %s failed\n", __func__, wtx.GetHash().ToString());
852 std::pair<std::map<uint256, CWalletTx>::iterator,
bool>
ret = mapWallet.insert(std::make_pair(hash, wtxIn));
855 bool fInsertedNew =
ret.second;
864 bool fUpdated =
false;
894 if (wtxIn.
tx->HasWitness() && !wtx.
tx->HasWitness()) {
904 if (fInsertedNew || fUpdated)
915 std::string strCmd =
gArgs.
GetArg(
"-walletnotify",
"");
930 const auto& ins = mapWallet.emplace(hash, wtxIn);
937 for (
const CTxIn& txin : wtx.
tx->vin) {
939 if (it != mapWallet.end()) {
954 if (pIndex !=
nullptr) {
956 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range = mapTxSpends.equal_range(txin.
prevout);
957 while (range.first != range.second) {
958 if (range.first->second != tx.
GetHash()) {
959 WalletLogPrintf(
"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);
967 bool fExisted = mapWallet.count(tx.
GetHash()) != 0;
968 if (fExisted && !fUpdate)
return false;
980 std::vector<CKeyID> vAffected;
982 for (
const CKeyID &keyid : vAffected) {
985 WalletLogPrintf(
"%s: Detected a used keypool key, mark all keypool key up to this key as used\n", __func__);
989 WalletLogPrintf(
"%s: Topping up keypool failed (locked wallet)\n", __func__);
998 if (pIndex !=
nullptr)
1016 for (
const CTxIn& txin : tx->vin) {
1018 if (it != mapWallet.end()) {
1019 it->second.MarkDirty();
1030 std::set<uint256> todo;
1031 std::set<uint256> done;
1034 auto it = mapWallet.find(hashTx);
1035 assert(it != mapWallet.end());
1037 if (origtx.GetDepthInMainChain() != 0 || origtx.InMempool()) {
1041 todo.insert(hashTx);
1043 while (!todo.empty()) {
1047 auto it = mapWallet.find(now);
1048 assert(it != mapWallet.end());
1052 assert(currentconfirm <= 0);
1054 if (currentconfirm == 0 && !wtx.isAbandoned()) {
1056 assert(!wtx.InMempool());
1063 TxSpends::const_iterator iter = mapTxSpends.lower_bound(
COutPoint(now, 0));
1064 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1065 if (!done.count(iter->second)) {
1066 todo.insert(iter->second);
1083 int conflictconfirms = 0;
1092 if (conflictconfirms >= 0)
1098 std::set<uint256> todo;
1099 std::set<uint256> done;
1101 todo.insert(hashTx);
1103 while (!todo.empty()) {
1107 auto it = mapWallet.find(now);
1108 assert(it != mapWallet.end());
1111 if (conflictconfirms < currentconfirm) {
1115 wtx.hashBlock = hashBlock;
1119 TxSpends::const_iterator iter = mapTxSpends.lower_bound(
COutPoint(now, 0));
1120 while (iter != mapTxSpends.end() && iter->first.hash == now) {
1121 if (!done.count(iter->second)) {
1122 todo.insert(iter->second);
1147 auto it = mapWallet.find(ptx->GetHash());
1148 if (it != mapWallet.end()) {
1149 it->second.fInMempool =
true;
1155 auto it = mapWallet.find(ptx->GetHash());
1156 if (it != mapWallet.end()) {
1157 it->second.fInMempool =
false;
1175 for (
size_t i = 0; i < pblock->vtx.size(); i++) {
1222 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.
prevout.
hash);
1223 if (mi != mapWallet.end())
1239 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.
prevout.
hash);
1240 if (mi != mapWallet.end())
1259 throw std::runtime_error(std::string(__func__) +
": value out of range");
1288 throw std::runtime_error(std::string(__func__) +
": value out of range");
1312 throw std::runtime_error(std::string(__func__) +
": value out of range");
1324 if (mi == mapWallet.end())
1345 throw std::runtime_error(std::string(__func__) +
": value out of range");
1357 throw std::runtime_error(std::string(__func__) +
": value out of range");
1372 int64_t nCreationTime =
GetTime();
1387 mapKeyMetadata[seed.
GetID()] = metadata;
1391 throw std::runtime_error(std::string(__func__) +
": AddKeyPubKey failed");
1413 throw std::runtime_error(std::string(__func__) +
": writing chain failed");
1428 throw std::runtime_error(std::string(__func__) +
": writing wallet flags failed");
1440 if (((overwriteFlags & g_known_wallet_flags) >> 32) ^ (overwriteFlags >> 32)) {
1445 throw std::runtime_error(std::string(__func__) +
": writing wallet flags failed");
1477 for (
const auto& txout : txouts)
1490 std::vector<CTxOut> txouts;
1494 for (
const CTxIn& input : tx.
vin) {
1495 const auto mi = wallet->mapWallet.find(input.
prevout.
hash);
1496 if (mi == wallet->mapWallet.end()) {
1499 assert(input.
prevout.
n < mi->second.tx->vout.size());
1500 txouts.emplace_back(mi->second.tx->vout[input.
prevout.
n]);
1509 if (!wallet->
DummySignTx(txNew, txouts, use_max_sig)) {
1533 listReceived.clear();
1541 nFee = nDebit - nValueOut;
1545 for (
unsigned int i = 0; i <
tx->vout.size(); ++i)
1558 else if (!(fIsMine &
filter))
1575 listSent.push_back(output);
1579 listReceived.push_back(output);
1648 double progress_begin;
1649 double progress_end;
1653 if (pindexStop ==
nullptr) {
1660 double progress_current = progress_begin;
1663 if (pindex->
nHeight % 100 == 0 && progress_end - progress_begin > 0.0) {
1664 ShowProgress(
strprintf(
"%s " +
_(
"Rescanning..."),
GetDisplayName()), std::max(1, std::min(99, (
int)((progress_current - progress_begin) / (progress_end - progress_begin) * 100))));
1680 for (
size_t posInBlock = 0; posInBlock < block.
vtx.size(); ++posInBlock) {
1686 if (pindex == pindexStop) {
1703 WalletLogPrintf(
"Rescan interrupted by shutdown request at block %d. Progress=%f\n", pindex->
nHeight, progress_current);
1716 std::map<int64_t, CWalletTx*> mapSorted;
1719 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1721 const uint256& wtxid = item.first;
1723 assert(wtx.
GetHash() == wtxid);
1728 mapSorted.insert(std::make_pair(wtx.
nOrderPos, &wtx));
1733 for (
const std::pair<const int64_t, CWalletTx*>& item : mapSorted) {
1764 std::set<uint256> result;
1769 result.erase(myHash);
1776 if (
tx->vin.empty())
1861 bool* cache_used =
nullptr;
1871 if (fUseCache && cache_used && *cache_used) {
1877 for (
unsigned int i = 0; i <
tx->vout.size(); i++)
1884 throw std::runtime_error(std::string(__func__) +
" : value out of range");
1941 for (
const CTxIn& txin :
tx->vin)
1945 if (parent ==
nullptr)
1958 for (
auto& txin : tx1.vin) txin.scriptSig =
CScript();
1959 for (
auto& txin : tx2.vin) txin.scriptSig =
CScript();
1965 std::vector<uint256> result;
1970 std::multimap<unsigned int, CWalletTx*> mapSorted;
1971 for (std::pair<const uint256, CWalletTx>& item : mapWallet)
1979 for (
const std::pair<const unsigned int, CWalletTx*>& item : mapSorted)
1983 result.push_back(wtx.
GetHash());
2007 if (!relayed.empty())
2008 WalletLogPrintf(
"%s: rebroadcast %u unconfirmed transactions\n", __func__, relayed.size());
2027 for (
const auto& entry : mapWallet)
2044 for (
const auto& entry : mapWallet)
2059 for (
const auto& entry : mapWallet)
2073 for (
const auto& entry : mapWallet)
2088 for (
const auto& entry : mapWallet)
2108 for (
const auto& entry : mapWallet) {
2118 const bool outgoing = debit > 0;
2119 for (
const CTxOut& out : wtx.
tx->vout) {
2122 }
else if (
IsMine(out) &
filter && depth >= minDepth) {
2141 std::vector<COutput> vCoins;
2143 for (
const COutput& out : vCoins) {
2144 if (out.fSpendable) {
2145 balance += out.tx->tx->vout[out.i].nValue;
2159 for (
const auto& entry : mapWallet)
2161 const uint256& wtxid = entry.first;
2196 if (nDepth == 0 && pcoin->
mapValue.count(
"replaces_txid")) {
2208 if (nDepth == 0 && pcoin->
mapValue.count(
"replaced_by_txid")) {
2212 if (fOnlySafe && !safeTx) {
2216 if (nDepth < nMinDepth || nDepth > nMaxDepth)
2219 for (
unsigned int i = 0; i < pcoin->
tx->vout.size(); i++) {
2220 if (pcoin->
tx->vout[i].nValue < nMinimumAmount || pcoin->
tx->vout[i].nValue > nMaximumAmount)
2238 bool solvable =
IsSolvable(*
this, pcoin->
tx->vout[i].scriptPubKey);
2241 vCoins.push_back(
COutput(pcoin, i, nDepth, spendable, solvable, safeTx, (coinControl && coinControl->
fAllowWatchOnly)));
2244 if (nMinimumSumAmount != MAX_MONEY) {
2245 nTotal += pcoin->
tx->vout[i].nValue;
2247 if (nTotal >= nMinimumSumAmount) {
2253 if (nMaximumCount > 0 && vCoins.size() >= nMaximumCount) {
2265 std::map<CTxDestination, std::vector<COutput>> result;
2266 std::vector<COutput> availableCoins;
2270 for (
const COutput& coin : availableCoins) {
2272 if (coin.fSpendable &&
2274 result[address].emplace_back(std::move(coin));
2278 std::vector<COutPoint> lockedCoins;
2280 for (
const COutPoint& output : lockedCoins) {
2281 auto it = mapWallet.find(output.hash);
2282 if (it != mapWallet.end()) {
2283 int depth = it->second.GetDepthInMainChain();
2284 if (depth >= 0 && output.n < it->second.tx->vout.size() &&
2288 result[address].emplace_back(
2289 &it->second, output.n, depth,
true ,
true ,
false );
2304 auto it = mapWallet.find(prevout.
hash);
2305 if (it == mapWallet.end() || it->second.tx->vout.size() <= prevout.
n ||
2306 !
IsMine(it->second.tx->vout[prevout.
n])) {
2309 ptx = it->second.tx.get();
2312 return ptx->
vout[n];
2318 setCoinsRet.clear();
2321 std::vector<OutputGroup> utxo_pool;
2334 if (!group.EligibleForSpending(eligibility_filter))
continue;
2337 group.long_term_fee = 0;
2338 group.effective_value = 0;
2339 for (
auto it = group.m_outputs.begin(); it != group.m_outputs.end(); ) {
2343 if (effective_value > 0) {
2346 group.effective_value += effective_value;
2349 it = group.Discard(coin);
2352 if (group.effective_value > 0) utxo_pool.push_back(group);
2357 return SelectCoinsBnB(utxo_pool, nTargetValue, cost_of_change, setCoinsRet, nValueRet, not_input_fees);
2361 if (!group.EligibleForSpending(eligibility_filter))
continue;
2362 utxo_pool.push_back(group);
2365 return KnapsackSolver(nTargetValue, utxo_pool, setCoinsRet, nValueRet);
2371 std::vector<COutput> vCoins(vAvailableCoins);
2379 for (
const COutput& out : vCoins)
2381 if (!out.fSpendable)
2383 nValueRet += out.tx->tx->vout[out.i].nValue;
2384 setCoinsRet.insert(out.GetInputCoin());
2386 return (nValueRet >= nTargetValue);
2390 std::set<CInputCoin> setPresetCoins;
2391 CAmount nValueFromPresetInputs = 0;
2393 std::vector<COutPoint> vPresetInputs;
2395 for (
const COutPoint& outpoint : vPresetInputs)
2401 std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(outpoint.hash);
2402 if (it != mapWallet.end())
2406 if (pcoin->
tx->vout.size() <= outpoint.n)
2409 nValueFromPresetInputs += pcoin->
tx->vout[outpoint.n].nValue;
2410 setPresetCoins.insert(
CInputCoin(pcoin->
tx, outpoint.n));
2416 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coin_control.
HasSelected();)
2418 if (setPresetCoins.count(it->GetInputCoin()))
2419 it = vCoins.erase(it);
2434 size_t max_ancestors = (size_t)std::max<int64_t>(1,
gArgs.
GetArg(
"-limitancestorcount", DEFAULT_ANCESTOR_LIMIT));
2435 size_t max_descendants = (size_t)std::max<int64_t>(1,
gArgs.
GetArg(
"-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2436 bool fRejectLongChains =
gArgs.
GetBoolArg(
"-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS);
2438 bool res = nTargetValue <= nValueFromPresetInputs ||
2442 (
m_spend_zero_conf_change &&
SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs,
CoinEligibilityFilter(0, 1, std::min((
size_t)4, max_ancestors/3), std::min((
size_t)4, max_descendants/3)), groups, setCoinsRet, nValueRet,
coin_selection_params, bnb_used)) ||
2451 nValueRet += nValueFromPresetInputs;
2462 for (
auto& input : tx.
vin) {
2463 std::map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(input.prevout.hash);
2464 if(mi == mapWallet.end() || input.prevout.n >= mi->second.tx->vout.size()) {
2467 const CScript& scriptPubKey = mi->second.tx->vout[input.prevout.n].scriptPubKey;
2468 const CAmount& amount = mi->second.tx->vout[input.prevout.n].nValue;
2481 std::vector<CRecipient> vecSend;
2484 for (
size_t idx = 0; idx < tx.
vout.size(); idx++) {
2487 vecSend.push_back(recipient);
2502 if (!
CreateTransaction(vecSend, tx_new, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl,
false)) {
2506 if (nChangePosInOut != -1) {
2507 tx.
vout.insert(tx.
vout.begin() + nChangePosInOut, tx_new->vout[nChangePosInOut]);
2515 for (
unsigned int idx = 0; idx < tx.
vout.size(); idx++) {
2516 tx.
vout[idx].nValue = tx_new->vout[idx].nValue;
2520 for (
const CTxIn& txin : tx_new->vin) {
2522 tx.
vin.push_back(txin);
2548 for (
const auto& recipient : vecSend) {
2550 int witnessversion = 0;
2551 std::vector<unsigned char> witnessprogram;
2552 if (recipient.scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
2562 int& nChangePosInOut, std::string& strFailReason,
const CCoinControl& coin_control,
bool sign)
2565 int nChangePosRequest = nChangePosInOut;
2566 unsigned int nSubtractFeeFromAmount = 0;
2567 for (
const auto& recipient : vecSend)
2569 if (nValue < 0 || recipient.nAmount < 0)
2571 strFailReason =
_(
"Transaction amounts must not be negative");
2574 nValue += recipient.nAmount;
2576 if (recipient.fSubtractFeeFromAmount)
2577 nSubtractFeeFromAmount++;
2579 if (vecSend.empty())
2581 strFailReason =
_(
"Transaction must have at least one recipient");
2617 assert(txNew.
nLockTime < LOCKTIME_THRESHOLD);
2622 std::set<CInputCoin> setCoins;
2625 std::vector<COutput> vAvailableCoins;
2635 if (!boost::get<CNoDestination>(&coin_control.
destChange)) {
2647 strFailReason =
_(
"Can't generate a change-address key. Private keys are disabled for this wallet.");
2655 strFailReason =
_(
"Keypool ran out, please call keypoolrefill first");
2664 CTxOut change_prototype_txout(0, scriptChange);
2673 bool pick_new_inputs =
true;
2682 nChangePosInOut = nChangePosRequest;
2687 CAmount nValueToSelect = nValue;
2688 if (nSubtractFeeFromAmount == 0)
2689 nValueToSelect += nFeeRet;
2693 for (
const auto& recipient : vecSend)
2695 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
2697 if (recipient.fSubtractFeeFromAmount)
2699 assert(nSubtractFeeFromAmount != 0);
2700 txout.
nValue -= nFeeRet / nSubtractFeeFromAmount;
2705 txout.
nValue -= nFeeRet % nSubtractFeeFromAmount;
2713 if (recipient.fSubtractFeeFromAmount && nFeeRet > 0)
2716 strFailReason =
_(
"The transaction amount is too small to pay the fee");
2718 strFailReason =
_(
"The transaction amount is too small to send after the fee has been deducted");
2721 strFailReason =
_(
"Transaction amount too small");
2724 txNew.
vout.push_back(txout);
2729 if (pick_new_inputs) {
2742 strFailReason =
_(
"Insufficient funds");
2750 const CAmount nChange = nValueIn - nValueToSelect;
2754 CTxOut newTxOut(nChange, scriptChange);
2759 if (
IsDust(newTxOut, discard_rate) || bnb_used)
2761 nChangePosInOut = -1;
2766 if (nChangePosInOut == -1)
2771 else if ((
unsigned int)nChangePosInOut > txNew.
vout.size())
2773 strFailReason =
_(
"Change index out of range");
2777 std::vector<CTxOut>::iterator position = txNew.
vout.begin()+nChangePosInOut;
2778 txNew.
vout.insert(position, newTxOut);
2781 nChangePosInOut = -1;
2786 for (
const auto& coin : setCoins) {
2792 strFailReason =
_(
"Signing transaction failed");
2799 strFailReason =
_(
"Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable -fallbackfee.");
2807 strFailReason =
_(
"Transaction too large for fee policy");
2811 if (nFeeRet >= nFeeNeeded) {
2822 if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 && pick_new_inputs) {
2826 if (nFeeRet >= fee_needed_with_change + minimum_value_for_change) {
2827 pick_new_inputs =
false;
2828 nFeeRet = fee_needed_with_change;
2834 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2835 CAmount extraFeePaid = nFeeRet - nFeeNeeded;
2836 std::vector<CTxOut>::iterator change_position = txNew.
vout.begin()+nChangePosInOut;
2837 change_position->nValue += extraFeePaid;
2838 nFeeRet -= extraFeePaid;
2842 else if (!pick_new_inputs) {
2847 strFailReason =
_(
"Transaction fee and change calculation failed");
2852 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
2853 CAmount additionalFeeNeeded = nFeeNeeded - nFeeRet;
2854 std::vector<CTxOut>::iterator change_position = txNew.
vout.begin()+nChangePosInOut;
2856 if (change_position->nValue >= MIN_FINAL_CHANGE + additionalFeeNeeded) {
2857 change_position->nValue -= additionalFeeNeeded;
2858 nFeeRet += additionalFeeNeeded;
2865 if (nSubtractFeeFromAmount > 0) {
2866 pick_new_inputs =
false;
2870 nFeeRet = nFeeNeeded;
2876 if (nChangePosInOut == -1) reservekey.
ReturnKey();
2880 std::vector<CInputCoin> selected_coins(setCoins.begin(), setCoins.end());
2881 std::shuffle(selected_coins.begin(), selected_coins.end(),
FastRandomContext());
2892 for (
const auto& coin : selected_coins) {
2899 for (
const auto& coin : selected_coins)
2901 const CScript& scriptPubKey = coin.txout.scriptPubKey;
2906 strFailReason =
_(
"Signing transaction failed");
2917 tx = MakeTransactionRef(std::move(txNew));
2920 if (GetTransactionWeight(*tx) > MAX_STANDARD_TX_WEIGHT)
2922 strFailReason =
_(
"Transaction too large");
2927 if (
gArgs.
GetBoolArg(
"-walletrejectlongchains", DEFAULT_WALLET_REJECT_LONG_CHAINS)) {
2932 size_t nLimitAncestors =
gArgs.
GetArg(
"-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
2933 size_t nLimitAncestorSize =
gArgs.
GetArg(
"-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
2934 size_t nLimitDescendants =
gArgs.
GetArg(
"-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
2935 size_t nLimitDescendantSize =
gArgs.
GetArg(
"-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
2936 std::string errString;
2939 strFailReason =
_(
"Transaction has too long of a mempool chain");
2944 WalletLogPrintf(
"Fee Calculation: Fee:%d Bytes:%u Needed:%d Tgt:%d (requested %d) Reason:\"%s\" Decay %.5f: Estimation: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out) Fail: (%g - %g) %.2f%% %.1f/(%.1f %d mem %.1f out)\n",
2964 wtxNew.
mapValue = std::move(mapValue);
2979 for (
const CTxIn& txin : wtxNew.
tx->vin)
3009 fFirstRunRet =
false;
3016 setExternalKeyPool.clear();
3031 return nLoadWalletRet;
3040 for (
uint256 hash : vHashOut) {
3041 const auto& it = mapWallet.find(hash);
3042 wtxOrdered.erase(it->second.m_it_wtxOrdered);
3043 mapWallet.erase(it);
3051 setExternalKeyPool.clear();
3060 return nZapSelectTxRet;
3077 setExternalKeyPool.clear();
3086 return nZapWalletTxRet;
3094 bool fUpdated =
false;
3097 std::map<CTxDestination, CAddressBookData>::iterator mi =
mapAddressBook.find(address);
3100 if (!strPurpose.empty())
3117 for (
const std::pair<const std::string, std::string> &item :
mapAddressBook[address].destdata)
3136 return mi->second.name;
3141 const static std::string DEFAULT_LABEL_NAME;
3142 return DEFAULT_LABEL_NAME;
3163 for (
const int64_t nIndex : setExternalKeyPool) {
3166 setExternalKeyPool.clear();
3197 setExternalKeyPool.insert(nIndex);
3199 m_max_keypool_index = std::max(m_max_keypool_index, nIndex);
3206 if (mapKeyMetadata.count(keyid) == 0)
3222 unsigned int nTargetSize;
3224 nTargetSize = kpSize;
3226 nTargetSize = std::max(
gArgs.
GetArg(
"-keypool", DEFAULT_KEYPOOL_SIZE), (int64_t) 0);
3230 int64_t missingExternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)setExternalKeyPool.size(), (int64_t) 0);
3231 int64_t missingInternal = std::max(std::max((int64_t) nTargetSize, (int64_t) 1) - (int64_t)
setInternalKeyPool.size(), (int64_t) 0);
3236 missingInternal = 0;
3238 bool internal =
false;
3240 for (int64_t i = missingInternal + missingExternal; i--;)
3242 if (i < missingInternal) {
3246 assert(m_max_keypool_index < std::numeric_limits<int64_t>::max());
3247 int64_t index = ++m_max_keypool_index;
3251 throw std::runtime_error(std::string(__func__) +
": writing generated key failed");
3257 setExternalKeyPool.insert(index);
3261 if (missingInternal + missingExternal > 0) {
3283 if (setKeyPool.empty()) {
3289 auto it = setKeyPool.begin();
3291 setKeyPool.erase(it);
3292 if (!batch.
ReadPool(nIndex, keypool)) {
3293 throw std::runtime_error(std::string(__func__) +
": read failed");
3296 throw std::runtime_error(std::string(__func__) +
": unknown key in key pool");
3299 if (use_split_keypool && keypool.
fInternal != fReturningInternal) {
3300 throw std::runtime_error(std::string(__func__) +
": keypool entry misclassified");
3303 throw std::runtime_error(std::string(__func__) +
": keypool entry invalid");
3330 setExternalKeyPool.insert(nIndex);
3359 static int64_t GetOldestKeyTimeInPool(
const std::set<int64_t>& setKeyPool,
WalletBatch& batch) {
3360 if (setKeyPool.empty()) {
3365 int64_t nIndex = *(setKeyPool.begin());
3366 if (!batch.
ReadPool(nIndex, keypool)) {
3367 throw std::runtime_error(std::string(__func__) +
": read oldest key in keypool failed");
3370 return keypool.
nTime;
3380 int64_t oldestKey = GetOldestKeyTimeInPool(setExternalKeyPool, batch);
3393 std::map<CTxDestination, CAmount> balances;
3397 for (
const auto& walletEntry : mapWallet)
3399 const CWalletTx *pcoin = &walletEntry.second;
3411 for (
unsigned int i = 0; i < pcoin->
tx->vout.size(); i++)
3421 if (!balances.count(addr))
3423 balances[addr] += n;
3434 std::set< std::set<CTxDestination> > groupings;
3435 std::set<CTxDestination> grouping;
3437 for (
const auto& walletEntry : mapWallet)
3439 const CWalletTx *pcoin = &walletEntry.second;
3441 if (pcoin->
tx->vin.size() > 0)
3443 bool any_mine =
false;
3445 for (
const CTxIn& txin : pcoin->
tx->vin)
3452 grouping.insert(address);
3459 for (
const CTxOut& txout : pcoin->
tx->vout)
3465 grouping.insert(txoutAddr);
3468 if (grouping.size() > 0)
3470 groupings.insert(grouping);
3476 for (
const auto& txout : pcoin->
tx->vout)
3482 grouping.insert(address);
3483 groupings.insert(grouping);
3488 std::set< std::set<CTxDestination>* > uniqueGroupings;
3489 std::map< CTxDestination, std::set<CTxDestination>* > setmap;
3490 for (std::set<CTxDestination> _grouping : groupings)
3493 std::set< std::set<CTxDestination>* > hits;
3494 std::map< CTxDestination, std::set<CTxDestination>* >::iterator it;
3496 if ((it = setmap.find(address)) != setmap.end())
3497 hits.insert((*it).second);
3500 std::set<CTxDestination>* merged =
new std::set<CTxDestination>(_grouping);
3501 for (std::set<CTxDestination>* hit : hits)
3503 merged->insert(hit->begin(), hit->end());
3504 uniqueGroupings.erase(hit);
3507 uniqueGroupings.insert(merged);
3511 setmap[element] = merged;
3514 std::set< std::set<CTxDestination> >
ret;
3515 for (
const std::set<CTxDestination>* uniqueGrouping : uniqueGroupings)
3517 ret.insert(*uniqueGrouping);
3518 delete uniqueGrouping;
3527 std::set<CTxDestination> result;
3528 for (
const std::pair<const CTxDestination, CAddressBookData>& item :
mapAddressBook)
3531 const std::string& strName = item.second.name;
3532 if (strName == label)
3533 result.insert(address);
3575 if (!
internal) assert(setExternalKeyPool.count(keypool_id) ||
set_pre_split_keypool.count(keypool_id));
3577 auto it = setKeyPool->begin();
3580 while (it !=
std::end(*setKeyPool)) {
3581 const int64_t& index = *(it);
3582 if (index > keypool_id)
break;
3585 if (batch.
ReadPool(index, keypool)) {
3591 it = setKeyPool->erase(it);
3597 std::shared_ptr<CReserveKey> rKey = std::make_shared<CReserveKey>(
this);
3599 if (!rKey->GetReservedKey(pubkey))
3609 setLockedCoins.insert(output);
3615 setLockedCoins.erase(output);
3621 setLockedCoins.clear();
3629 return (setLockedCoins.count(outpt) > 0);
3635 for (std::set<COutPoint>::iterator it = setLockedCoins.begin();
3636 it != setLockedCoins.end(); it++) {
3638 vOutpts.push_back(outpt);
3646 mapKeyBirth.clear();
3649 for (
const auto& entry : mapKeyMetadata) {
3650 if (entry.second.nCreateTime) {
3651 mapKeyBirth[entry.first] = entry.second.nCreateTime;
3657 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
3659 if (mapKeyBirth.count(keyid) == 0)
3660 mapKeyFirstBlock[keyid] = pindexMax;
3664 if (mapKeyFirstBlock.empty())
3668 std::vector<CKeyID> vAffected;
3669 for (
const auto& entry : mapWallet) {
3675 int nHeight = pindex->
nHeight;
3676 for (
const CTxOut &txout : wtx.
tx->vout) {
3679 for (
const CKeyID &keyid : vAffected) {
3681 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
3682 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
3683 rit->second = pindex;
3691 for (
const auto& entry : mapKeyFirstBlock)
3692 mapKeyBirth[entry.first] = entry.second->
GetBlockTime() - TIMESTAMP_WINDOW;
3722 int64_t latestEntry = 0;
3725 int64_t latestTolerated = latestNow + 300;
3727 for (
auto it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) {
3737 if (nSmartTime <= latestTolerated) {
3738 latestEntry = nSmartTime;
3739 if (nSmartTime > latestNow) {
3740 latestNow = nSmartTime;
3746 int64_t blocktime = pindex->GetBlockTime();
3747 nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow));
3757 if (boost::get<CNoDestination>(&dest))
3760 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3773 mapAddressBook[dest].destdata.insert(std::make_pair(key, value));
3778 std::map<CTxDestination, CAddressBookData>::const_iterator i =
mapAddressBook.find(dest);
3781 CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key);
3782 if(j != i->second.destdata.end())
3795 std::vector<std::string> values;
3797 for (
const auto& data : address.second.destdata) {
3799 values.emplace_back(data.second);
3809 for (
auto it = setExternalKeyPool.begin(); it != setExternalKeyPool.end();) {
3810 int64_t index = *it;
3812 if (!batch.
ReadPool(index, keypool)) {
3813 throw std::runtime_error(std::string(__func__) +
": read keypool entry failed");
3817 throw std::runtime_error(std::string(__func__) +
": writing modified keypool entry failed");
3820 it = setExternalKeyPool.erase(it);
3824 bool CWallet::Verify(std::string wallet_file,
bool salvage_wallet, std::string& error_string, std::string& warning_string)
3833 fs::path wallet_path = fs::absolute(wallet_file,
GetWalletDir());
3834 fs::file_type path_type = fs::symlink_status(wallet_path).type();
3835 if (!(path_type == fs::file_not_found || path_type == fs::directory_file ||
3836 (path_type == fs::symlink_file && fs::is_directory(wallet_path)) ||
3837 (path_type == fs::regular_file && fs::path(wallet_file).filename() == wallet_file))) {
3839 "Invalid -wallet path '%s'. -wallet path should point to a directory where wallet.dat and " 3840 "database/log.?????????? files can be stored, a location where such a directory could be created, " 3841 "or (for backwards compatibility) the name of an existing data file in -walletdir (%s)",
3849 error_string =
strprintf(
"Error loading wallet %s. Duplicate -wallet filename specified.", wallet_file);
3858 }
catch (
const fs::filesystem_error& e) {
3863 if (salvage_wallet) {
3866 std::string backup_filename;
3877 const std::string& walletFile =
name;
3880 std::vector<CWalletTx> vWtx;
3883 uiInterface.InitMessage(
_(
"Zapping all transactions from wallet..."));
3886 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
3896 bool fFirstRun =
true;
3900 DBErrors nLoadWalletRet = walletInstance->LoadWallet(fFirstRun);
3910 " or address book entries might be missing or incorrect."),
3928 int prev_version = walletInstance->nWalletVersion;
3931 int nMaxVersion =
gArgs.
GetArg(
"-upgradewallet", 0);
3932 if (nMaxVersion == 0)
3934 walletInstance->WalletLogPrintf(
"Performing wallet upgrade to %i\n",
FEATURE_LATEST);
3939 walletInstance->WalletLogPrintf(
"Allowing wallet upgrade up to %i\n", nMaxVersion);
3940 if (nMaxVersion < walletInstance->
GetVersion())
3945 walletInstance->SetMaxVersion(nMaxVersion);
3950 LOCK(walletInstance->cs_wallet);
3953 int max_version = walletInstance->nWalletVersion;
3955 InitError(
_(
"Cannot upgrade a non HD split wallet without upgrading to support pre split keypool. Please use -upgradewallet=169900 or -upgradewallet with no version specified."));
3959 bool hd_upgrade =
false;
3960 bool split_upgrade =
false;
3961 if (walletInstance->CanSupportFeature(
FEATURE_HD) && !walletInstance->IsHDEnabled()) {
3962 walletInstance->WalletLogPrintf(
"Upgrading wallet to HD\n");
3966 CPubKey masterPubKey = walletInstance->GenerateNewSeed();
3967 walletInstance->SetHDSeed(masterPubKey);
3972 walletInstance->WalletLogPrintf(
"Upgrading wallet to use HD chain split\n");
3977 if (split_upgrade) {
3978 walletInstance->MarkPreSplitKeys();
3982 if (!walletInstance->TopUpKeyPool()) {
3999 CPubKey seed = walletInstance->GenerateNewSeed();
4000 walletInstance->SetHDSeed(seed);
4005 InitError(
_(
"Unable to generate initial keys"));
4012 InitError(
strprintf(
_(
"Error loading %s: Private keys can only be disabled during creation"), walletFile));
4015 LOCK(walletInstance->cs_KeyStore);
4016 if (!walletInstance->mapKeys.empty() || !walletInstance->mapCryptedKeys.empty()) {
4017 InitWarning(
strprintf(
_(
"Warning: Private keys detected in wallet {%s} with disabled private keys"), walletFile));
4037 if (n > HIGH_TX_FEE_PER_KB) {
4039 _(
"This is the minimum transaction fee you pay on every transaction."));
4041 walletInstance->m_min_fee =
CFeeRate(n);
4051 if (nFeePerK > HIGH_TX_FEE_PER_KB) {
4053 _(
"This is the transaction fee you may pay when fee estimates are not available."));
4055 walletInstance->m_fallback_fee =
CFeeRate(nFeePerK);
4056 walletInstance->m_allow_fallback_fee = nFeePerK != 0;
4064 if (nFeePerK > HIGH_TX_FEE_PER_KB) {
4066 _(
"This is the transaction fee you may discard if change is smaller than dust at this level"));
4068 walletInstance->m_discard_rate =
CFeeRate(nFeePerK);
4076 if (nFeePerK > HIGH_TX_FEE_PER_KB) {
4078 _(
"This is the transaction fee you will pay if you send a transaction."));
4080 walletInstance->m_pay_tx_fee =
CFeeRate(nFeePerK, 1000);
4082 InitError(
strprintf(
_(
"Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
4087 walletInstance->m_confirm_target =
gArgs.
GetArg(
"-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
4088 walletInstance->m_spend_zero_conf_change =
gArgs.
GetBoolArg(
"-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
4089 walletInstance->m_signal_rbf =
gArgs.
GetBoolArg(
"-walletrbf", DEFAULT_WALLET_RBF);
4091 walletInstance->WalletLogPrintf(
"Wallet completed loading in %15dms\n",
GetTimeMillis() - nStart);
4094 walletInstance->TopUpKeyPool();
4118 block = block->
pprev;
4120 if (pindexRescan != block) {
4121 InitError(
_(
"Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
4127 walletInstance->WalletLogPrintf(
"Rescanning last %i blocks (from block %i)...\n",
chainActive.
Height() - pindexRescan->
nHeight, pindexRescan->
nHeight);
4131 while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->
GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) {
4138 if (!reserver.reserve()) {
4139 InitError(
_(
"Failed to rescan the wallet during initialization"));
4142 walletInstance->ScanForWalletTransactions(pindexRescan,
nullptr, reserver,
true);
4144 walletInstance->WalletLogPrintf(
"Rescan completed in %15dms\n",
GetTimeMillis() - nStart);
4146 walletInstance->database->IncrementUpdateCounter();
4155 uint256 hash = wtxOld.GetHash();
4156 std::map<uint256, CWalletTx>::iterator mi = walletInstance->mapWallet.find(hash);
4157 if (mi != walletInstance->mapWallet.end())
4178 walletInstance->SetBroadcastTransactions(
gArgs.
GetBoolArg(
"-walletbroadcast", DEFAULT_WALLETBROADCAST));
4181 walletInstance->WalletLogPrintf(
"setKeyPool.size() = %u\n", walletInstance->GetKeyPoolSize());
4182 walletInstance->WalletLogPrintf(
"mapWallet.size() = %u\n", walletInstance->mapWallet.size());
4183 walletInstance->WalletLogPrintf(
"mapAddressBook.size() = %u\n", walletInstance->mapAddressBook.size());
4186 return walletInstance;
4251 assert(chain_depth >= 0);
4252 return std::max(0, (COINBASE_MATURITY+1) - chain_depth);
4269 nullptr ,
false , nAbsurdFee);
4292 std::vector<OutputGroup> groups;
4293 std::map<CTxDestination, OutputGroup> gmap;
4295 for (
const auto& output : outputs) {
4296 if (output.fSpendable) {
4297 CInputCoin input_coin = output.GetInputCoin();
4299 size_t ancestors, descendants;
4301 if (!single_coin &&
ExtractDestination(output.tx->tx->vout[output.i].scriptPubKey, dst)) {
4305 if (gmap[dst].m_outputs.size() >= OUTPUT_GROUP_MAX_ENTRIES) {
4306 groups.push_back(gmap[dst]);
4309 gmap[dst].Insert(input_coin, output.nDepth, output.tx->IsFromMe(
ISMINE_ALL), ancestors, descendants);
4311 groups.emplace_back(input_coin, output.nDepth, output.tx->IsFromMe(
ISMINE_ALL), ancestors, descendants);
4316 for (
const auto& it : gmap) groups.push_back(it.second);
4326 auto it = mapKeyMetadata.find(keyID);
4327 if (it != mapKeyMetadata.end()) {
bool IsEquivalentTo(const CWalletTx &tx) const
void MarkReserveKeysAsUsed(int64_t keypool_id) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Marks all keys in the keypool up to and including reserve_key as used.
static std::unique_ptr< BerkeleyDatabase > CreateDummy()
Return object for accessing dummy database with no read/write capabilities.
bool WriteName(const std::string &strAddress, const std::string &strName)
int64_t GetVirtualTransactionSize(int64_t nWeight, int64_t nSigOpCost)
Compute the virtual transaction size (weight reinterpreted as bytes).
bool EraseDestData(const std::string &address, const std::string &key)
Erase destination data tuple from wallet database.
bool SetKeyFromPassphrase(const SecureString &strKeyData, const std::vector< unsigned char > &chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
CAmount GetMinimumFee(const CWallet &wallet, unsigned int nTxBytes, const CCoinControl &coin_control, const CTxMemPool &pool, const CBlockPolicyEstimator &estimator, FeeCalculation *feeCalc)
Estimate the minimum fee considering user set parameters and the required fee.
void LoadKeyPool(int64_t nIndex, const CKeyPool &keypool) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
void SetTx(CTransactionRef arg)
static const uint256 ABANDON_HASH
Constant used in hashBlock to indicate tx has been abandoned.
unsigned char fingerprint[4]
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
std::unique_ptr< WalletDatabase > database
Internal database handle.
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
OutputType m_default_change_type
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized OpenSSL private key data).
bool RelayWalletTransaction(CConnman *connman) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void SetMerkleBranch(const CBlockIndex *pIndex, int posInBlock)
CAmount nImmatureWatchCreditCached
void BindWallet(CWallet *pwalletIn)
unsigned int nDerivationMethod
0 = EVP_sha512() 1 = scrypt()
void LoadDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
Adds a destination data tuple to the store, without saving it to disk.
bool ErasePurpose(const std::string &strAddress)
std::set< std::set< CTxDestination > > GetAddressGroupings() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
bool fPruneMode
True if we're running in -prune mode.
CAmount GetAvailableCredit(bool fUseCache=true, const isminefilter &filter=ISMINE_SPENDABLE) const NO_THREAD_SAFETY_ANALYSIS
const CWalletTx * GetWalletTx(const uint256 &hash) const
CAmount GetImmatureBalance() const
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
int64_t GetOldestKeyPoolTime()
bool fAllowWatchOnly
Includes watch only addresses which are solvable.
bool ReadBestBlock(CBlockLocator &locator)
static bool Verify(std::string wallet_file, bool salvage_wallet, std::string &error_string, std::string &warning_string)
Verify wallet naming and perform salvage on the wallet if required.
std::map< std::string, std::string > mapValue_t
bool CanSupportFeature(enum WalletFeature wf) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
check whether we are allowed to upgrade (or already support) to the named feature ...
bool HaveKey(const CKeyID &address) const override
Check whether a key corresponding to a given address is present in the store.
void AvailableCoins(std::vector< COutput > &vCoins, bool fOnlySafe=true, const CCoinControl *coinControl=nullptr, const CAmount &nMinimumAmount=1, const CAmount &nMaximumAmount=MAX_MONEY, const CAmount &nMinimumSumAmount=MAX_MONEY, const uint64_t nMaximumCount=0, const int nMinDepth=0, const int nMaxDepth=9999999) const EXCLUSIVE_LOCKS_REQUIRED(cs_main
populate vCoins with vector of available COutputs.
void Process(const CScript &script)
Apply the visitor to each destination in a script, recursively to the redeemscript in the case of p2s...
int64_t GetBlockTime() const
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, const CKeyMetadata &keyMeta)
const unsigned int WALLET_CRYPTO_KEY_SIZE
CBlockIndex * pprev
pointer to the index of the predecessor of this block
bool Encrypt(const CKeyingMaterial &vchPlaintext, std::vector< unsigned char > &vchCiphertext) const
void UnlockCoin(const COutPoint &output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
std::shared_ptr< CWallet > GetWallet(const std::string &name)
void postInitProcess()
Wallet post-init setup Gives the wallet a chance to register repetitive tasks and complete post-init ...
void GetKeyBirthTimes(std::map< CTxDestination, int64_t > &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
CAmount GetAvailableBalance(const CCoinControl *coinControl=nullptr) const
char fFromMe
From me flag is set to 1 for transactions that were created by the wallet on this bitcoin node...
bool Derive(CExtKey &out, unsigned int nChild) const
size_t change_output_size
boost::optional< unsigned int > m_confirm_target
Override the default confirmation target if set.
void SetHDChain(const CHDChain &chain, bool memonly)
std::map< CTxDestination, CAddressBookData > mapAddressBook
std::vector< std::string > GetDestValues(const std::string &prefix) const
Get all destination values matching a prefix.
bool AddWallet(const std::shared_ptr< CWallet > &wallet)
Encryption/decryption context with key information.
const uint256 & GetHash() const
bool IsFromMe(const isminefilter &filter) const
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
CAmount maxTxFee
Absolute maximum transaction fee (in satoshis) used by wallet and mempool (rejects high fee in sendra...
const CTxOut & FindNonChangeParentOutput(const CTransaction &tx, int output) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Find non-change parent output.
CPubKey GetPubKey() const
Compute the public key from a private key.
bool IsFromMe(const CTransaction &tx) const
should probably be renamed to IsRelevantToMe
bool DummySignTx(CMutableTransaction &txNew, const std::set< CTxOut > &txouts, bool use_max_sig=false) const
std::vector< unsigned char > vchCryptedKey
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut)
bool WriteMinVersion(int nVersion)
bool fImmatureCreditCached
CCriticalSection cs_KeyStore
bool AddToWalletIfInvolvingMe(const CTransactionRef &tx, const CBlockIndex *pIndex, int posInBlock, bool fUpdate) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Add a transaction to the wallet, or update it.
UniValue ret(UniValue::VARR)
bool WriteHDChain(const CHDChain &chain)
write the hdchain model (external chain child index counter)
bool SelectCoinsBnB(std::vector< OutputGroup > &utxo_pool, const CAmount &target_value, const CAmount &cost_of_change, std::set< CInputCoin > &out_set, CAmount &value_ret, CAmount not_input_fees)
static const uint32_t SEQUENCE_FINAL
bool SelectCoinsMinConf(const CAmount &nTargetValue, const CoinEligibilityFilter &eligibility_filter, std::vector< OutputGroup > groups, std::set< CInputCoin > &setCoinsRet, CAmount &nValueRet, const CoinSelectionParams &coin_selection_params, bool &bnb_used) const
Shuffle and select coins until nTargetValue is reached while avoiding small change; This method is st...
CAmount GetDebit(const isminefilter &filter) const
filter decides which addresses will count towards the debit
Private key encryption is done based on a CMasterKey, which holds a salt and random encryption key...
void ListSelected(std::vector< COutPoint > &vOutpoints) const
void ReacceptWalletTransactions()
bool MoneyRange(const CAmount &nValue)
bool FundTransaction(CMutableTransaction &tx, CAmount &nFeeRet, int &nChangePosInOut, std::string &strFailReason, bool lockUnspents, const std::set< int > &setSubtractFeeFromOutputs, CCoinControl)
Insert additional inputs into the transaction by calling CreateTransaction();.
int Height() const
Return the maximal height in the chain.
bool CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector< std::pair< std::string, std::string >> orderForm, CReserveKey &reservekey, CConnman *connman, CValidationState &state)
Call after CreateTransaction unless you want to abort.
bool WriteWatchOnly(const CScript &script, const CKeyMetadata &keymeta)
size_t KeypoolCountExternalKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
const BaseSignatureCreator & DUMMY_SIGNATURE_CREATOR
A signature creator that just produces 71-byte empty signatures.
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
bool m_spend_zero_conf_change
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
int64_t nOrderPos
position in ordered transaction list
void LoadToWallet(const CWalletTx &wtxIn) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
std::multimap< int64_t, CWalletTx * >::const_iterator m_it_wtxOrdered
std::set< int64_t > setInternalKeyPool
static bool VerifyDatabaseFile(const fs::path &wallet_path, std::string &warningStr, std::string &errorStr)
bool AddCScript(const CScript &redeemScript) override
Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki.
std::string StringForFeeReason(FeeReason reason)
bool RemoveWatchOnly(const CScript &dest) override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
void GetStrongRandBytes(unsigned char *out, int num)
Function to gather random data from multiple sources, failing whenever any of those sources fail to p...
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
bool SetMaxVersion(int nVersion)
change which version we're allowed to upgrade to (note that this does not immediately imply upgrading...
boost::optional< OutputType > m_change_type
Override the default change type if set, ignored if destChange is set.
const BaseSignatureCreator & DUMMY_MAXIMUM_SIGNATURE_CREATOR
A signature creator that just produces 72-byte empty signatures.
std::set< txiter, CompareIteratorByHash > setEntries
bool EncryptKeys(CKeyingMaterial &vMasterKeyIn)
will encrypt previously unencrypted keys
void insert(Tdst &dst, const Tsrc &src)
Simplification of std insertion.
uint8_t isminefilter
used for bitflags of isminetype
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
bool IsTrusted() const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
uint32_t nExternalChainCounter
bool IsWalletFlagSet(uint64_t flag)
check if a certain wallet flag is set
WalletFeature
(client) version numbers for particular wallet features
CAmount GetLegacyBalance(const isminefilter &filter, int minDepth) const
std::map< CKeyID, int64_t > m_pool_key_to_index
void MarkDirty()
make sure balances are recalculated
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
std::vector< std::shared_ptr< CWallet > > GetWallets()
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
bool Decrypt(const std::vector< unsigned char > &vchCiphertext, CKeyingMaterial &vchPlaintext) const
bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const override
Implement lookup of key origin information through wallet key metadata.
DBErrors ZapWalletTx(std::vector< CWalletTx > &vWtx)
A signature creator for transactions.
CWalletKey(int64_t nExpires=0)
todo: add something to note what created it (user, getnewaddress, change) maybe should have a map<str...
bool WriteTx(const CWalletTx &wtx)
int64_t GetVirtualTransactionInputSize(const CTxIn &txin, int64_t nSigOpCost)
DBErrors LoadWallet(CWallet *pwallet)
virtual bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
std::atomic< bool > fAbortRescan
const unsigned char * begin() const
bool MarkReplaced(const uint256 &originalHash, const uint256 &newHash)
Mark a transaction as replaced by another transaction (e.g., BIP 125).
DBErrors
Error statuses for the wallet database.
CAmount nWatchDebitCached
CAmount GetUnconfirmedWatchOnlyBalance() const
bool EncryptWallet(const SecureString &strWalletPassphrase)
const CBlockIndex * m_last_block_processed
The following is used to keep track of how far behind the wallet is from the chain sync...
bool GetDestData(const CTxDestination &dest, const std::string &key, std::string *value) const
Look up a destination data tuple in the store, return true if found false otherwise.
std::shared_ptr< const CTransaction > CTransactionRef
bool WriteWalletFlags(const uint64_t flags)
bool fAvailableCreditCached
bool IsChange(const CTxOut &txout) const
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
CAmount GetImmatureWatchOnlyCredit(const bool fUseCache=true) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void DeriveNewChildKey(WalletBatch &batch, CKeyMetadata &metadata, CKey &secret, bool internal=false) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
static bool Recover(const fs::path &wallet_path, void *callbackDataIn, bool(*recoverKVcallback)(void *callbackData, CDataStream ssKey, CDataStream ssValue), std::string &out_backup_filename)
void PushInventory(const CInv &inv)
bool LoadCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
Adds an encrypted key to the store, without saving it to disk (used by LoadWallet) ...
void operator()(const X &none)
const std::vector< CTxIn > vin
static std::shared_ptr< CWallet > CreateWalletFromFile(const std::string &name, const fs::path &path, uint64_t wallet_creation_flags=0)
size_t GetSerializeSize(const T &t, int nVersion=0)
std::string ToString() const
void BlockDisconnected(const std::shared_ptr< const CBlock > &pblock) override
Notifies listeners of a block being disconnected.
bool EraseWatchOnly(const CScript &script)
Access to the wallet database.
bool IsUnspendable() const
Returns whether the script is guaranteed to fail at execution, regardless of the initial stack...
mapValue_t mapValue
Key/value map with information about the transaction.
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
bool ExtractDestinations(const CScript &scriptPubKey, txnouttype &typeRet, std::vector< CTxDestination > &addressRet, int &nRequiredRet)
Parse a standard scriptPubKey with one or more destination addresses.
void KeepKey(int64_t nIndex)
int64_t CAmount
Amount in satoshis (Can be negative)
bool m_avoid_partial_spends
Avoid partial use of funds sent to a given address.
bool WriteBestBlock(const CBlockLocator &locator)
void ResendWalletTransactions(int64_t nBestBlockTime, CConnman *connman) override EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Tells listeners to broadcast their data.
bool fAvailableWatchCreditCached
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Add a key to the store.
uint256 GetBlockHash() const
boost::signals2::signal< void(CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
#define AssertLockHeld(cs)
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
CBlockPolicyEstimator feeEstimator
const uint32_t BIP32_HARDENED_KEY_LIMIT
void MarkConflicted(const uint256 &hashBlock, const uint256 &hashTx)
DBErrors ReorderTransactions()
boost::signals2::signal< void(CCryptoKeyStore *wallet)> NotifyStatusChanged
Wallet status (encrypted, locked) changed.
bool IsLockedCoin(uint256 hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
bool DelAddressBook(const CTxDestination &address)
bool WriteDestData(const std::string &address, const std::string &key, const std::string &value)
Write destination data key,value tuple to database.
bool SelectCoins(const std::vector< COutput > &vAvailableCoins, const CAmount &nTargetValue, std::set< CInputCoin > &setCoinsRet, CAmount &nValueRet, const CCoinControl &coin_control, CoinSelectionParams &coin_selection_params, bool &bnb_used) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Select a set of coins such that nValueRet >= nTargetValue and at least all coins from coinControl are...
bool DummySignInput(CTxIn &tx_in, const CTxOut &txout, bool use_max_sig=false) const
A class to identify which pubkeys a script and a keystore have in common.
unsigned int nMasterKeyMaxID
bool CheckFinalTx(const CTransaction &tx, int flags)
Transaction validation functions.
void SyncTransaction(const CTransactionRef &tx, const CBlockIndex *pindex=nullptr, int posInBlock=0, bool update_tx=true) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
unsigned int ComputeTimeSmart(const CWalletTx &wtx) const
Compute smart timestamp for a transaction being added to the wallet.
CAmount GetBalance(const isminefilter &filter=ISMINE_SPENDABLE, const int min_depth=0) const
void GetAmounts(std::list< COutputEntry > &listReceived, std::list< COutputEntry > &listSent, CAmount &nFee, const isminefilter &filter) const
int GetDepthInMainChain() const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Return depth of transaction in blockchain: <0 : conflicts with a transaction this deep in the blockch...
bool AbandonTransaction(const uint256 &hashTx)
DBErrors LoadWallet(bool &fFirstRunRet)
bool AddKeyPubKeyWithDB(WalletBatch &batch, const CKey &key, const CPubKey &pubkey) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
CAmount GetCredit(const isminefilter &filter) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void TransactionAddedToMempool(const CTransactionRef &tx) override
Notifies listeners of a transaction having been added to mempool.
bool ParseHDKeypath(const std::string &keypath_str, std::vector< uint32_t > &keypath)
Parse an HD keypaths like "m/7/0'/2000".
void WalletLogPrintf(std::string fmt, Params... parameters) const
Prepends the wallet name in logging output to ease debugging in multi-wallet use cases.
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
bool NewKeyPool()
Mark old keypool keys as used, and generate all new keys.
void UpdateTimeFirstKey(int64_t nCreateTime) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Update wallet first key creation time.
static bool VerifyEnvironment(const fs::path &wallet_path, std::string &errorStr)
isminetype
IsMine() return codes.
An input of a transaction.
boost::variant< CNoDestination, CKeyID, CScriptID, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
OutputType m_default_address_type
bool AddCScript(const CScript &redeemScript) override
Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki.
int CalculateMaximumSignedInputSize(const CTxOut &txout, const CWallet *wallet, bool use_max_sig)
const uint256 & GetHash() const
int GetVersion()
get the current wallet format (the oldest client version guaranteed to understand this wallet) ...
CAmount GetImmatureCredit(bool fUseCache=true) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
int GetBlocksToMaturity() const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool HasWalletSpend(const uint256 &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Check if a given transaction has any of its outputs spent by another transaction in the wallet...
void LoadKeyMetadata(const CKeyID &keyID, const CKeyMetadata &metadata) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Load metadata (used by LoadWallet)
void operator()(const CScriptID &scriptId)
CTxDestination destChange
Custom change destination, if not set an address is generated.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
virtual bool HaveKey(const CKeyID &address) const =0
Check whether a key corresponding to a given address is present in the store.
std::set< uint256 > GetConflicts() const NO_THREAD_SAFETY_ANALYSIS
void Select(const COutPoint &output)
uint256 uint256S(const char *str)
CBlockIndex * FindEarliestAtLeast(int64_t nTime) const
Find the earliest block with timestamp equal or greater than the given.
An encapsulated public key.
bool fAllowOtherInputs
If false, allows unselected inputs, but requires all selected inputs be used.
bool Unlock(const CKeyingMaterial &vMasterKeyIn)
bool TransactionCanBeAbandoned(const uint256 &hashTx) const
Return whether transaction can be abandoned.
std::vector< OutputGroup > GroupOutputs(const std::vector< COutput > &outputs, bool single_coin) const
CBlockIndex * Next(const CBlockIndex *pindex) const
Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip...
void UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
void MakeNewKey(bool fCompressed)
Generate a new private key using a cryptographic PRNG.
const std::vector< CTxOut > vout
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Adds a key to the store, and saves it to disk.
CAmount GetUnconfirmedBalance() const
int64_t GetBlockTimeMax() const
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
std::map< CTxDestination, std::vector< COutput > > ListCoins() const EXCLUSIVE_LOCKS_REQUIRED(cs_main
Return list of available coins and locked coins grouped by non-change output address.
CAmount GetImmatureWatchOnlyBalance() const
void Flush(bool shutdown=false)
Flush wallet (bitdb flush)
bool EraseDestData(const CTxDestination &dest, const std::string &key)
Erases a destination data tuple in the store and on disk.
void ChainStateFlushed(const CBlockLocator &loc) override
Notifies listeners of the new active block chain on-disk.
CWallet(std::string name, std::unique_ptr< WalletDatabase > database)
Construct wallet with specified name and database implementation.
bool GetReservedKey(CPubKey &pubkey, bool internal=false)
bool SignTransaction(CMutableTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
bool ParseMoney(const std::string &str, CAmount &nRet)
bool GetKey(const CKeyID &address, CKey &keyOut) const override
unsigned int size() const
Simple read-only vector-like interface.
bool WriteOrderPosNext(int64_t nOrderPosNext)
An output of a transaction.
bool IsSpent(const uint256 &hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_main
Outpoint is spent if any non-conflicted transaction spends it:
CFeeRate GetMinimumFeeRate(const CWallet &wallet, const CCoinControl &coin_control, const CTxMemPool &pool, const CBlockPolicyEstimator &estimator, FeeCalculation *feeCalc)
Estimate the minimum fee rate considering user set parameters and the required fee.
std::string ToString() const
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
bool SetWalletFlags(uint64_t overwriteFlags, bool memOnly)
overwrite all flags by the given uint64_t returns false if unknown, non-tolerable flags are present ...
std::string AmountHighWarn(const std::string &optname)
bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents=true) const EXCLUSIVE_LOCKS_REQUIRED(cs)
Try to calculate all in-mempool ancestors of entry.
An outpoint - a combination of a transaction hash and an index n into its vout.
CCriticalSection cs_wallet
std::vector< CTxOut > vout
void TransactionRemovedFromMempool(const CTransactionRef &ptx) override
Notifies listeners of a transaction leaving mempool.
unsigned int fTimeReceivedIsTxTime
bool IsAllFromMe(const CTransaction &tx, const isminefilter &filter) const
Returns whether all of the inputs match the filter.
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
CAmount GetDustThreshold(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
void ForEachNode(Callable &&func)
Special output type for change outputs only.
bool RemoveWatchOnly(const CScript &dest) override
bool AcceptToMemoryPool(const CAmount &nAbsurdFee, CValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Pass this transaction to the mempool.
void SetSeed(const unsigned char *seed, unsigned int nSeedLen)
boost::optional< bool > m_signal_bip125_rbf
Override the wallet's m_signal_rbf if set.
bool AddToWallet(const CWalletTx &wtxIn, bool fFlushOnClose=true)
virtual bool GetCScript(const CScriptID &scriptid, CScript &script) const
static std::unique_ptr< BerkeleyDatabase > Create(const fs::path &path)
Return object for accessing database at specified path.
void AddToSpends(const COutPoint &outpoint, const uint256 &wtxid) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
void SyncMetaData(std::pair< TxSpends::iterator, TxSpends::iterator >) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
RAII object to check and reserve a wallet rescan.
A transaction with a bunch of additional info that only the owner cares about.
bool IsSolvable(const SigningProvider &provider, const CScript &script)
CRIPEMD160 & Write(const unsigned char *data, size_t len)
void ListLockedCoins(std::vector< COutPoint > &vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
void RegisterValidationInterface(CValidationInterface *pwalletIn)
Register a wallet to receive updates from core.
bool AddWatchOnly(const CScript &dest) override EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Private version of AddWatchOnly method which does not accept a timestamp, and which will reset the wa...
std::map< CTxDestination, CAmount > GetAddressBalances() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool GetBroadcastTransactions() const
Inquire whether this wallet broadcasts transactions.
bool fBroadcastTransactions
void BlockUntilSyncedToCurrentChain() LOCKS_EXCLUDED(cs_main
Blocks until the wallet state is up-to-date to /at least/ the current chain at the time this function...
CBlockIndex * ScanForWalletTransactions(CBlockIndex *pindexStart, CBlockIndex *pindexStop, const WalletRescanReserver &reserver, bool fUpdate=false)
Scan the block chain (starting in pindexStart) for transactions from or to us.
bool ErasePool(int64_t nPool)
int64_t IncOrderPosNext(WalletBatch *batch=nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Increment the next transaction order id.
void LockCoin(const COutPoint &output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
CPubKey DeriveNewSeed(const CKey &key)
bool CreateTransaction(const std::vector< CRecipient > &vecSend, CTransactionRef &tx, CReserveKey &reservekey, CAmount &nFeeRet, int &nChangePosInOut, std::string &strFailReason, const CCoinControl &coin_control, bool sign=true)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
bool IsInMainChain() const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool WritePool(int64_t nPool, const CKeyPool &keypool)
std::string get_filesystem_error_message(const fs::filesystem_error &e)
Capture information about block/transaction validation.
const unsigned int WALLET_CRYPTO_SALT_SIZE
CAmount nWatchCreditCached
void SetMinVersion(enum WalletFeature, WalletBatch *batch_in=nullptr, bool fExplicit=false)
signify that a particular wallet feature is now used. this may change nWalletVersion and nWalletMaxVe...
void GetScriptForMining(std::shared_ptr< CReserveScript > &script)
std::vector< CTransactionRef > vtx
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
const ChainTxData & TxData() const
bool InitError(const std::string &str)
Show error message.
CAmount nAvailableCreditCached
CoinSelectionParams coin_selection_params(false, 0, 0, CFeeRate(0), 0)
DBErrors ZapWalletTx(std::vector< CWalletTx > &vWtx)
boost::signals2::signal< void(CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, const std::string &purpose, ChangeType status)> NotifyAddressBookChanged
Address book entry changed.
CAmount GetDebit(const CTxIn &txin, const isminefilter &filter) const
Returns amount of debit if the input matches the filter, otherwise returns 0.
bool ChangeWalletPassphrase(const SecureString &strOldWalletPassphrase, const SecureString &strNewWalletPassphrase)
void SetWalletFlag(uint64_t flags)
set a single wallet flag
std::atomic< uint64_t > m_wallet_flags
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
MasterKeyMap mapMasterKeys
int64_t GetTxTime() const
A key allocated from the key pool.
The block chain is a tree shaped structure starting with the genesis block at the root...
const CChainParams & Params()
Return the currently selected parameters.
std::set< CTxDestination > GetLabelAddresses(const std::string &label) const
Serialized script, used inside transaction inputs and outputs.
CFeeRate GetDiscardRate(const CWallet &wallet, const CBlockPolicyEstimator &estimator)
Return the maximum feerate for discarding change.
bool IsSelected(const COutPoint &output) const
bool TopUpKeyPool(unsigned int kpSize=0)
bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret) override
Adds an encrypted key to the store, and saves it to disk.
unsigned int nTimeSmart
Stable timestamp that never changes, and reflects the order a transaction was added to the wallet...
std::set< int64_t > set_pre_split_keypool
void BlockConnected(const std::shared_ptr< const CBlock > &pblock, const CBlockIndex *pindex, const std::vector< CTransactionRef > &vtxConflicted) override
Notifies listeners of a block being connected.
double GuessVerificationProgress(const ChainTxData &data, const CBlockIndex *pindex)
Guess how far we are in the verification process at the given block index require cs_main if pindex h...
void SetHDSeed(const CPubKey &key)
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
A virtual base class for key stores.
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator)
Find the last common block between the parameter chain and a locator.
int64_t GetAdjustedTime()
void runCommand(const std::string &strCommand)
isminetype IsMine(const CKeyStore &keystore, const CScript &scriptPubKey)
CCriticalSection cs_wallets
A reference to a CKey: the Hash360 of its serialized public key.
void UpdateInput(CTxIn &input, const SignatureData &data)
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
void LearnRelatedScripts(const CPubKey &key, OutputType)
Explicitly make the wallet learn the related scripts for outputs to the given key.
std::string GetHex() const
std::set< uint256 > GetConflicts(const uint256 &txid) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get wallet transactions that conflict with given transaction (spend same outputs) ...
int nWalletVersion
the current wallet version: clients below this version are not able to load the wallet ...
bool RemoveWallet(const std::shared_ptr< CWallet > &wallet)
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
void operator()(const CKeyID &keyId)
Fee rate in satoshis per kilobyte: CAmount / kB.
void MarkInputsDirty(const CTransactionRef &tx) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
bool WritePurpose(const std::string &strAddress, const std::string &purpose)
CBlockLocator GetLocator(const CBlockIndex *pindex=nullptr) const
Return a CBlockLocator that refers to a block in this chain (by default the tip). ...
#define AssertLockNotHeld(cs)
bool LoadCScript(const CScript &redeemScript)
fs::path GetWalletDir()
Get the path of the wallet directory.
bool KnapsackSolver(const CAmount &nTargetValue, std::vector< OutputGroup > &groups, std::set< CInputCoin > &setCoinsRet, CAmount &nValueRet)
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
std::vector< unsigned char > vchSalt
CTxDestination GetDestinationForKey(const CPubKey &key, OutputType type)
Get a destination of the requested type (if possible) to the specified key.
void MarkPreSplitKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
bool ReadPool(int64_t nPool, CKeyPool &keypool)
bool ReserveKeyFromKeyPool(int64_t &nIndex, CKeyPool &keypool, bool fRequestedInternal)
Reserves a key from the keypool and sets nIndex to its index.
static const int VERSION_HD_CHAIN_SPLIT
std::vector< uint256 > ResendWalletTransactionsBefore(int64_t nTime, CConnman *connman) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
A reference to a CScript: the Hash360 of its serialization (see script.h)
bool GetKeyFromPool(CPubKey &key, bool internal=false)
std::vector< CKeyID > & vKeys
std::string EncodeDestination(const CTxDestination &dest)
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
A mutable version of CTransaction.
CAmount nAvailableWatchCreditCached
const std::string GetDisplayName() const
Returns a bracketed wallet name for displaying in logs, will return [default wallet] if the wallet ha...
void operator()(const WitnessV0ScriptHash &scriptID)
std::vector< std::shared_ptr< CWallet > > vpwallets GUARDED_BY(cs_wallets)
const std::string & GetLabelName(const CScript &scriptPubKey) const
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
std::string ToString() const
unsigned int nTimeReceived
time received by this node
void InitWarning(const std::string &str)
Show warning message.
An encapsulated private key.
bool IsFallbackFeeEnabled() const
Return true if the fallback fee is by default enabled for this network.
CClientUIInterface uiInterface
void LearnAllRelatedScripts(const CPubKey &key)
Same as LearnRelatedScripts, but when the OutputType is not known (and could be anything).
The basic transaction that is broadcasted on the network and contained in blocks. ...
int nHeight
height of the entry in the chain. The genesis block has height 0
void LoadScriptMetadata(const CScriptID &script_id, const CKeyMetadata &metadata) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
bool AddDestData(const CTxDestination &dest, const std::string &key, const std::string &value)
Adds a destination data tuple to the store, and saves it to disk.
Information about a peer.
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
CAmount GetCredit(const CTxOut &txout, const isminefilter &filter) const
bool HaveWatchOnly() const override
unsigned int nDeriveIterations
CBlockIndex * GetAncestor(int height)
Efficiently find an ancestor of this block.
full block available in blk*.dat
int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver &reserver, bool update)
Scan active chain for relevant transactions after importing keys.
isminetype IsMine(const CTxIn &txin) const
bool fImmatureWatchCreditCached
std::set< CKeyID > GetKeys() const override
CChain & chainActive
The currently-connected chain of blocks (protected by cs_main).
bool m_allow_fallback_fee
will be defined via chainparams
CKeyID seed_id
seed hash360
bool BackupWallet(const std::string &strDest)
std::string AmountErrMsg(const char *const optname, const std::string &strValue)
uint160 Hash360(const T1 pbegin, const T1 pend)
Compute the 160-bit hash an object.
std::vector< uint32_t > path
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
std::multimap< int64_t, CWalletTx * > TxItems
bool ParseOutputType(const std::string &type, OutputType &output_type)
bool IsImmatureCoinBase() const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void ReturnKey(int64_t nIndex, bool fInternal, const CPubKey &pubkey)
OutputType TransactionChangeType(OutputType change_type, const std::vector< CRecipient > &vecSend)
static bool RecoverKeysOnlyFilter(void *callbackData, CDataStream ssKey, CDataStream ssValue)
unsigned int nTx
Number of transactions in this block.
int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, bool use_max_sig)
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet) ...
static const int VERSION_HD_BASE
CAmount GetChange(const CTxOut &txout) const
std::string _(const char *psz)
Translation function.
CPubKey GenerateNewKey(WalletBatch &batch, bool internal=false) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
keystore implementation Generate a new key
void operator()(const WitnessV0KeyHash &keyid)
CAmount nImmatureCreditCached
CAmount GetChange() const
CPubKey GenerateNewSeed()
void GetTransactionAncestry(const uint256 &txid, size_t &ancestors, size_t &descendants) const
Calculate the ancestor and descendant count for the given transaction.
uint64_t GetRand(uint64_t nMax)
CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector< CKeyID > &vKeysIn)
A hasher class for RIPEMD-160.
bool Unlock(const SecureString &strWalletPassphrase)
uint32_t nInternalChainCounter
bool AddWatchOnly(const CScript &dest) override
Support for Watch-only addresses.
std::vector< unsigned char > ToByteVector(const T &in)
const CKeyStore & keystore
bool EraseName(const std::string &strAddress)
std::vector< std::pair< std::string, std::string > > vOrderForm
CAmount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
bool IsCompressed() const
Check whether this is a compressed public key.
CBlockIndex * LookupBlockIndex(const uint256 &hash)