10 #if defined(HAVE_CONFIG_H)
31 #include <boost/algorithm/string/replace.hpp>
66 const std::pair<
CAmount, std::pair<const CWalletTx*, unsigned int> >& t2)
const
68 return t1.first < t2.first;
89 std::vector<CTxDestination> vDest;
93 boost::apply_visitor(*
this, dest);
100 vKeys.push_back(keyId);
105 vKeys.push_back(keyId);
120 std::vector<CKeyID> ret;
121 std::vector<CKeyID> vAffected;
123 for (
const CKeyID& keyid : vAffected) {
124 ret.emplace_back(keyid);
135 if (
m_spk_man->SetupGeneration(newKeypool,
true, memOnly)) {
136 LogPrintf(
"%s : spkm setup completed\n", __func__);
145 LogPrintf(
"%s : sapling spkm setup completed\n", __func__);
148 LogPrintf(
"%s : ERROR: wallet cannot upgrade to sapling features. Try to upgrade using the 'upgradewallet' RPC command\n", __func__);
169 std::map<uint256, CWalletTx>::const_iterator it =
mapWallet.find(hash);
172 return &(it->second);
178 std::vector<CWalletTx> result;
181 result.emplace_back(entry.second);
205 uint8_t type = (addrType == CChainParams::Base58Type::STAKING_ADDRESS ? HDChain::ChangeType::STAKING : HDChain::ChangeType::EXTERNAL);
211 _(
"Keypool ran out, please call keypoolrefill first, or unlock the wallet.")));
216 throw std::runtime_error(
"CWallet::getNewAddress() : SetAddressBook failed");
235 const CKeyID* keyID = boost::get<CKeyID>(&address);
280 const std::vector<unsigned char>& vchCryptedSecret)
318 if (nCreateTime <= 1) {
339 if (redeemScript.
size() > MAX_SCRIPT_ELEMENT_SIZE) {
341 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",
342 __func__, redeemScript.
size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr);
383 for (
const MasterKeyMap::value_type& pMasterKey :
mapMasterKeys) {
384 if (!crypter.
SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
418 bool keyPass =
false;
419 bool keyFail =
false;
422 const CPubKey& vchPubKey = (*mi).second.first;
423 const std::vector<unsigned char>& vchCryptedSecret = (*mi).second.second;
425 if (!
DecryptKey(vMasterKeyIn, vchCryptedSecret, vchPubKey, key)) {
434 if (keyPass && keyFail) {
435 LogPrintf(
"The wallet is probably corrupted: Some keys decrypt but not all.\n");
436 throw std::runtime_error(
"Error unlocking wallet: some keys decrypt but not all. Your wallet file may be corrupt.");
439 if (keyFail || !keyPass)
445 LogPrintf(
"Sapling wallet unlock keys failed\n");
446 throw std::runtime_error(
"Error unlocking wallet: some Sapling keys decrypt but not all. Your wallet file may be corrupt.");
460 SecureString strOldWalletPassphraseFinal = strOldWalletPassphrase;
469 if (!crypter.
SetKeyFromPassphrase(strOldWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
475 crypter.
SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
476 pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(
GetTimeMillis() - nStartTime)));
479 crypter.
SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod);
480 pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(
GetTimeMillis() - nStartTime))) / 2;
482 if (pMasterKey.second.nDeriveIterations < 25000)
483 pMasterKey.second.nDeriveIterations = 25000;
485 LogPrintf(
"Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations);
487 if (!crypter.
SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod))
508 m_sspk_man->UpdateSaplingNullifierNoteMapForBlock(pblock);
521 LogPrintf(
"%s: Couldn't start atomic write\n", __func__);
527 LogPrintf(
"SetBestChain(): Failed to write best block, aborting atomic write\n");
533 for (std::pair<const uint256, CWalletTx>& wtxItem :
mapWallet) {
534 auto wtx = wtxItem.second;
539 if (!wtx.mapSaplingNoteData.empty()) {
541 if (!wtx.tx->isSaplingVersion()) {
542 LogPrintf(
"SetBestChain(): ERROR, Invalid tx version found with sapling data\n");
545 _(
"A fatal internal error occurred, see debug.log for details"),
552 LogPrintf(
"SetBestChain(): Failed to write CWalletTx, aborting atomic write\n");
562 LogPrintf(
"%s: Failed to write nWitnessCacheSize\n", __func__);
570 LogPrintf(
"%s: Couldn't commit atomic write\n", __func__);
620 std::set<uint256> result;
623 std::map<uint256, CWalletTx>::const_iterator it =
mapWallet.find(txid);
628 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
630 for (
const CTxIn& txin : wtx.
tx->vin) {
634 for (TxSpends::const_iterator _it = range.first; _it != range.second; ++_it)
635 result.insert(_it->second);
648 SyncMetaData<uint256>(range);
658 int nMinOrderPos = std::numeric_limits<int>::max();
663 if (n < nMinOrderPos) {
674 for (
auto it = range.first; it != range.second; ++it) {
675 const uint256& hash = it->second;
677 if (copyFrom == copyTo)
continue;
678 assert(copyFrom &&
"Oldest wallet transaction in range assumed to have been found.");
723 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range;
725 for (TxSpends::const_iterator it = range.first; it != range.second; ++it) {
726 const uint256& wtxid = it->second;
727 std::map<uint256, CWalletTx>::const_iterator mit =
mapWallet.find(wtxid);
730 const int nDepth = mit->second.GetDepthAndMempool(fConflicted);
732 const bool fConflictedCoinstake = fConflicted && mit->second.IsCoinStake();
733 if (nDepth > 0 || (nDepth == 0 && !mit->second.isAbandoned() && !fConflictedCoinstake) )
750 std::pair<TxSpends::iterator, TxSpends::iterator> range;
752 SyncMetaData<COutPoint>(range);
763 for (
const CTxIn& txin : thisTx.
tx->vin)
800 LogPrintf(
"Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.
nDeriveIterations);
842 Unlock(strWalletPassphrase);
845 if (!
m_spk_man->SetupGeneration(
true,
true)) {
884 for (
const CTxOut& txout : wtx.
tx->vout)
896 for (std::pair<const uint256, CWalletTx> & item :
mapWallet)
897 item.second.MarkDirty();
908 std::pair<std::map<uint256, CWalletTx>::iterator,
bool> ret =
mapWallet.emplace(hash, wtxIn);
912 m_sspk_man->UpdateNullifierNoteMapWithTx(wtx);
913 bool fInsertedNew = ret.second;
922 bool fUpdated =
false;
946 LogPrintf(
"AddToWallet %s %s%s\n", wtxIn.
GetHash().
ToString(), (fInsertedNew ?
"new" :
""), (fUpdated ?
"update" :
""));
949 if (fInsertedNew || fUpdated) {
961 std::string strCmd =
gArgs.
GetArg(
"-walletnotify",
"");
963 if (!strCmd.empty()) {
1011 m_sspk_man->UpdateNullifierNoteMapWithTx(wtx);
1014 for (
const CTxIn& txin : wtx.
tx->vin) {
1028 auto saplingNoteDataAndAddressesToAdd =
m_sspk_man->FindMySaplingNotes(tx);
1029 saplingNoteData = saplingNoteDataAndAddressesToAdd.first;
1030 auto addressesToAdd = saplingNoteDataAndAddressesToAdd.second;
1032 for (
const auto& addressToAdd : addressesToAdd) {
1033 if (!
m_sspk_man->AddSaplingIncomingViewingKey(addressToAdd.second, addressToAdd.first)) {
1046 for (
unsigned int i = 0; i < wtx.
tx->sapData->vShieldedOutput.size(); i++) {
1054 const auto& memo = recovered->first.memo();
1056 if (memo[0] < 0xF6) {
1085 std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range =
mapTxSpends.equal_range(txin.
prevout);
1086 while (range.first != range.second) {
1087 if (range.first->second != tx.
GetHash()) {
1088 LogPrintf(
"Transaction %s (in block %s) conflicts with wallet transaction %s (both spend %s:%i)\n", tx.
GetHash().
ToString(), confirm.
hashBlock.
ToString(), range.first->second.ToString(), range.first->first.hash.ToString(), range.first->first.n);
1097 if (fExisted && !fUpdate)
return false;
1111 if (fExisted ||
IsMine(ptx) || isFromMe || (saplingNoteData && !saplingNoteData->empty())) {
1124 CWalletTx wtx(
this, MakeTransactionRef(tx));
1125 if (wtx.
tx->IsShieldedTx()) {
1126 if (saplingNoteData && !saplingNoteData->empty()) {
1150 std::set<uint256> todo;
1151 std::set<uint256> done;
1161 todo.insert(hashTx);
1163 while (!todo.empty()) {
1172 assert(currentconfirm <= 0);
1183 while (iter !=
mapTxSpends.end() && iter->first.hash == now) {
1184 if (!done.count(iter->second)) {
1185 todo.insert(iter->second);
1191 for (
const CTxIn& txin : wtx.
tx->vin) {
1194 _it->second.MarkDirty();
1207 int conflictconfirms = (m_last_block_processed_height - conflicting_height + 1) * -1;
1212 if (conflictconfirms >= 0)
1218 std::set<uint256> todo;
1219 std::set<uint256> done;
1221 todo.insert(hashTx);
1223 while (!todo.empty()) {
1231 if (conflictconfirms < currentconfirm) {
1242 while (iter !=
mapTxSpends.end() && iter->first.hash == now) {
1243 if (!done.count(iter->second)) {
1244 todo.insert(iter->second);
1250 for (
const CTxIn& txin : wtx.
tx->vin) {
1253 _it->second.MarkDirty();
1275 auto it =
mapWallet.find(ptx->GetHash());
1277 it->second.fInMempool =
true;
1283 auto it =
mapWallet.find(ptx->GetHash());
1285 it->second.fInMempool =
false;
1326 m_last_block_processed_height = pindex->
nHeight;
1327 for (
size_t index = 0; index < pblock->vtx.size(); index++) {
1329 m_last_block_processed, index);
1338 bool isSaplingActive = (pprev) !=
nullptr &&
1341 if (isSaplingActive) {
1368 m_last_block_processed_height = nBlockHeight - 1;
1369 m_last_block_processed_time = blockTime;
1370 m_last_block_processed = blockHash;
1379 m_sspk_man->UpdateSaplingNullifierNoteMapForBlock(pblock.get());
1396 if (!last_block_hash.
IsNull() && initialChainTip &&
1417 it->second.MarkDirty();
1426 auto nit =
m_sspk_man->mapSaplingNullifiersToNotes.find(nullifier);
1427 if (nit !=
m_sspk_man->mapSaplingNullifiersToNotes.end()) {
1428 auto it =
mapWallet.find(nit->second.hash);
1430 it->second.MarkDirty();
1443 LogPrintf(
"%s: Erased wtx %s from wallet\n", __func__, hash.
GetHex());
1466 if (!::
IsMine(*
this, scriptPubKey)) {
1475 for (
const CTxOut& txout : wtx.
tx->vout) {
1486 if (!::
IsMine(*
this, address)) {
1493 if (txout.second.address && *txout.second.address == address)
1568 if (recalculate || !amount.m_cached[filter]) {
1571 return amount.m_value[filter];
1582 if (
tx->vin.empty() && (
tx->sapData &&
tx->sapData->vShieldedSpend.empty())) {
1669 for (
unsigned int i = 0; i <
tx->vout.size(); i++) {
1673 if (!
Params().GetConsensus().MoneyRange(nCredit))
1674 throw std::runtime_error(std::string(__func__) +
" : value out of range");
1717 for (
unsigned int i = 0; i <
tx->vout.size(); i++) {
1733 if (!
Params().GetConsensus().MoneyRange(nCredit))
1734 throw std::runtime_error(
"CWalletTx::GetLockedCredit() : value out of range");
1755 std::list<COutputEntry>& listSent,
1760 listReceived.clear();
1765 bool isFromMyTaddr = nDebit > 0;
1767 if (isFromMyTaddr) {
1769 CAmount nValueIn =
tx->GetShieldedValueIn();
1770 nFee = nDebit - nValueOut + nValueIn;
1775 if (
tx->sapData->valueBalance < 0) {
1777 listSent.push_back(output);
1778 }
else if (
tx->sapData->valueBalance > 0) {
1780 listReceived.push_back(output);
1786 bool hasZerocoinSpends =
tx->HasZerocoinSpendInputs();
1787 for (
unsigned int i = 0; i <
tx->vout.size(); ++i) {
1797 }
else if (!(fIsMine & filter) && !hasZerocoinSpends)
1807 LogPrintf(
"CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n", this->
GetHash().ToString());
1816 listSent.push_back(output);
1819 if (fIsMine & filter)
1820 listReceived.push_back(output);
1830 error =
strprintf(
_(
"Cannot upgrade to Sapling wallet (already running Sapling support). Version: %d"), prevVersion);
1868 LogPrintf(
"%s: Rescanning last %i blocks\n", __func__, startBlock ?
chainActive.
Height() - startBlock->
nHeight + 1 : 0);
1910 double dProgressStart;
1911 double dProgressTip;
1919 std::vector<uint256> myTxHashes;
1922 if (pindex->
nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0) {
1924 ShowProgress(
_(
"Rescanning..."), std::max(1, std::min(99, (
int)((gvp - dProgressStart) / (dProgressTip - dProgressStart) * 100))));
1928 LogPrintf(
"Still rescanning. At block %d. Progress=%f\n", pindex->
nHeight, gvp);
1943 for (
int posInBlock = 0; posInBlock < (int) block.
vtx.size(); posInBlock++) {
1944 const auto& tx = block.
vtx[posInBlock];
1947 myTxHashes.push_back(tx->GetHash());
1954 if (pindex->
pprev) {
1965 if (pindex == pindexStop) {
1983 for (
const auto& hash : myTxHashes) {
1987 LogPrintf(
"Rescanning... WriteToDisk failed to update Sapling note data for: %s\n", hash.ToString());
2003 std::map<int64_t, CWalletTx*> mapSorted;
2006 for (std::pair<const uint256, CWalletTx>& item:
mapWallet) {
2007 const uint256& wtxid = item.first;
2009 assert(wtx.
GetHash() == wtxid);
2018 for (std::pair<const int64_t, CWalletTx*>& item: mapSorted) {
2044 LogPrintf(
"Relaying wtx %s\n", hash.
ToString());
2054 std::set<uint256> result;
2058 result.erase(myHash);
2088 LogPrintf(
"ResendWalletTransactions()\n");
2092 std::multimap<unsigned int, CWalletTx*> mapSorted;
2093 for (std::pair<const uint256, CWalletTx> & item :
mapWallet) {
2101 for (std::pair<const unsigned int, CWalletTx*> & item : mapSorted) {
2126 std::set<uint256> trusted_parents;
2133 if (is_trusted && tx_depth >= min_depth) {
2136 if (wtx.
tx->HasP2CSOutputs()) {
2140 if (!is_trusted && tx_depth == 0 && wtx.
InMempool()) {
2156 method(it.first, it.second, nTotal);
2165 if (fIncludeDelegated && fIncludeShielded) {
2167 }
else if (fIncludeDelegated) {
2169 }
else if (fIncludeShielded) {
2182 if (pcoin.
IsTrusted(depth, fConflicted) && depth >= minDepth) {
2183 nTotal += pcoin.GetAvailableCredit(useCache, filter);
2191 if (pcoin.
tx->HasP2CSOutputs() && pcoin.
IsTrusted())
2204 if (fIncludeColdStaking)
2213 if (pcoin.
tx->HasP2CSOutputs() && pcoin.
IsTrusted())
2229 ret += it->second.
tx->vout.at(coin.n).nValue;
2332 const bool outgoing = debit > 0;
2333 for (
const CTxOut& out : wtx.
tx->vout) {
2336 }
else if (
IsMine(out) & filter && depth >= minDepth) {
2367 const uint256& wtxid = it.first;
2373 if (fConflicted || nDepth < 0)
2378 if (pcoin->
tx->HasP2CSOutputs()) {
2379 for (
int i = 0; i < (int) pcoin->
tx->vout.size(); i++) {
2380 const auto &utxo = pcoin->
tx->vout[i];
2385 if (utxo.scriptPubKey.IsPayToColdStaking()) {
2390 vCoins.emplace_back(pcoin, i, 0, isMineSpendable,
true, fSafe);
2402 static bool CheckTXAvailabilityInternal(
const CWalletTx* pcoin,
bool fOnlySafe,
int& nDepth,
bool& safeTx)
2405 if (fOnlySafe && !safeTx)
return false;
2412 if (nDepth == 0 && !pcoin->
InMempool())
return false;
2418 static bool CheckTXAvailability(
const CWalletTx* pcoin,
bool fOnlySafe,
int& nDepth,
bool& safeTx)
2422 return CheckTXAvailabilityInternal(pcoin, fOnlySafe, nDepth, safeTx);
2426 static bool CheckTXAvailability(
const CWalletTx* pcoin,
2434 return CheckTXAvailabilityInternal(pcoin, fOnlySafe, nDepth, safeTx);
2440 bool fValidateCollateral,
2441 std::string& strError)
2449 strError =
"collateral tx not found in the wallet";
2450 return error(
"%s: %s", __func__, strError);
2454 if (collateralOut.
n < 0 || collateralOut.
n >= (uint32_t) wtx->
tx->vout.size()) {
2455 strError =
"Invalid masternode output index";
2456 return error(
"%s: output index %d not found in %s", __func__, collateralOut.
n, collateralOut.
hash.
GetHex());
2459 CTxOut txOut = wtx->
tx->vout[collateralOut.
n];
2463 if (txOut.
nValue != consensus.nMNCollateralAmt) {
2465 return error(
"%s: tx %s, index %d not a masternode collateral", __func__, collateralOut.
hash.
GetHex(), collateralOut.
n);
2468 if (fValidateCollateral) {
2473 bool safeTx =
false;
2474 if (!CheckTXAvailability(wtx,
true, nDepth, safeTx, m_last_block_processed_height)) {
2475 strError =
"Not available collateral transaction";
2476 return error(
"%s: tx %s not available", __func__, collateralOut.
hash.
GetHex());
2481 strError =
"Error: collateral already spent";
2482 return error(
"%s: tx %s already spent", __func__, collateralOut.
hash.
GetHex());
2487 if (nDepth < consensus.MasternodeCollateralMinConf()) {
2488 strError =
strprintf(
"Collateral tx must have at least %d confirmations, has %d",
2489 consensus.MasternodeCollateralMinConf(), nDepth);
2490 return error(
"%s: %s", __func__, strError);
2496 const CKeyID* keyID = boost::get<CKeyID>(&destCollateral);
2498 LogPrintf(
"%s: Address does not refer to a key\n", __func__);
2502 if (!
GetKey(*keyID, keyRet)) {
2503 LogPrintf(
"%s: Private key for address is not known\n", __func__);
2513 const unsigned int outIndex,
2516 const bool fCoinsSelected,
2517 const bool fIncludeColdStaking,
2518 const bool fIncludeDelegated,
2519 const bool fIncludeLocked)
const
2524 if (
IsSpent(wtxid, outIndex))
return res;
2532 if (!fIncludeLocked &&
IsLockedCoin(wtxid, outIndex))
return res;
2535 if (output.
nValue <= 0)
return res;
2559 if (pCoins) pCoins->clear();
2560 const bool fCoinsSelected = (coinControl !=
nullptr) && coinControl->
HasSelected();
2569 const uint256& wtxid = entry.first;
2574 bool safeTx =
false;
2575 if (!CheckTXAvailability(pcoin, coinsFilter.
fOnlySafe, nDepth, safeTx, m_last_block_processed_height))
2579 if (nDepth < coinsFilter.
minDepth)
continue;
2581 for (
unsigned int i = 0; i < pcoin->
tx->vout.size(); i++) {
2582 const auto& output = pcoin->
tx->vout[i];
2611 if (!res.available)
continue;
2615 if (!pCoins)
return true;
2616 pCoins->emplace_back(pcoin, (
int) i, nDepth, res.spendable, res.solvable, safeTx);
2620 nTotal += output.nValue;
2633 return (pCoins && !pCoins->empty());
2644 std::vector<COutput> vCoins;
2647 std::map<CTxDestination, std::vector<COutput> > mapCoins;
2648 for (
const COutput& out : vCoins) {
2650 bool fColdStakeAddr =
false;
2651 if (!
ExtractDestination(out.tx->tx->vout[out.i].scriptPubKey, address, fColdStakeAddr)) {
2652 bool isP2CS = out.tx->tx->vout[out.i].scriptPubKey.IsPayToColdStaking();
2653 if (isP2CS && !fIncludeColdStaking) {
2658 fColdStakeAddr =
true;
2659 if (!isP2CS || !
ExtractDestination(out.tx->tx->vout[out.i].scriptPubKey, address, fColdStakeAddr) )
2663 mapCoins[address].emplace_back(out);
2669 static void ApproximateBestSubset(
const std::vector<std::pair<
CAmount, std::pair<const CWalletTx*,unsigned int> > >& vValue,
const CAmount& nTotalLower,
const CAmount& nTargetValue,
2670 std::vector<char>& vfBest,
CAmount& nBest,
int iterations = 1000)
2672 std::vector<char> vfIncluded;
2674 vfBest.assign(vValue.size(),
true);
2675 nBest = nTotalLower;
2679 for (
int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++) {
2680 vfIncluded.assign(vValue.size(),
false);
2682 bool fReachedTarget =
false;
2683 for (
int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) {
2684 for (
unsigned int i = 0; i < vValue.size(); i++) {
2691 if (nPass == 0 ? insecure_rand.
randbool() : !vfIncluded[i]) {
2692 nTotal += vValue[i].first;
2693 vfIncluded[i] =
true;
2694 if (nTotal >= nTargetValue) {
2695 fReachedTarget =
true;
2696 if (nTotal < nBest) {
2698 vfBest = vfIncluded;
2700 nTotal -= vValue[i].first;
2701 vfIncluded[i] =
false;
2714 if (pCoins) pCoins->clear();
2718 const uint256& wtxid = it.first;
2723 bool safeTx =
false;
2724 if (!CheckTXAvailability(pcoin,
true, nDepth, safeTx))
2731 for (
unsigned int index = 0; index < pcoin->
tx->vout.size(); index++) {
2734 pcoin->
tx->vout[index],
2739 fIncludeColdStaking,
2743 if (!res.available || !res.spendable)
continue;
2746 if (!pCoins)
return true;
2748 pCoins->emplace_back(pcoin, (
int) index, nDepth, pindex);
2751 return (pCoins && !pCoins->empty());
2754 bool CWallet::SelectCoinsMinConf(
const CAmount& nTargetValue,
int nConfMine,
int nConfTheirs, uint64_t nMaxAncestors, std::vector<COutput> vCoins, std::set<std::pair<const CWalletTx*, unsigned int> >& setCoinsRet,
CAmount& nValueRet)
const
2756 setCoinsRet.clear();
2760 std::pair<CAmount, std::pair<const CWalletTx*, unsigned int> > coinLowestLarger;
2761 coinLowestLarger.first = std::numeric_limits<CAmount>::max();
2762 coinLowestLarger.second.first =
nullptr;
2763 std::vector<std::pair<CAmount, std::pair<const CWalletTx*, unsigned int> > > vValue;
2768 for (
const COutput& output : vCoins) {
2769 if (!output.fSpendable)
2785 std::pair<CAmount, std::pair<const CWalletTx*, unsigned int> > coin = std::make_pair(n, std::make_pair(pcoin, i));
2787 if (n == nTargetValue) {
2788 setCoinsRet.insert(coin.second);
2789 nValueRet += coin.first;
2791 }
else if (n < nTargetValue + MIN_CHANGE) {
2792 vValue.push_back(coin);
2794 }
else if (n < coinLowestLarger.first) {
2795 coinLowestLarger = coin;
2799 if (nTotalLower == nTargetValue) {
2800 for (
unsigned int i = 0; i < vValue.size(); ++i) {
2801 setCoinsRet.insert(vValue[i].second);
2802 nValueRet += vValue[i].first;
2807 if (nTotalLower < nTargetValue) {
2808 if (coinLowestLarger.second.first ==
nullptr)
2810 setCoinsRet.insert(coinLowestLarger.second);
2811 nValueRet += coinLowestLarger.first;
2817 std::vector<char> vfBest;
2820 ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest);
2821 if (nBest != nTargetValue && nTotalLower >= nTargetValue + MIN_CHANGE)
2822 ApproximateBestSubset(vValue, nTotalLower, nTargetValue + MIN_CHANGE, vfBest, nBest);
2826 if (coinLowestLarger.second.first &&
2827 ((nBest != nTargetValue && nBest < nTargetValue + MIN_CHANGE) || coinLowestLarger.first <= nBest)) {
2828 setCoinsRet.insert(coinLowestLarger.second);
2829 nValueRet += coinLowestLarger.first;
2831 std::string s =
"CWallet::SelectCoinsMinConf best subset: ";
2832 for (
unsigned int i = 0; i < vValue.size(); i++) {
2834 setCoinsRet.insert(vValue[i].second);
2835 nValueRet += vValue[i].first;
2839 LogPrintf(
"%s - total %s\n", s,
FormatMoney(nBest));
2848 std::vector<COutput> vCoins(vAvailableCoins);
2852 for (
const COutput& out : vCoins) {
2853 if (!out.fSpendable)
2856 nValueRet += out.tx->tx->vout[out.i].nValue;
2857 setCoinsRet.emplace(out.tx, out.i);
2859 return (nValueRet >= nTargetValue);
2863 std::set<std::pair<const CWalletTx*, uint32_t> > setPresetCoins;
2864 CAmount nValueFromPresetInputs = 0;
2866 std::vector<OutPointWrapper> vPresetInputs;
2869 for (
const auto& outpoint : vPresetInputs) {
2870 std::map<uint256, CWalletTx>::const_iterator it =
mapWallet.find(outpoint.outPoint.hash);
2874 if (pcoin->
tx->vout.size() <= outpoint.outPoint.n)
2876 nValueFromPresetInputs += pcoin->
tx->vout[outpoint.outPoint.n].nValue;
2877 setPresetCoins.emplace(pcoin, outpoint.outPoint.n);
2883 for (std::vector<COutput>::iterator it = vCoins.begin(); it != vCoins.end() && coinControl && coinControl->
HasSelected();) {
2884 if (setPresetCoins.count(std::make_pair(it->tx, it->i)))
2885 it = vCoins.erase(it);
2890 size_t nMaxChainLength = std::min(
gArgs.
GetArg(
"-limitancestorcount", DEFAULT_ANCESTOR_LIMIT),
gArgs.
GetArg(
"-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT));
2892 bool res = nTargetValue <= nValueFromPresetInputs ||
2893 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 6, 0, vCoins, setCoinsRet, nValueRet) ||
2894 SelectCoinsMinConf(nTargetValue - nValueFromPresetInputs, 1, 1, 0, vCoins, setCoinsRet, nValueRet) ||
2901 setCoinsRet.insert(setPresetCoins.begin(), setPresetCoins.end());
2904 nValueRet += nValueFromPresetInputs;
2909 std::map<std::pair<CTxDestination, Optional<CTxDestination>>, std::vector<COutput>>
CWallet::ListCoins()
const
2911 std::map<std::pair<CTxDestination, Optional<CTxDestination>>, std::vector<COutput>> result;
2916 std::vector<COutput> availableCoins;
2919 for (
const COutput& coin : availableCoins) {
2920 const CScript& scriptPubKey = coin.tx->tx->vout[coin.i].scriptPubKey;
2921 txnouttype type; std::vector<CTxDestination> addresses;
int nRequired;
2923 if (addresses.size() == 1) {
2925 const auto& addrpair = std::make_pair(addresses[0], nullopt);
2926 result[addrpair].emplace_back(std::move(coin));
2929 assert(addresses.size() == 2);
2931 result[addrpair].emplace_back(std::move(coin));
2950 std::string strFail =
"";
2951 std::vector<CRecipient> vecSend;
2952 vecSend.emplace_back(scriptChange,
fee,
false);
2955 int nChangePosInOut = -1;
2956 bool success =
CreateTransaction(vecSend, tx, keyChange, nFeeRet, nChangePosInOut, strFail, coinControl,
true, (
CAmount)0);
2958 LogPrintf(
"%s: Error - %s\n", __func__, strFail);
2967 std::vector<CRecipient> vecSend;
2970 for (
size_t idx = 0; idx < tx.
vout.size(); idx++) {
2972 vecSend.emplace_back(txOut.
scriptPubKey, txOut.
nValue, setSubtractFeeFromOutputs.count(idx) == 1);
2980 coinControl.
nFeeRate = specificFeeRate;
2995 if (!
CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePosInOut, strFailReason, &coinControl,
false, 0,
false,
nullptr, nExtraSize)) {
2999 if (nChangePosInOut != -1) {
3000 tx.
vout.insert(tx.
vout.begin() + nChangePosInOut, wtx->vout[nChangePosInOut]);
3008 for (
unsigned int idx = 0; idx < tx.
vout.size(); idx++) {
3009 tx.
vout[idx].nValue = wtx->vout[idx].nValue;
3013 for (
const CTxIn& txin : wtx->vin) {
3015 tx.
vin.emplace_back(txin);
3025 assert(coinControl);
3027 std::vector<COutput> vCoinsRet;
3028 std::vector<OutPointWrapper> vPresetInputs;
3030 for (
const auto& out : vPresetInputs) {
3031 auto it =
mapWallet.find(out.outPoint.hash);
3033 assert(it->second.tx->vout.size() > out.outPoint.n);
3034 vCoinsRet.emplace_back(
COutput(&(it->second), out.outPoint.n, 0,
true,
true,
true));
3044 int& nChangePosInOut,
3045 std::string& strFailReason,
3049 bool fIncludeDelegated,
3050 bool* fStakeDelegationVoided,
3055 int nChangePosRequest = nChangePosInOut;
3056 unsigned int nSubtractFeeFromAmount = 0;
3058 if (nValue < 0 || rec.nAmount < 0) {
3059 strFailReason =
_(
"Transaction amounts must be positive");
3062 nValue += rec.nAmount;
3063 if (rec.fSubtractFeeFromAmount)
3064 nSubtractFeeFromAmount++;
3066 if (vecSend.empty()) {
3067 strFailReason =
_(
"Transaction must have at least one recipient");
3080 std::set<std::pair<const CWalletTx*,unsigned int> > setCoins;
3083 std::vector<COutput> vAvailableCoins;
3093 if (nFeePay > 0) nFeeRet = nFeePay;
3095 nChangePosInOut = nChangePosRequest;
3100 CAmount nValueToSelect = nValue;
3101 if (nSubtractFeeFromAmount == 0)
3102 nValueToSelect += nFeeRet;
3106 CTxOut txout(rec.nAmount, rec.scriptPubKey);
3107 if (rec.fSubtractFeeFromAmount) {
3108 assert(nSubtractFeeFromAmount != 0);
3109 txout.
nValue -= nFeeRet / nSubtractFeeFromAmount;
3114 txout.
nValue -= nFeeRet % nSubtractFeeFromAmount;
3118 strFailReason =
_(
"Transaction amount too small");
3121 txNew.
vout.emplace_back(txout);
3128 if (!
SelectCoinsToSpend(vAvailableCoins, nValueToSelect, setCoins, nValueIn, coinControl)) {
3129 strFailReason =
_(
"Insufficient funds.");
3134 CAmount nChange = nValueIn - nValueToSelect;
3139 bool combineChange =
false;
3145 std::vector<CTxOut>::iterator it = txNew.
vout.begin();
3146 while (it != txNew.
vout.end()) {
3147 if (scriptChange == it->scriptPubKey) {
3148 it->nValue += nChange;
3151 combineChange =
true;
3170 strFailReason =
_(
"Can't generate a change-address key. Please call keypoolrefill first.");
3177 if (!combineChange) {
3178 CTxOut newTxOut(nChange, scriptChange);
3186 nChangePosInOut = -1;
3188 if (nChangePosInOut == -1) {
3191 }
else if (nChangePosInOut < 0 || (
unsigned int) nChangePosInOut > txNew.
vout.size()) {
3192 strFailReason =
_(
"Change index out of range");
3195 std::vector<CTxOut>::iterator position = txNew.
vout.begin() + nChangePosInOut;
3196 txNew.
vout.insert(position, newTxOut);
3201 nChangePosInOut = -1;
3205 for (
const std::pair<const CWalletTx*, unsigned int>& coin : setCoins) {
3206 if(fStakeDelegationVoided && coin.first->tx->vout[coin.second].scriptPubKey.IsPayToColdStaking()) {
3207 *fStakeDelegationVoided =
true;
3209 txNew.
vin.emplace_back(coin.first->GetHash(), coin.second);
3214 for (
const auto & coin : setCoins) {
3215 const CScript& scriptPubKey = coin.first->tx->vout[coin.second].scriptPubKey;
3218 strFailReason =
_(
"Signing transaction failed");
3227 const unsigned int nBytes =
::GetSerializeSize(txNew, PROTOCOL_VERSION) + nExtraSize;
3235 if (coinControl && nFeeNeeded > 0 && coinControl->
nMinimumTotalFee > nFeeNeeded) {
3244 strFailReason =
_(
"Transaction too large for fee policy");
3248 if (nFeeRet >= nFeeNeeded)
3252 nFeeRet = nFeeNeeded;
3257 if (scriptChange.
empty() && nChangePosInOut != -1) {
3265 for (
const auto& coin : setCoins) {
3266 const CScript& scriptPubKey = coin.first->tx->vout[coin.second].scriptPubKey;
3268 bool haveKey = coin.first->GetStakeDelegationCredit() > 0;
3277 strFailReason =
_(
"Signing transaction failed");
3288 strFailReason =
_(
"Transaction too large");
3293 txRet = MakeTransactionRef(std::move(txNew));
3299 size_t nLimitAncestors =
gArgs.
GetArg(
"-limitancestorcount", DEFAULT_ANCESTOR_LIMIT);
3300 size_t nLimitAncestorSize =
gArgs.
GetArg(
"-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT)*1000;
3301 size_t nLimitDescendants =
gArgs.
GetArg(
"-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT);
3302 size_t nLimitDescendantSize =
gArgs.
GetArg(
"-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT)*1000;
3303 std::string errString;
3305 strFailReason =
_(
"Transaction has too long of a mempool chain");
3312 bool CWallet::CreateTransaction(
CScript scriptPubKey,
const CAmount& nValue,
CTransactionRef& wtxNew,
CReserveKey& reservekey,
CAmount& nFeeRet, std::string& strFailReason,
const CCoinControl* coinControl,
CAmount nFeePay,
bool fIncludeDelegated,
bool* fStakeDelegationVoided,
int nExtraSize,
int nMinDepth)
3314 std::vector<CRecipient> vecSend;
3315 vecSend.emplace_back(scriptPubKey, nValue,
false);
3316 int nChangePosInOut = -1;
3317 return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, nChangePosInOut, strFailReason, coinControl,
true, nFeePay, fIncludeDelegated, fStakeDelegationVoided, nExtraSize, nMinDepth);
3327 std::vector<valtype> vSolutions;
3331 return error(
"%s: failed to get stake input", __func__);
3334 if (!
Solver(scriptPubKeyKernel, whichType, vSolutions))
3335 return error(
"%s: failed to parse kernel", __func__);
3338 return error(
"%s: type=%d (%s) not supported for scriptPubKeyKernel", __func__, whichType,
GetTxnOutputType(whichType));
3344 return error(
"%s: Unable to get staking private key", __func__);
3347 vout.emplace_back(0, scriptPubKeyKernel);
3354 int txSizeMax = MAX_STANDARD_TX_SIZE >> 11;
3355 if (nSplit > txSizeMax)
3357 for (
int i = nSplit; i > 1; i--) {
3358 LogPrintf(
"%s: StakeSplit: nTotal = %d; adding output %d of %d\n", __func__, nTotal, (nSplit-i)+2, nSplit);
3359 vout.emplace_back(0, scriptPubKeyKernel);
3371 int64_t& nTxNewTime,
3372 std::vector<CStakeableOutput>* availableCoins,
3373 bool stopOnNewBlock)
const
3376 if (availableCoins &&
Params().IsRegTestNet()) {
3393 bool fKernelFound =
false;
3395 for (
auto it = availableCoins->begin(); it != availableCoins->end();) {
3397 CPivStake stakeInput(it->tx->tx->vout[it->i],
3410 it = availableCoins->erase(it);
3417 fKernelFound =
Stake(pindexPrev, &stakeInput, nBits, nTxNewTime);
3423 if (!fKernelFound) {
3429 LogPrintf(
"CreateCoinStake : kernel found\n");
3437 std::vector<CTxOut> vout;
3439 LogPrintf(
"%s : failed to create output\n", __func__);
3443 txNew.
vout.insert(txNew.
vout.end(), vout.begin(), vout.end());
3446 int outputs = (int) txNew.
vout.size() - 1;
3450 CAmount nShare = nRemaining / outputs;
3451 for (
int i = 1; i < outputs; i++) {
3453 txNew.
vout[i].nValue = nShare;
3454 nRemaining -= nShare;
3458 txNew.
vout[outputs].nValue += nRemaining;
3461 txNew.
vin.emplace_back(stakeInput.
GetTxIn());
3465 if (nBytes >= DEFAULT_BLOCK_MAX_SIZE / 5)
3466 return error(
"%s : exceeded coinstake size limit", __func__);
3472 return fKernelFound;
3479 for (
const CTxIn& txIn : txNew.
vin) {
3482 return error(
"%s : failed to sign coinstake", __func__);
3495 return _(
"No error");
3496 case CWallet::CommitStatus::Abandoned:
3497 strErrRet +=
_(
"Transaction canceled.");
3499 case CWallet::CommitStatus::NotAccepted:
3500 strErrRet +=
strprintf(
_(
"WARNING: The transaction has been signed and recorded, so the wallet will try to re-send it. "
3501 "Use 'abandontransaction' to cancel it. (txid: %s)"),
hashTx.
ToString());
3504 return _(
"Invalid status error.");
3527 if (extras) wtxNew.
mapValue.insert(extras->begin(), extras->end());
3531 LogPrintf(
"%s: %s\n", __func__, wtxNew.
tx->ToString());
3534 if (opReservekey) opReservekey->
KeepKey();
3541 if (!wtxNew.
tx->HasZerocoinSpendInputs()) {
3542 std::set<uint256> updated_hashes;
3543 for (
const CTxIn& txin : wtxNew.
tx->vin) {
3545 if (updated_hashes.find(txin.
prevout.
hash) != updated_hashes.end())
continue;
3567 res.
status = CWallet::CommitStatus::Abandoned;
3569 if (opReservekey) opReservekey->
ReturnKey();
3572 LogPrintf(
"%s: ERROR: %s\n", __func__, res.
ToString());
3590 if (
database->Rewrite(
"\x04pool")) {
3592 m_spk_man->set_pre_split_keypool.clear();
3603 return nLoadWalletRet;
3615 if (
database->Rewrite(
"\x04pool")) {
3617 m_spk_man->set_pre_split_keypool.clear();
3625 return nZapWalletTxRet;
3648 if (!strPurpose.empty())
3667 for (
const std::pair<std::string, std::string> & item :
mapAddressBook[address].destdata) {
3731 return m_spk_man->KeypoolCountExternalKeys();
3748 uint8_t changeType = staking ? HDChain::ChangeType::STAKING : (
internal ? HDChain::ChangeType::INTERNAL : HDChain::ChangeType::EXTERNAL);
3749 m_spk_man->ReturnDestination(nIndex, changeType, address);
3754 return m_spk_man->GetKeyFromPool(result, type);
3764 std::map<CTxDestination, CAmount> balances;
3768 for (
const auto& walletEntry :
mapWallet) {
3769 const CWalletTx* pcoin = &walletEntry.second;
3784 for (
unsigned int i = 0; i < pcoin->
tx->vout.size(); i++) {
3794 if (!balances.count(addr))
3796 balances[addr] += n;
3807 std::set<std::set<CTxDestination> > groupings;
3808 std::set<CTxDestination> grouping;
3810 for (
const auto& walletEntry :
mapWallet) {
3811 const CWalletTx* pcoin = &walletEntry.second;
3813 if (pcoin->
tx->vin.size() > 0) {
3814 bool any_mine =
false;
3816 for (
CTxIn txin : pcoin->
tx->vin) {
3822 grouping.insert(address);
3828 for (
CTxOut txout : pcoin->
tx->vout)
3833 grouping.insert(txoutAddr);
3836 if (grouping.size() > 0) {
3837 groupings.insert(grouping);
3843 for (
unsigned int i = 0; i < pcoin->
tx->vout.size(); i++)
3848 grouping.insert(address);
3849 groupings.insert(grouping);
3854 std::set<std::set<CTxDestination>*> uniqueGroupings;
3855 std::map<CTxDestination, std::set<CTxDestination>*> setmap;
3856 for (std::set<CTxDestination> grouping : groupings) {
3858 std::set<std::set<CTxDestination>*> hits;
3859 std::map<CTxDestination, std::set<CTxDestination>*>::iterator it;
3861 if ((it = setmap.find(address)) != setmap.end())
3862 hits.insert((*it).second);
3865 std::set<CTxDestination>* merged =
new std::set<CTxDestination>(grouping);
3866 for (std::set<CTxDestination>* hit : hits) {
3867 merged->insert(hit->begin(), hit->end());
3868 uniqueGroupings.erase(hit);
3871 uniqueGroupings.insert(merged);
3875 setmap[element] = merged;
3878 std::set<std::set<CTxDestination> > ret;
3879 for (std::set<CTxDestination>* uniqueGrouping : uniqueGroupings) {
3880 ret.insert(*uniqueGrouping);
3881 delete uniqueGrouping;
3890 std::set<CTxDestination> result;
3892 if (item.second.isShielded())
continue;
3893 const auto& address = boost::get<CTxDestination>(item.first);
3894 const std::string& strName = item.second.name;
3895 if (strName == label)
3896 result.insert(address);
3913 internal = _internal;
3916 uint8_t changeType =
internal ? HDChain::ChangeType::INTERNAL : HDChain::ChangeType::EXTERNAL;
3918 if (!
m_spk_man->GetReservedKey(changeType, nIndex, keypool))
3927 assert(vchPubKey.IsValid());
3935 pwallet->KeepKey(nIndex);
3943 pwallet->ReturnKey(nIndex,
internal);
4029 mapKeyBirth.clear();
4033 if (entry.second.nCreateTime) mapKeyBirth[entry.first] = entry.second.nCreateTime;
4038 std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock;
4040 if (mapKeyBirth.count(keyid) == 0)
4041 mapKeyFirstBlock[keyid] = pindexMax;
4045 if (mapKeyFirstBlock.empty())
4049 std::vector<CKeyID> vAffected;
4056 int nHeight = pindex->
nHeight;
4057 for (
const CTxOut& txout : wtx.
tx->vout) {
4060 for (
const CKeyID& keyid : vAffected) {
4062 std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid);
4063 if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight)
4064 rit->second = pindex;
4072 for (
const auto& entry : mapKeyFirstBlock)
4073 mapKeyBirth[entry.first] = entry.second->
GetBlockTime() - TIMESTAMP_WINDOW;
4101 std::vector<std::string> values;
4103 for (
const auto& data : address.second.destdata) {
4105 values.emplace_back(data.second);
4116 if (m_last_block_processed.IsNull() ||
4123 std::map<CTxDestination, std::vector<COutput> > mapCoinsByAddress =
4127 for (
const auto& entry : mapCoinsByAddress) {
4128 std::vector<COutput> vCoins, vRewardCoins;
4129 bool maxSize =
false;
4130 vCoins = entry.second;
4134 unsigned int txSizeEstimate = 90;
4138 CAmount nTotalRewardsValue = 0;
4139 for (
const COutput& out : vCoins) {
4140 if (!out.fSpendable)
4143 COutPoint outpt(out.tx->GetHash(), out.i);
4144 coinControl->
Select(outpt);
4145 vRewardCoins.push_back(out);
4146 nTotalRewardsValue += out.Value();
4153 txSizeEstimate += 190;
4154 if (txSizeEstimate >= MAX_STANDARD_TX_SIZE - 200) {
4165 if (vRewardCoins.size() <= 1)
4168 std::vector<CRecipient> vecSend;
4170 vecSend.emplace_back(scriptPubKey, nTotalRewardsValue,
false);
4175 LogPrintf(
"AutoCombineDust: failed to extract destination\n");
4185 int nChangePosInOut = -1;
4188 vecSend[0].nAmount = nTotalRewardsValue - (nTotalRewardsValue / 10);
4193 if (!
CreateTransaction(vecSend, wtx, keyChange, nFeeRet, nChangePosInOut, strErr, coinControl,
4195 LogPrintf(
"AutoCombineDust createtransaction failed, reason: %s\n", strErr);
4201 if (!maxSize && vecSend[0].nAmount < nAutoCombineThreshold && nFeeRet > 0)
4206 LogPrintf(
"AutoCombineDust transaction commit failed\n");
4210 LogPrintf(
"AutoCombineDust sent transaction. Fee=%d, Total value=%d, Sending=%d\n", nFeeRet, nTotalRewardsValue, vecSend[0].nAmount);
4225 if (ptx && c.
hash == ptx->GetHash() && c.
n < ptx->vout.size()) {
4227 txout = ptx->vout[c.
n];
4232 txout = it->second.tx->vout[c.
n];
4253 const std::string& walletFile =
name;
4256 std::vector<CWalletTx> vWtx;
4262 DBErrors nZapWalletRet = tempWallet->ZapWalletTx(vWtx);
4264 UIError(
strprintf(
_(
"Error loading %s: Wallet corrupted"), walletFile));
4272 bool fFirstRun =
true;
4277 UIError(
strprintf(
_(
"Error loading %s: Wallet corrupted"), walletFile));
4280 UIWarning(
strprintf(
_(
"Warning: error reading %s! All keys read correctly, but transaction data"
4281 " or address book entries might be missing or incorrect."), walletFile));
4283 UIError(
strprintf(
_(
"Error loading %s: Wallet requires newer version of %s"), walletFile,
PACKAGE_NAME));
4289 UIError(
strprintf(
_(
"Error loading %s\n"), walletFile));
4296 LogPrintf(
"WARNING: stake split threshold value %s too low. Restoring to minimum value %s.\n",
4301 int prev_version = walletInstance->
GetVersion();
4305 if (
gArgs.
GetBoolArg(
"-upgradewallet", fFirstRun && !fLegacyWallet) ||
4307 if (prev_version <= FEATURE_PRE_PIVX && walletInstance->
IsLocked()) {
4309 UIError(
_(
"Cannot upgrade a locked wallet."));
4313 int nMaxVersion =
gArgs.
GetArg(
"-upgradewallet", 0);
4314 if (nMaxVersion == 0)
4320 LogPrintf(
"Allowing wallet upgrade up to %i\n", nMaxVersion);
4322 if (nMaxVersion < walletInstance->
GetVersion()) {
4323 UIError(
_(
"Cannot downgrade wallet."));
4333 std::string upgradeError;
4334 if (!walletInstance->
Upgrade(upgradeError, prev_version)) {
4335 UIError(upgradeError);
4341 if (!fLegacyWallet) {
4343 LogPrintf(
"Creating HD Wallet\n");
4348 if (!
Params().IsRegTestNet()) {
4349 UIError(
"Legacy wallets can only be created on RegTest.");
4353 LogPrintf(
"Creating Pre-HD Wallet\n");
4360 UIError(
_(
"Unable to generate initial key!"));
4367 LogPrintf(
"Wallet completed loading in %15dms\n",
GetTimeMillis() - nStart);
4386 walletInstance->m_last_block_processed = tip->
GetBlockHash();
4387 walletInstance->m_last_block_processed_height = tip->
nHeight;
4388 walletInstance->m_last_block_processed_time = tip->
GetBlockTime();
4407 UIError(
_(
"Failed to rescan the wallet during initialization"));
4411 UIError(
_(
"Shutdown requested over the txs scan. Exiting."));
4415 LogPrintf(
"Rescan completed in %15dms\n",
GetTimeMillis() - nWalletRescanTime);
4417 walletInstance->
database->IncrementUpdateCounter();
4423 uint256 hash = wtxOld.GetHash();
4424 std::map<uint256, CWalletTx>::iterator mi = walletInstance->
mapWallet.find(hash);
4425 if (mi != walletInstance->
mapWallet.end()) {
4440 return walletInstance;
4465 type = HDChain::ChangeType::EXTERNAL;
4466 m_pre_split =
false;
4472 vchPubKey = vchPubKeyIn;
4474 m_pre_split =
false;
4479 assert(pwallet !=
nullptr);
4481 if (isUnconfirmed() || isAbandoned())
return 0;
4483 return (pwallet->GetLastBlockHeight() - m_confirm.block_height + 1) * (isConflicted() ? -1 : 1);
4488 if (!(IsCoinBase() || IsCoinStake()))
4490 return std::max(0, (
Params().GetConsensus().nCoinbaseMaturity + 1) - GetDepthInMainChain());
4495 if (!IsCoinBase() && !IsCoinStake())
return false;
4496 const int depth = GetDepthInMainChain();
4497 return (depth > 0 && depth <=
Params().GetConsensus().nCoinbaseMaturity);
4515 bool fMissingInputs;
4517 fInMempool = fAccepted;
4519 if (fMissingInputs) {
4522 state.
Invalid(
false, REJECT_INVALID,
"Missing inputs");
4606 throw std::runtime_error(
"CWallet::GetCredit() : value out of range");
4613 throw std::runtime_error(
"CWallet::GetChange() : value out of range");
4619 for (
const CTxOut& txout : tx->vout)
4631 if (tx->IsShieldedTx()) {
4645 for (
const CTxIn& txin : tx->vin) {
4647 if (!
Params().GetConsensus().MoneyRange(nDebit))
4648 throw std::runtime_error(
"CWallet::GetDebit() : value out of range");
4653 if (tx->hasSaplingData()) {
4664 for (
unsigned int i = 0; i < tx.
tx->vout.size(); i++) {
4670 if (tx.
tx->hasSaplingData()) {
4671 nCredit +=
m_sspk_man->GetCredit(tx, filter,
false);
4675 if (!
Params().GetConsensus().MoneyRange(nCredit))
4676 throw std::runtime_error(
"CWallet::GetCredit() : value out of range");
4683 for (
const CTxOut& txout : tx->vout) {
4685 if (!
Params().GetConsensus().MoneyRange(nChange))
4686 throw std::runtime_error(
"CWallet::GetChange() : value out of range");
4698 return m_spk_man->GetStakingKeyPoolSize();
4712 throw std::runtime_error(
"Cannot generate shielded addresses. Start with -upgradewallet in order to upgrade a non-HD wallet to HD and Sapling features");
4715 auto address =
m_sspk_man->GenerateNewSaplingZKey();
4736 const std::vector<unsigned char> &vchCryptedSecret) {
return m_sspk_man->AddCryptedSaplingSpendingKeyDB(extfvk, vchCryptedSecret); }
4742 const std::vector<unsigned char> &vchCryptedSecret) {
return m_sspk_man->LoadCryptedSaplingZKey(extfvk, vchCryptedSecret); }
4752 : tx(
std::move(arg))
4779 bool fConflicted =
false;
4805 for (
const CTxIn& txin :
tx->vin) {
4808 if (parent ==
nullptr)
4820 fConflicted = (ret == 0 && !
InMempool());
4828 for (
auto& txin : tx1.vin) txin.scriptSig =
CScript();
4829 for (
auto& txin : tx2.vin) txin.scriptSig =
CScript();
4855 for (
const std::pair<SaplingOutPoint, SaplingNoteData> nd : noteData) {
4856 if (nd.first.n <
tx->sapData->vShieldedOutput.size()) {
4859 throw std::logic_error(
"CWalletTx::SetSaplingNoteData(): Invalid note");
4874 auto output = this->
tx->sapData->vShieldedOutput[op.
n];
4878 output.encCiphertext,
4880 output.ephemeralKey,
4882 assert(
static_cast<bool>(maybe_pt));
4883 auto notePt = maybe_pt.get();
4885 auto maybe_pa = nd.ivk->address(notePt.d);
4886 assert(
static_cast<bool>(maybe_pa));
4887 auto pa = maybe_pa.get();
4889 return std::make_pair(notePt, pa);
4896 auto output = this->
tx->sapData->vShieldedOutput[op.
n];
4898 for (
const auto& ovk : ovks) {
4900 output.outCiphertext,
4904 output.ephemeralKey);
4910 output.encCiphertext,
4911 output.ephemeralKey,
4915 assert(
static_cast<bool>(maybe_pt));
4916 auto notePt = maybe_pt.get();
4961 return boost::get<CTxDestination>(&
it->first);
4966 return boost::get<libzcash::SaplingPaymentAddress>(&
it->first);
int64_t CAmount
Amount in PIV (Can be negative)
const CChainParams & Params()
Return the currently selected parameters.
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
static std::unique_ptr< BerkeleyDatabase > Create(const fs::path &path)
Return object for accessing database at specified path.
std::map< CWDestination, AddressBook::CAddressBookData >::iterator it
const libzcash::SaplingPaymentAddress * GetShieldedDestKey()
const CWDestination * GetDestKey()
const CTxDestination * GetCTxDestKey()
void operator()(const CScriptID &scriptId)
void Process(const CScript &script)
CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector< CKeyID > &vKeysIn)
std::vector< CKeyID > & vKeys
const CKeyStore & keystore
void operator()(const CKeyID &keyId)
void operator()(const CNoDestination &none)
void operator()(const CExchangeKeyID &keyId)
virtual bool RemoveWatchOnly(const CScript &dest)
virtual bool AddWatchOnly(const CScript &dest)
Support for Watch-only addresses.
virtual bool AddCScript(const CScript &redeemScript)
Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki.
virtual bool HaveWatchOnly() const
virtual bool GetSaplingIncomingViewingKey(const libzcash::SaplingPaymentAddress &addr, libzcash::SaplingIncomingViewingKey &ivkOut) const
WatchOnlySet setWatchOnly
std::vector< CTransactionRef > vtx
The block chain is a tree shaped structure starting with the genesis block at the root,...
CBlockIndex * pprev
pointer to the index of the predecessor of this block
uint256 GetBlockHash() const
int64_t GetBlockTime() const
int64_t GetBlockTimeMax() const
uint256 hashFinalSaplingRoot
int nHeight
height of the entry in the chain. The genesis block has height 0
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
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...
CBlockIndex * Tip(bool fProofOfStake=false) const
Returns the index entry for the tip of this chain, or nullptr if none.
CBlockLocator GetLocator(const CBlockIndex *pindex=nullptr) const
Return a CBlockLocator that refers to a block in this chain (by default the tip).
int Height() const
Return the maximal height in the chain.
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
CBlockIndex * FindEarliestAtLeast(int64_t nTime) const
Find the earliest block with timestamp equal or greater than the given.
const Consensus::Params & GetConsensus() const
boost::signals2::signal< void(const std::string &message)> InitMessage
Progress message during initialization.
boost::signals2::signal< bool(const std::string &message, const std::string &caption, unsigned int style), boost::signals2::last_value< bool > > ThreadSafeMessageBox
Show message box.
boost::signals2::signal< void(CWallet *wallet)> LoadWallet
A wallet has been loaded.
bool IsSelected(const BaseOutPoint &output) const
CFeeRate nFeeRate
Feerate to use if overrideFeeRate is true.
void Select(const BaseOutPoint &output, CAmount value=0, bool isP2CS=false)
void ListSelected(std::vector< OutPointWrapper > &vOutpoints) const
bool fAllowWatchOnly
Includes watch only addresses which are solvable.
bool fOverrideFeeRate
Override estimated feerate.
CTxDestination destChange
bool fAllowOtherInputs
If false, allows unselected inputs, but requires all selected inputs be used.
CAmount nMinimumTotalFee
Minimum absolute fee (not per kilobyte)
void ForEachNode(Callable &&func)
Encryption/decryption context with key information.
bool Encrypt(const CKeyingMaterial &vchPlaintext, std::vector< unsigned char > &vchCiphertext) const
bool SetKeyFromPassphrase(const SecureString &strKeyData, const std::vector< unsigned char > &chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod)
bool Decrypt(const std::vector< unsigned char > &vchCiphertext, CKeyingMaterial &vchPlaintext) const
bool GetKey(const CKeyID &address, CKey &keyOut) const override
static bool DecryptKey(const CKeyingMaterial &vMasterKey, const std::vector< unsigned char > &vchCryptedSecret, const CPubKey &vchPubKey, CKey &key)
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Add a key to the store.
bool UnlockSaplingKeys(const CKeyingMaterial &vMasterKeyIn, bool fDecryptionThoroughlyChecked)
bool EncryptKeys(CKeyingMaterial &vMasterKeyIn)
will encrypt previously unencrypted keys
virtual bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret)
CKeyingMaterial vMasterKey
CryptedKeyMap mapCryptedKeys
std::set< CKeyID > GetKeys() const override
boost::signals2::signal< void(CCryptoKeyStore *wallet)> NotifyStatusChanged
Wallet status (encrypted, locked) changed.
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
A reference to a CKey: the Hash160 of its serialized public key, special case for exchange key.
Fee rate in PIV per kilobyte: CAmount / kB.
CAmount GetFee(size_t size) const
CAmount GetFeePerK() const
An encapsulated private key.
CPrivKey GetPrivKey() const
Convert the private key to a CPrivKey (serialized secp256k1 private key data).
CPubKey GetPubKey() const
Compute the public key from a private key.
A reference to a CKey: the Hash160 of its serialized public key.
CPubKey vchPubKey
The public key.
A virtual base class for key stores.
RecursiveMutex cs_KeyStore
virtual bool HaveKey(const CKeyID &address) const =0
Check whether a key corresponding to a given address is present in the store.
virtual bool GetCScript(const CScriptID &hash, CScript &redeemScriptOut) const =0
Private key encryption is done based on a CMasterKey, which holds a salt and random encryption key.
std::vector< unsigned char > vchSalt
unsigned int nDerivationMethod
0 = EVP_sha512() 1 = scrypt()
std::vector< unsigned char > vchCryptedKey
unsigned int nDeriveIterations
Information about a peer.
void PushInventory(const CInv &inv)
An outpoint - a combination of a transaction hash and an index n into its vout.
bool GetTxOutFrom(CTxOut &out) const override
CAmount GetValue() const override
An encapsulated public key.
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
A key allocated from the key pool.
void scheduleEvery(Function f, int64_t deltaMilliSeconds)
Serialized script, used inside transaction inputs and outputs.
A reference to a CScript: the Hash160 of its serialization (see script.h)
bool IsSporkActive(SporkId nSporkID)
CStakeableOutput(const CWalletTx *txIn, int iIn, int nDepthIn, const CBlockIndex *&pindex)
Record info about last stake attempt:
void SetLastTime(const uint64_t lastTime)
void SetLastTries(const int tries)
void SetLastCoins(const int coins)
void SetLastTip(const CBlockIndex *lastTip)
The basic transaction that is broadcasted on the network and contained in blocks.
bool HasZerocoinSpendInputs() const
bool IsShieldedTx() const
SigVersion GetRequiredSigVersion() const
const uint256 & GetHash() const
Optional< SaplingTxData > sapData
std::vector< CTxOut > vout
An input of a transaction.
bool IsZerocoinSpend() const
CTxMemPoolEntry stores data about the corresponding transaction, as well as data about all in-mempool...
bool TransactionWithinChainLimit(const uint256 &txid, size_t chainLimit) const
Returns false if the transaction is in the mempool and not within the chain limit specified.
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
Try to calculate all in-mempool ancestors of entry.
bool exists(uint256 hash) const
std::set< txiter, CompareIteratorByHash > setEntries
An output of a transaction.
bool IsZerocoinMint() const
Capture information about block/transaction validation.
bool Invalid(bool ret=false, unsigned int _chRejectCode=0, const std::string &_strRejectReason="", const std::string &_strDebugMessage="")
std::string GetRejectReason() const
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances,...
WalletBatch * encrypted_batch
std::map< CWDestination, AddressBook::CAddressBookData > mapAddressBook
Destination --> label/purpose mapping.
std::map< uint256, CWalletTx > mapWallet
bool 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.
int nWalletMaxVersion
the maximum wallet format version: memory-only variable that specifies to what version this wallet ma...
void GetKeyBirthTimes(std::map< CKeyID, int64_t > &mapKeyBirth) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
static CWallet * CreateWalletFromFile(const std::string &name, const fs::path &path)
void IncrementNoteWitnesses(const CBlockIndex *pindex, const CBlock *pblock, SaplingMerkleTree &saplingTree)
pindex is the new tip being connected.
bool LoadCryptedSaplingZKey(const libzcash::SaplingExtendedFullViewingKey &extfvk, const std::vector< unsigned char > &vchCryptedSecret)
Adds an encrypted spending key to the store, without saving it to disk (used by LoadWallet)
MasterKeyMap mapMasterKeys
boost::signals2::signal< void(const CAmount stakeSplitThreshold)> NotifySSTChanged
notify stake-split threshold changed
std::string m_name
Wallet filename from wallet=<path> command line or config option.
void DecrementNoteWitnesses(const CBlockIndex *pindex)
pindex is the old tip being disconnected.
bool LoadSaplingZKeyMetadata(const libzcash::SaplingIncomingViewingKey &ivk, const CKeyMetadata &meta)
Load spending key metadata (used by LoadWallet)
CStakerStatus * pStakerStatus
void LockOutpointIfMine(const CTransactionRef &ptx, const COutPoint &c)
bool fDecryptionThoroughlyChecked
keeps track of whether Unlock has run a thorough check before
void AutoCombineDust(CConnman *connman)
std::unique_ptr< ScriptPubKeyMan > m_spk_man
Key manager //.
int GetVersion()
get the current wallet format (the oldest client version guaranteed to understand this wallet)
bool AddSaplingZKey(const libzcash::SaplingExtendedSpendingKey &key)
Adds Sapling spending key to the store, and saves it to disk.
CWallet(std::string name, std::unique_ptr< WalletDatabase > dbw_in)
Construct wallet with specified name and database implementation.
int64_t nRelockTime
Lock Wallet Holds a timestamp at which point the wallet is scheduled (externally) to be relocked.
boost::signals2::signal< void(CWallet *wallet, const uint256 &hashTx, ChangeType status)> NotifyTransactionChanged
Wallet transaction added, removed or updated.
void LockOutpointIfMineWithMutex(const CTransactionRef &ptx, const COutPoint &c)
std::unique_ptr< SaplingScriptPubKeyMan > m_sspk_man
CAmount nStakeSplitThreshold
std::atomic< bool > fAbortRescan
std::set< COutPoint > setLockedCoins
static CAmount minStakeSplitThreshold
minimum accpeted value for stake split threshold
void postInitProcess(CScheduler &scheduler)
Wallet post-init setup Gives the wallet a chance to register repetitive tasks and complete post-init ...
int GetLastBlockHeight() const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Get last block processed height.
bool BackupWallet(const std::string &strDest)
Creates a wallet backup in strDest path.
bool CanSupportFeature(enum WalletFeature wf)
check whether we are allowed to upgrade (or already support) to the named feature
bool LoadMinVersion(int nVersion)
CAmount nAutoCombineThreshold
bool LoadSaplingZKey(const libzcash::SaplingExtendedSpendingKey &key)
Adds spending key to the store, without saving it to disk (used by LoadWallet)
void LockIfMyCollateral(const CTransactionRef &ptx)
std::vector< std::string > GetDestValues(const std::string &prefix) const
Get all destination values matching a prefix.
bool HaveSpendingKeyForPaymentAddress(const libzcash::SaplingPaymentAddress &zaddr) const
Returns true if the wallet contains the spending key.
bool EraseDestData(const CTxDestination &dest, const std::string &key)
Erases a destination data tuple in the store and on disk.
unsigned int GetKeyPoolSize()
std::set< SaplingOutPoint > setLockedNotes
CAmount GetCredit(const CTxOut &txout, const isminefilter &filter) const
std::unique_ptr< WalletDatabase > database
Internal database handle.
static CFeeRate minTxFee
Fees smaller than this (in upiv) are considered zero fee (for transaction creation) We are ~100 times...
boost::signals2::signal< void(bool fHaveWatchOnly)> NotifyWatchonlyChanged
Watch-only address added.
std::atomic< int64_t > nTimeBestReceived
bool fWalletUnlockStaking
bool IsFromMe(const CTransactionRef &tx) const
should probably be renamed to IsRelevantToMe
CAmount GetChange(const CTxOut &txout) const
SaplingScriptPubKeyMan * GetSaplingScriptPubKeyMan() const
std::string GetUniqueWalletBackupName() const
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.
std::map< CKeyID, CKeyMetadata > mapKeyMetadata
int nWalletVersion
the current wallet version: clients below this version are not able to load the wallet
unsigned int GetStakingKeyPoolSize()
libzcash::SaplingPaymentAddress GenerateNewSaplingZKey(std::string label="")
Generates new Sapling key.
static const CAmount DEFAULT_STAKE_SPLIT_THRESHOLD
bool LoadSaplingPaymentAddress(const libzcash::SaplingPaymentAddress &addr, const libzcash::SaplingIncomingViewingKey &ivk)
Adds a Sapling payment address -> incoming viewing key map entry, without saving it to disk (used by ...
void ClearNoteWitnessCache()
clear note witness cache
bool AddSaplingIncomingViewingKeyW(const libzcash::SaplingIncomingViewingKey &ivk, const libzcash::SaplingPaymentAddress &addr)
std::atomic< bool > fScanningWallet
unsigned int nMasterKeyMaxID
boost::signals2::signal< void(CWallet *wallet, const CWDestination &address, const std::string &label, bool isMine, const std::string &purpose, ChangeType status)> NotifyAddressBookChanged
Address book entry changed.
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
bool AddCryptedSaplingSpendingKeyW(const libzcash::SaplingExtendedFullViewingKey &extfvk, const std::vector< unsigned char > &vchCryptedSecret)
static std::atomic< bool > fFlushScheduled
A transaction with a bunch of additional info that only the owner cares about.
Optional< std::pair< libzcash::SaplingNotePlaintext, libzcash::SaplingPaymentAddress > > RecoverSaplingNote(const SaplingOutPoint &op, const std::set< uint256 > &ovks) const
int GetDepthInMainChain() const NO_THREAD_SAFETY_ANALYSIS
Return depth of transaction in blockchain: <0 : conflicts with a transaction this deep in the blockch...
int GetDepthAndMempool(bool &fConflicted) const
bool AcceptToMemoryPool(CValidationState &state) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Pass this transaction to the mempool.
unsigned int nTimeSmart
time received by this node
bool HasP2CSInputs() const
checks whether a tx has P2CS inputs or not
bool IsFromMe(const isminefilter &filter) const
CAmount nShieldedChangeCached
CAmount GetShieldedChange() const
int GetBlocksToMaturity() const
bool IsEquivalentTo(const CWalletTx &tx) const
CAmount GetChange() const
bool isConflicted() const
AmountType
position in ordered transaction list
void SetSaplingNoteData(mapSaplingNoteData_t ¬eData)
static const uint256 ABANDON_HASH
Constant used in hashBlock to indicate tx has been abandoned, only used at serialization/deserializat...
bool fStakeDelegationVoided
Optional< std::pair< libzcash::SaplingNotePlaintext, libzcash::SaplingPaymentAddress > > DecryptSaplingNote(const SaplingOutPoint &op) const
bool fShieldedChangeCached
std::vector< std::pair< std::string, std::string > > vOrderForm
mapSaplingNoteData_t mapSaplingNoteData
bool IsInMainChainImmature() const
CAmount GetShieldedAvailableCredit(bool fUseCache=true) const
void BindWallet(CWallet *pwalletIn)
const uint256 & GetHash() const
unsigned int fTimeReceivedIsTxTime
CachableAmount m_amounts[AMOUNTTYPE_ENUM_ELEMENTS]
void MarkDirty()
make sure balances are recalculated
void Init(const CWallet *pwalletIn)
CWalletTx(const CWallet *pwalletIn, CTransactionRef arg)
unsigned int nTimeReceived
A signature creator that just produces 72-byte empty signatyres.
bool randbool() noexcept
Generate a random boolean.
An outpoint - a combination of a transaction hash and an index n into its sapling output description ...
int64_t GetKeyCreationTime(const libzcash::SaplingIncomingViewingKey &ivk)
void AddToSaplingSpends(const uint256 &nullifier, const uint256 &wtxid)
Keep track of the used nullifier.
CAmount GetCredit(const CWalletTx &tx, const isminefilter &filter, const bool fUnspent=false) const
Return the shielded credit of the tx.
Optional< std::pair< libzcash::SaplingNotePlaintext, libzcash::SaplingPaymentAddress > > TryToRecoverNote(const CWalletTx &tx, const SaplingOutPoint &op)
Try to recover the note using the wallet's ovks (mostly used when the outpoint is a debit)
CAmount GetShieldedChange(const CWalletTx &wtx) const
Return the shielded change of the tx.
A shielded input to a transaction.
uint256 nullifier
The nullifier of the input note.
A signature creator for transactions.
Access to the wallet database.
bool TxnCommit()
Commit current transaction.
bool WriteMasterKey(unsigned int nID, const CMasterKey &kMasterKey)
bool WriteName(const std::string &strAddress, const std::string &strName)
bool WriteMinVersion(int nVersion)
DBErrors ZapWalletTx(CWallet *pwallet, std::vector< CWalletTx > &vWtx)
bool ErasePurpose(const std::string &strAddress)
bool WriteCScript(const uint160 &hash, const CScript &redeemScript)
bool EraseWatchOnly(const CScript &script)
bool WriteCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret, const CKeyMetadata &keyMeta)
bool WriteKey(const CPubKey &vchPubKey, const CPrivKey &vchPrivKey, const CKeyMetadata &keyMeta)
bool EraseDestData(const std::string &address, const std::string &key)
Erase destination data tuple from wallet database.
bool ReadBestBlock(CBlockLocator &locator)
bool WriteOrderPosNext(int64_t nOrderPosNext)
bool WriteTx(const CWalletTx &wtx)
bool TxnBegin()
Begin a new transaction.
bool TxnAbort()
Abort current transaction.
bool WriteWitnessCacheSize(int64_t nWitnessCacheSize)
bool WriteBestBlock(const CBlockLocator &locator)
bool WriteWatchOnly(const CScript &script)
bool EraseTx(uint256 hash)
bool WriteStakeSplitThreshold(const CAmount &nStakeSplitThreshold)
bool WritePurpose(const std::string &strAddress, const std::string &purpose)
bool WriteDestData(const std::string &address, const std::string &key, const std::string &value)
Write destination data key,value tuple to database.
bool EraseName(const std::string &strAddress)
DBErrors LoadWallet(CWallet *pwallet)
RAII object to check and reserve a wallet rescan.
std::string ToString() const
std::string GetHex() const
static libzcash::PedersenHash empty_root()
static Optional< SaplingNotePlaintext > decrypt(const SaplingEncCiphertext &ciphertext, const uint256 &ivk, const uint256 &epk, const uint256 &cmu)
static Optional< SaplingOutgoingPlaintext > decrypt(const SaplingOutCiphertext &ciphertext, const uint256 &ovk, const uint256 &cv, const uint256 &cm, const uint256 &epk)
std::vector< unsigned char, secure_allocator< unsigned char > > CKeyingMaterial
const unsigned int WALLET_CRYPTO_SALT_SIZE
const unsigned int WALLET_CRYPTO_KEY_SIZE
boost::variant< CTxDestination, libzcash::SaplingPaymentAddress > CWDestination
void UnlockCoin(const COutPoint &output)
CAmount GetImmatureDelegatedBalance() const
void GetAvailableP2CSCoins(std::vector< COutput > &vCoins) const
Available coins (P2CS)
CAmount GetImmatureWatchOnlyBalance() const
bool SelectCoinsToSpend(const std::vector< COutput > &vAvailableCoins, const CAmount &nTargetValue, std::set< std::pair< const CWalletTx *, unsigned int > > &setCoinsRet, CAmount &nValueRet, const CCoinControl *coinControl=nullptr) const
Available coins (spending)
CAmount loopTxsBalance(const std::function< void(const uint256 &, const CWalletTx &, CAmount &)> &method) const
int64_t GetOldestKeyPoolTime()
CAmount GetUnconfirmedShieldedBalance() const
static std::string ParseIntoAddress(const CWDestination &dest, const std::string &purpose)
bool DelAddressBook(const CWDestination &address, const CChainParams::Base58Type addrType=CChainParams::PUBKEY_ADDRESS)
CAmount GetDelegatedBalance() const
CAmount GetLegacyBalance(const isminefilter &filter, int minDepth) const
std::map< std::pair< CTxDestination, Optional< CTxDestination > >, std::vector< COutput > > ListCoins() const
Return list of available coins and locked coins grouped by non-change output address.
std::string GetPurposeForAddressBookEntry(const CWDestination &address) const
void LockNote(const SaplingOutPoint &op)
CWallet::CommitResult CommitTransaction(CTransactionRef tx, CReserveKey &opReservekey, CConnman *connman)
bool GetKeyFromPool(CPubKey &key, const uint8_t &type=HDChain::ChangeType::EXTERNAL)
void LoadAddressBookPurpose(const CWDestination &dest, const std::string &strPurpose)
size_t KeypoolCountExternalKeys()
CAmount GetImmatureColdStakingBalance() const
CAmount GetColdStakingBalance() const
bool CreateTransaction(const std::vector< CRecipient > &vecSend, CTransactionRef &txRet, CReserveKey &reservekey, CAmount &nFeeRet, int &nChangePosInOut, std::string &strFailReason, const CCoinControl *coinControl=nullptr, bool sign=true, CAmount nFeePay=0, bool fIncludeDelegated=false, bool *fStakeDelegationVoided=nullptr, int nExtraSize=0, int nMinDepth=0)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
DBErrors LoadWallet(bool &fFirstRunRet)
Balance GetBalance(int min_depth=0) const
std::set< std::set< CTxDestination > > GetAddressGroupings()
int GetLastBlockHeightLockWallet() const
Get last block processed height locking the wallet.
bool SelectCoinsMinConf(const CAmount &nTargetValue, int nConfMine, int nConfTheirs, uint64_t nMaxAncestors, std::vector< COutput > vCoins, std::set< std::pair< const CWalletTx *, unsigned int > > &setCoinsRet, CAmount &nValueRet) const
Select coins until nTargetValue is reached.
CAmount GetLockedShieldCoins() const
bool GetMasternodeVinAndKeys(CPubKey &pubKeyRet, CKey &keyRet, const COutPoint &collateralOut, bool fValidateCollateral, std::string &strError)
Get 10000 PIV output and keys which can be used for the Masternode.
CAmount GetImmatureBalance() const
bool IsLockedNote(const SaplingOutPoint &op) const
CAmount GetLockedCoins() const
std::set< SaplingOutPoint > ListLockedNotes()
DBErrors ZapWalletTx(std::vector< CWalletTx > &vWtx)
CAmount GetStakingBalance(const bool fIncludeColdStaking=true) const
bool FundTransaction(CMutableTransaction &tx, CAmount &nFeeRet, bool overrideEstimatedFeeRate, const CFeeRate &specificFeeRate, int &nChangePosInOut, std::string &strFailReason, bool includeWatching, bool lockUnspents, const std::set< int > &setSubtractFeeFromOutputs, const CTxDestination &destChange=CNoDestination())
void LoadAddressBookName(const CWDestination &dest, const std::string &strName)
bool AvailableCoins(std::vector< COutput > *pCoins, const CCoinControl *coinControl=nullptr, AvailableCoinsFilter coinsFilter=AvailableCoinsFilter()) const
populate vCoins with vector of available COutputs.
bool SetStakeSplitThreshold(const CAmount sst)
bool CreateCoinStake(const CBlockIndex *pindexPrev, unsigned int nBits, CMutableTransaction &txNew, int64_t &nTxNewTime, std::vector< CStakeableOutput > *availableCoins, bool stopOnNewBlock=true) const
CAmount GetWatchOnlyBalance() const
bool TopUpKeyPool(unsigned int kpSize=0)
bool CreateBudgetFeeTX(CTransactionRef &tx, const uint256 &hash, CReserveKey &keyChange, CAmount fee)
std::vector< COutput > GetOutputsFromCoinControl(const CCoinControl *coinControl)
Return the selected known outputs.
std::string GetNameForAddressBookEntry(const CWDestination &address) const
CAmount GetUnconfirmedWatchOnlyBalance() const
bool HasDelegator(const CTxOut &out) const
std::map< libzcash::SaplingPaymentAddress, std::vector< SaplingNoteEntry > > ListNotes() const
Return list of available shield notes and locked shield notes grouped by sapling address.
bool HasAddressBook(const CWDestination &address) const
CAmount GetAvailableBalance(bool fIncludeDelegated=true, bool fIncludeShielded=true) const
OutputAvailabilityResult CheckOutputAvailability(const CTxOut &output, const unsigned int outIndex, const uint256 &wtxid, const CCoinControl *coinControl, const bool fCoinsSelected, const bool fIncludeColdStaking, const bool fIncludeDelegated, const bool fIncludeLocked) const
std::set< COutPoint > ListLockedCoins()
bool SetAddressBook(const CWDestination &address, const std::string &strName, const std::string &purpose)
bool IsLockedCoin(const uint256 &hash, unsigned int n) const
bool GetReservedKey(CPubKey &pubkey, bool internal=false)
CAmount GetUnconfirmedBalance(isminetype filter=ISMINE_SPENDABLE_ALL) const
std::string ToString() const
CAmount GetAvailableShieldedBalance(bool fUseCache=true) const
void LockCoin(const COutPoint &output)
std::map< CTxDestination, CAmount > GetAddressBalances()
bool StakeableCoins(std::vector< CStakeableOutput > *pCoins=nullptr)
Available coins (staking)
void KeepKey(int64_t nIndex)
void ReturnKey(int64_t nIndex, const bool internal=false, const bool staking=false)
Optional< AddressBook::CAddressBookData > GetAddressBookEntry(const CWDestination &address) const
std::set< CTxDestination > GetLabelAddresses(const std::string &label) const
bool CreateCoinstakeOuts(const CPivStake &stakeInput, std::vector< CTxOut > &vout, CAmount nTotal) const
bool SignCoinStake(CMutableTransaction &txNew) const
std::map< CTxDestination, std::vector< COutput > > AvailableCoinsByAddress(bool fConfirmed, CAmount maxCoinValue, bool fIncludeColdStaking)
void UnlockNote(const SaplingOutPoint &op)
CAmount GetImmatureCredit(bool fUseCache=true, const isminefilter &filter=ISMINE_SPENDABLE_ALL) const
std::vector< CWalletTx > getWalletTxs()
CAmount GetImmatureWatchOnlyCredit(const bool fUseCache=true) const
bool IsSaplingSpent(const SaplingOutPoint &op) const
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)
CallResult< CTxDestination > getNewAddress(const std::string &addressLabel, const std::string purpose, const CChainParams::Base58Type addrType=CChainParams::PUBKEY_ADDRESS)
void SyncTransaction(const CTransactionRef &tx, const CWalletTx::Confirmation &confirm)
std::vector< CKeyID > GetAffectedKeys(const CScript &spk)
bool AddCScript(const CScript &redeemScript) override
Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki.
void Flush(bool shutdown=false)
Flush wallet (bitdb flush)
CAmount GetAvailableWatchOnlyCredit(const bool fUseCache=true) const
bool SetMaxVersion(int nVersion)
change which version we're allowed to upgrade to (note that this does not immediately imply upgrading...
bool IsAmountCached(AmountType type, const isminefilter &filter) const
bool LoadKeyMetadata(const CPubKey &pubkey, const CKeyMetadata &metadata)
Load metadata (used by LoadWallet)
ScriptPubKeyMan * GetScriptPubKeyMan() const
Get spkm.
bool AddWatchOnly(const CScript &dest) override
Adds a watch-only address to the store, and saves it to disk.
bool RemoveWatchOnly(const CScript &dest) override
bool Upgrade(std::string &error, const int prevVersion)
Upgrade wallet to HD and Sapling if needed.
const CKeyingMaterial & GetEncryptionKey() const
CAmount GetColdStakingCredit(bool fUseCache=true) const
void EraseFromWallet(const uint256 &hash)
std::set< uint256 > GetConflicts(const uint256 &txid) const
Get wallet transactions that conflict with given transaction (spend same outputs)
bool ChangeWalletPassphrase(const SecureString &strOldWalletPassphrase, const SecureString &strNewWalletPassphrase)
CBlockIndex * ScanForWalletTransactions(CBlockIndex *pindexStart, CBlockIndex *pindexStop, const WalletRescanReserver &reserver, bool fUpdate=false, bool fromStartup=false)
Scan the block chain (starting in pindexStart) for transactions from or to us.
isminetype IsMine(const CTxIn &txin) const
bool 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...
bool LoadToWallet(CWalletTx &wtxIn)
void RelayWalletTransaction(CConnman *connman)
CAmount GetDebit(const CTxIn &txin, const isminefilter &filter) const
bool Unlock(const SecureString &strWalletPassphrase, bool anonimizeOnly=false)
bool AddToWallet(const CWalletTx &wtxIn, bool fFlushOnClose=true)
void AddToSpends(const COutPoint &outpoint, const uint256 &wtxid)
CAmount GetCachableAmount(AmountType type, const isminefilter &filter, bool recalculate=false) const
bool IsKeyUsed(const CPubKey &vchPubKey) const
void UpdateTimeSmart()
Update smart timestamp for a transaction being added to the wallet.
CAmount GetDebit(const isminefilter &filter) const
filter decides which addresses will count towards the debit
void BlockUntilSyncedToCurrentChain()
Blocks until the wallet state is up-to-date to /at least/ the current chain at the time this function...
void SetBestChain(const CBlockLocator &loc) override
Notifies listeners of the new active block chain on-disk.
void UpdateTimeFirstKey(int64_t nCreateTime)
Update wallet first key creation time.
CallResult< CTxDestination > getNewStakingAddress(const std::string &label)
CAmount GetLockedCredit() const
int64_t IncOrderPosNext(WalletBatch *batch=nullptr)
Increment the next transaction order id.
bool AbandonTransaction(const uint256 &hashTx)
bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector< unsigned char > &vchCryptedSecret) override
Adds an encrypted key to the store, and saves it to disk.
void ReacceptWalletTransactions(bool fFirstLoad=false)
bool FindNotesDataAndAddMissingIVKToKeystore(const CTransaction &tx, Optional< mapSaplingNoteData_t > &saplingNoteData)
bool IsHDEnabled() const
Whether the wallet is hd or not //.
void ResendWalletTransactions(CConnman *connman) override
Tells listeners to broadcast their data.
void GetAmounts(std::list< COutputEntry > &listReceived, std::list< COutputEntry > &listSent, CAmount &nFee, const isminefilter &filter) const
void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override
Notifies listeners when the block chain tip advances.
bool EncryptWallet(const SecureString &strWalletPassphrase)
int64_t GetTxTime() const
bool HasSaplingSPKM() const
bool IsChange(const CTxOut &txout) const
int64_t GetKeyCreationTime(const CWDestination &dest)
bool ActivateSaplingWallet(bool memOnly=false)
bool AddToWalletIfInvolvingMe(const CTransactionRef &tx, const CWalletTx::Confirmation &confirm, bool fUpdate)
Add a transaction to the wallet, or update it.
const CWalletTx * GetWalletTx(const uint256 &hash) const
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Adds a key to the store, and saves it to disk.
CAmount GetCredit(const isminefilter &filter, bool recalculate=false) const
int64_t RescanFromTime(int64_t startTime, const WalletRescanReserver &reserver, bool update)
Scan active chain for relevant transactions after importing keys.
CAmount GetColdStakingDebit(bool fUseCache=true) const
void SyncMetaData(std::pair< typename TxSpendMap< T >::iterator, typename TxSpendMap< T >::iterator > range)
void SyncMetaDataN(std::pair< TxSpendMap< uint256 >::iterator, TxSpendMap< uint256 >::iterator > range)
bool LoadWatchOnly(const CScript &dest)
Adds a watch-only address to the store, without saving it to disk (used by LoadWallet)
void SetBestChainInternal(WalletBatch &batch, const CBlockLocator &loc)
std::string ToString() const
bool LoadCScript(const CScript &redeemScript)
bool SetupSPKM(bool newKeypool=true, bool memOnly=false)
Generates hd wallet //.
CAmount GetStakeDelegationDebit(bool fUseCache=true) const
std::set< uint256 > GetConflicts() const
bool IsUsed(const CTxDestination address) const
void TransactionAddedToMempool(const CTransactionRef &tx) override
Notifies listeners of a transaction having been added to mempool.
CAmount GetAvailableCredit(bool fUseCache=true, const isminefilter &filter=ISMINE_SPENDABLE) const
bool HasEncryptionKeys() const
void BlockConnected(const std::shared_ptr< const CBlock > &pblock, const CBlockIndex *pindex) override
Notifies listeners of a block being connected.
void MarkAffectedTransactionsDirty(const CTransaction &tx)
void ChainTipAdded(const CBlockIndex *pindex, const CBlock *pblock, SaplingMerkleTree saplingTree)
CAmount GetStakeDelegationCredit(bool fUseCache=true) const
void AddExternalNotesDataToTx(CWalletTx &wtx) const
void MarkConflicted(const uint256 &hashBlock, int conflicting_height, const uint256 &hashTx)
void TransactionRemovedFromMempool(const CTransactionRef &ptx, MemPoolRemovalReason reason) override
Notifies listeners of a transaction leaving mempool.
bool IsSaplingUpgradeEnabled() const
Whether the wallet supports Sapling or not //.
bool IsSpent(const COutPoint &outpoint) const
Outpoint is spent if any non-conflicted transaction spends it:
void BlockDisconnected(const std::shared_ptr< const CBlock > &pblock, const uint256 &blockHash, int nBlockHeight, int64_t blockTime) override
Notifies listeners of a block being disconnected.
CClientUIInterface uiInterface
uint160 Hash160(const T1 pbegin, const T1 pend)
Compute the 160-bit hash an object.
std::unique_ptr< CConnman > g_connman
isminetype IsMine(const CKeyStore &keystore, const CTxDestination &dest)
isminetype
IsMine() return codes.
@ ISMINE_SPENDABLE_NO_DELEGATED
@ ISMINE_COLD
Indicates that we have the staking key of a P2CS.
@ ISMINE_SPENDABLE_SHIELDED
Indicates that we have the spending key of a shielded spend/output.
@ ISMINE_WATCH_ONLY_SHIELDED
Indicates that we don't have the spending key of a shielded spend/output.
@ ISMINE_SPENDABLE_TRANSPARENT
@ ISMINE_SPENDABLE_DELEGATED
Indicates that we have the spending key of a P2CS.
uint8_t isminefilter
used for bitflags of isminetype
bool Stake(const CBlockIndex *pindexPrev, CStakeInput *stakeInput, unsigned int nBits, int64_t &nTimeTx)
#define LogPrint(category,...)
const std::string DELEGATOR
const std::string SHIELDED_RECEIVE
const std::string RECEIVE
const std::string COLD_STAKING
bool IsExchangePurpose(const std::string &purpose)
bool IsColdStakingPurpose(const std::string &purpose)
double GuessVerificationProgress(const CBlockIndex *pindex, bool fSigchecks)
Guess how far we are in the verification process at the given block index.
const CTxDestination * GetTransparentDestination(const CWDestination &dest)
bool IsValidDestination(const CWDestination &address)
std::string EncodeDestination(const CWDestination &address, const CChainParams::Base58Type addrType)
const libzcash::SaplingPaymentAddress * GetShieldedDestination(const CWDestination &dest)
RecursiveMutex cs_main
Global state.
boost::optional< T > Optional
Substitute for C++17 std::optional.
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
bool GetProRegCollateral(const CTransactionRef &tx, COutPoint &outRet)
void GetStrongRandBytes(unsigned char *buf, int num) noexcept
Gather entropy from various sources, feed it into the internal PRNG, and generate random data using i...
uint64_t GetRand(uint64_t nMax) noexcept
int GetRandInt(int nMax) noexcept
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
std::map< SaplingOutPoint, SaplingNoteData > mapSaplingNoteData_t
std::vector< unsigned char > ToByteVector(const T &in)
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
unsigned int GetSerializeSize(const std::array< T, N > &item)
array
void UpdateTransaction(CMutableTransaction &tx, unsigned int nIn, const SignatureData &data)
bool IsSolvable(const CKeyStore &store, const CScript &script, bool fColdStaking)
bool SignSignature(const CKeyStore &keystore, const CScript &fromPubKey, CMutableTransaction &txTo, unsigned int nIn, const CAmount &amount, int nHashType, bool fColdStake)
Produce a script signature for a transaction.
bool ProduceSignature(const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata, SigVersion sigversion, bool fColdStake, ScriptError *serror)
Produce a script signature using a generic signature creator.
CSporkManager sporkManager
@ SPORK_19_COLDSTAKING_MAINTENANCE
bool ExtractDestinations(const CScript &scriptPubKey, txnouttype &typeRet, std::vector< CTxDestination > &addressRet, int &nRequiredRet)
Parse a standard scriptPubKey with one or more destination addresses.
bool Solver(const CScript &scriptPubKey, txnouttype &typeRet, std::vector< std::vector< unsigned char > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
const char * GetTxnOutputType(txnouttype t)
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a PIVX scriptPubKey for the given CTxDestination.
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet, bool fColdStake)
Parse a standard scriptPubKey for the destination address.
boost::variant< CNoDestination, CKeyID, CScriptID, CExchangeKeyID > CTxDestination
A txout script template with a specific destination.
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
A mutable version of CTransaction.
Optional< std::vector< uint8_t > > extraPayload
Optional< SaplingTxData > sapData
SigVersion GetRequiredSigVersion() const
std::vector< CTxOut > vout
bool isSaplingVersion() const
std::set< CTxDestination > * onlyFilteredDest
CAmount nMinimumSumAmount
unsigned int nMaximumCount
CAmount m_mine_trusted
Trusted, at depth=GetBalance.min_depth or more.
CAmount m_mine_trusted_shield
Trusted shield, at depth=GetBalance.min_depth or more.
CAmount m_mine_untrusted_pending
Untrusted, but in mempool (pending)
CAmount m_mine_immature
Immature coinbases/coinstakes in the main chain.
CAmount m_mine_untrusted_shielded_balance
Untrusted shield, but in mempool (pending)
CAmount m_mine_cs_delegated_trusted
Trusted, at depth=GetBalance.min_depth or more. Part of m_mine_trusted as well.
CWallet::CommitStatus status
void Set(isminefilter filter, CAmount value)
CAmount m_value[ISMINE_ENUM_ELEMENTS]
std::bitset< ISMINE_ENUM_ELEMENTS > m_cached
bool operator()(const std::pair< CAmount, std::pair< const CWalletTx *, unsigned int > > &t1, const std::pair< CAmount, std::pair< const CWalletTx *, unsigned int > > &t2) const
bool NetworkUpgradeActive(int nHeight, Consensus::UpgradeIndex idx) const
Returns true if the given network upgrade is active as of the given block height.
#define AssertLockNotHeld(cs)
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
#define AssertLockHeld(cs)
std::atomic< bool > fMasterNode
void runCommand(std::string strCommand)
bool error(const char *fmt, const Args &... args)
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a Optional result.
#define EXCLUSIVE_LOCKS_REQUIRED(...)
int64_t GetAdjustedTime()
std::shared_ptr< const CTransaction > CTransactionRef
bool IsFinalTx(const CTransactionRef &tx, int nBlockHeight, int64_t nBlockTime)
Check if transaction is final and can be included in a block with the specified height and time.
MemPoolRemovalReason
Reason why a transaction was removed from the mempool, this is passed to the notification signal.
@ BLOCK
Removed for reorganization.
@ CONFLICT
Removed for block.
const uint256 UINT256_ZERO
constant uint256 instances
uint256 uint256S(const char *str)
bool NetworkUpgradeActive(int nHeight, const Consensus::Params ¶ms, Consensus::UpgradeIndex idx)
Returns true if the given network upgrade is active as of the given block height.
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
std::string FormatMoney(const CAmount &n, bool fPlus)
Money parsing/formatting utilities.
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
@ SAFE_CHARS_FILENAME
Chars allowed in filenames.
int64_t GetTimeMillis()
Returns the system time (not mockable)
std::string FormatISO8601DateTimeForBackup(int64_t nTime)
int64_t GetTime()
DEPRECATED Use either GetSystemTimeInSeconds (not mockable) or GetTime<T> (mockable)
bool CheckFinalTx(const CTransactionRef &tx, int flags)
Check if transaction will be final in the next block to be created.
CTxMemPool mempool(::minRelayTxFee)
CFeeRate minRelayTxFee
Fees smaller than this (in upiv) are considered zero fee (for relaying, mining and transaction creati...
std::unique_ptr< CCoinsViewCache > pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
int64_t GetMasternodePayment(int nHeight)
CAmount GetBlockValue(int nHeight)
std::atomic< bool > fImporting
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree, bool *pfMissingInputs, bool fOverrideMempoolLimit, bool fRejectInsaneFee, bool ignoreFees)
(try to) add transaction to memory pool
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos)
std::atomic< bool > fReindex
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
CBlockIndex * FindForkInGlobalIndex(const CChain &chain, const CBlockLocator &locator)
Find the last common block between the parameter chain and a locator.
CBlockIndex * LookupBlockIndex(const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
void RegisterValidationInterface(CValidationInterface *pwalletIn)
Register a wallet to receive updates from core.
void SyncWithValidationInterfaceQueue()
This is a synonym for the following, which asserts certain locks are not held: std::promise<void> pro...
CAmount GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool &pool)
Estimate the minimum fee considering user set parameters and the required fee.
std::vector< CWalletRef > vpwallets
CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE)
Settings.
bool bSpendZeroConfChange
bool fPayAtLeastCustomFee
unsigned int nTxConfirmTarget
bool bdisableSystemnotifications
WalletFeature
(client) version numbers for particular wallet features
@ FEATURE_PRE_SPLIT_KEYPOOL
std::multimap< T, uint256 > TxSpendMap
std::map< std::string, std::string > mapValue_t
void MaybeCompactWalletDB()
Compacts BDB state so that wallet.dat is self-contained (if there are changes)
DBErrors
Error statuses for the wallet database.