24 unsigned int out,
bool use_max_sig) {
37 if (!
wallet->DummySignInput(txn.
vin[0], txout, use_max_sig)) {
46 const std::vector<CTxOut> &txouts,
49 if (!
wallet->DummySignTx(txNew, txouts, use_max_sig)) {
57 std::vector<CTxOut> txouts;
58 for (
auto &input : tx.
vin) {
59 const auto mi =
wallet->mapWallet.find(input.prevout.GetTxId());
61 if (mi ==
wallet->mapWallet.end()) {
64 assert(input.prevout.GetN() < mi->second.tx->vout.size());
65 txouts.emplace_back(mi->second.tx->vout[input.prevout.GetN()]);
72 const Amount nMinimumAmount,
const Amount nMaximumAmount,
73 const Amount nMinimumSumAmount,
74 const uint64_t nMaximumCount) {
83 bool allow_used_addresses =
86 const int min_depth = {coinControl ? coinControl->
m_min_depth
88 const int max_depth = {coinControl ? coinControl->
m_max_depth
91 std::set<TxId> trusted_parents;
92 for (
const auto &entry :
wallet.mapWallet) {
93 const TxId &wtxid = entry.first;
96 if (
wallet.IsTxImmatureCoinBase(wtx)) {
100 int nDepth =
wallet.GetTxDepthInMainChain(wtx);
130 if (nDepth == 0 && wtx.
mapValue.count(
"replaced_by_txid")) {
134 if (fOnlySafe && !safeTx) {
138 if (nDepth < min_depth || nDepth > max_depth) {
142 for (uint32_t i = 0; i < wtx.
tx->vout.size(); i++) {
149 if (wtx.
tx->vout[i].nValue < nMinimumAmount ||
150 wtx.
tx->vout[i].nValue > nMaximumAmount) {
162 if (
wallet.IsLockedCoin(outpoint)) {
166 if (
wallet.IsSpent(outpoint)) {
176 if (!allow_used_addresses &&
wallet.IsSpentKey(wtxid, i)) {
180 std::unique_ptr<SigningProvider> provider =
181 wallet.GetSolvingProvider(wtx.
tx->vout[i].scriptPubKey);
184 provider ?
IsSolvable(*provider, wtx.
tx->vout[i].scriptPubKey)
197 nTotal += wtx.
tx->vout[i].nValue;
199 if (nTotal >= nMinimumSumAmount) {
205 if (nMaximumCount > 0 &&
vCoins.size() >= nMaximumCount) {
217 std::vector<COutput>
vCoins;
220 if (out.fSpendable) {
221 balance += out.tx->tx->vout[out.i].nValue;
235 if (it ==
wallet.mapWallet.end() ||
236 it->second.tx->vout.size() <= prevout.
GetN() ||
237 !
wallet.IsMine(it->second.tx->vout[prevout.
GetN()])) {
240 ptx = it->second.tx.get();
246 std::map<CTxDestination, std::vector<COutput>>
250 std::map<CTxDestination, std::vector<COutput>> result;
251 std::vector<COutput> availableCoins;
255 for (
const auto &coin : availableCoins) {
257 if ((coin.fSpendable ||
264 result[address].emplace_back(std::move(coin));
268 std::vector<COutPoint> lockedCoins;
269 wallet.ListLockedCoins(lockedCoins);
271 const bool include_watch_only =
272 wallet.GetLegacyScriptPubKeyMan() &&
276 for (
const auto &output : lockedCoins) {
277 auto it =
wallet.mapWallet.find(output.GetTxId());
278 if (it !=
wallet.mapWallet.end()) {
279 int depth =
wallet.GetTxDepthInMainChain(it->second);
280 if (depth >= 0 && output.GetN() < it->second.tx->vout.size() &&
281 wallet.IsMine(it->second.tx->vout[output.GetN()]) ==
289 result[address].emplace_back(
290 wallet, it->second, output.GetN(), depth,
302 const std::vector<COutput> &outputs,
304 const size_t max_ancestors) {
305 std::vector<OutputGroup> groups;
306 std::map<CTxDestination, OutputGroup> gmap;
307 std::set<CTxDestination> full_groups;
309 for (
const auto &output : outputs) {
310 if (output.fSpendable) {
312 CInputCoin input_coin = output.GetInputCoin();
317 size_t ancestors = 0, descendants = 0;
322 auto it = gmap.find(dst);
323 if (it != gmap.end()) {
330 if (it->second.m_outputs.size() >=
332 groups.push_back(it->second);
334 full_groups.insert(dst);
337 input_coin, output.nDepth,
339 ancestors, descendants);
342 input_coin, output.nDepth,
344 ancestors, descendants);
348 input_coin, output.nDepth,
355 for (
auto &it : gmap) {
356 auto &group = it.second;
357 if (full_groups.count(it.first) > 0) {
360 group.m_ancestors = max_ancestors - 1;
362 groups.push_back(group);
370 std::vector<OutputGroup> groups,
371 std::set<CInputCoin> &setCoinsRet,
Amount &nValueRet,
377 std::vector<OutputGroup> utxo_pool;
385 Amount cost_of_change =
wallet.chain().relayDustFee().GetFee(
393 if (!group.EligibleForSpending(eligibility_filter)) {
410 utxo_pool.push_back(pos_group);
418 setCoinsRet, nValueRet, not_input_fees);
422 if (!group.EligibleForSpending(eligibility_filter)) {
425 utxo_pool.push_back(group);
428 return KnapsackSolver(nTargetValue, utxo_pool, setCoinsRet, nValueRet);
433 const std::vector<COutput> &vAvailableCoins,
434 const Amount nTargetValue, std::set<CInputCoin> &setCoinsRet,
437 std::vector<COutput>
vCoins(vAvailableCoins);
438 Amount value_to_select = nTargetValue;
447 if (!out.fSpendable) {
451 nValueRet += out.tx->tx->vout[out.i].nValue;
452 setCoinsRet.insert(out.GetInputCoin());
455 return (nValueRet >= nTargetValue);
459 std::set<CInputCoin> setPresetCoins;
462 std::vector<COutPoint> vPresetInputs;
465 for (
const COutPoint &outpoint : vPresetInputs) {
466 std::map<TxId, CWalletTx>::const_iterator it =
467 wallet.mapWallet.find(outpoint.GetTxId());
468 if (it !=
wallet.mapWallet.end()) {
471 if (wtx.
tx->vout.size() <= outpoint.GetN()) {
476 wtx.
tx, outpoint.GetN(),
491 setPresetCoins.insert(coin);
498 for (std::vector<COutput>::iterator it =
vCoins.begin();
500 if (setPresetCoins.count(it->GetInputCoin())) {
509 size_t max_ancestors{0};
510 size_t max_descendants{0};
511 wallet.chain().getPackageLimits(max_ancestors, max_descendants);
535 (
wallet.m_spend_zero_conf_change &&
539 (
wallet.m_spend_zero_conf_change &&
543 std::min((
size_t)4, max_descendants / 3)),
546 (
wallet.m_spend_zero_conf_change &&
549 max_descendants / 2),
550 groups, setCoinsRet, nValueRet,
552 (
wallet.m_spend_zero_conf_change &&
555 max_descendants - 1),
556 groups, setCoinsRet, nValueRet,
558 (
wallet.m_spend_zero_conf_change &&
569 nValueRet += nValueFromPresetInputs;
585 :
wallet.m_default_change_type,
588 int nChangePosRequest = nChangePosInOut;
589 unsigned int nSubtractFeeFromAmount = 0;
590 for (
const auto &recipient : vecSend) {
592 error =
_(
"Transaction amounts must not be negative");
596 nValue += recipient.nAmount;
598 if (recipient.fSubtractFeeFromAmount) {
599 nSubtractFeeFromAmount++;
603 if (vecSend.empty()) {
604 error =
_(
"Transaction must have at least one recipient");
611 std::set<CInputCoin> setCoins;
620 std::vector<COutput> vAvailableCoins;
631 if (!boost::get<CNoDestination>(&coin_control.
destChange)) {
649 error =
_(
"Transaction needs a change address, but we can't "
650 "generate it. Please call keypoolrefill first.");
668 nFeeRateNeeded > *coin_control.
m_feerate) {
670 "rate setting (%s)"),
677 bool pick_new_inputs =
true;
686 nSubtractFeeFromAmount != 0;
689 nChangePosInOut = nChangePosRequest;
694 Amount nValueToSelect = nValue;
695 if (nSubtractFeeFromAmount == 0) {
696 nValueToSelect += nFeeRet;
706 for (
const auto &recipient : vecSend) {
707 CTxOut txout(recipient.nAmount, recipient.scriptPubKey);
709 if (recipient.fSubtractFeeFromAmount) {
710 assert(nSubtractFeeFromAmount != 0);
712 txout.
nValue -= nFeeRet / int(nSubtractFeeFromAmount);
718 txout.
nValue -= nFeeRet % int(nSubtractFeeFromAmount);
730 if (recipient.fSubtractFeeFromAmount &&
733 error =
_(
"The transaction amount is too small to "
736 error =
_(
"The transaction amount is too small to "
737 "send after the fee has been deducted");
740 error =
_(
"Transaction amount too small");
746 txNew.
vout.push_back(txout);
750 bool bnb_used =
false;
751 if (pick_new_inputs) {
755 change_prototype_txout, &
wallet);
758 if (change_spend_size == -1) {
763 size_t(change_spend_size);
767 setCoins, nValueIn, coin_control,
775 error =
_(
"Insufficient funds");
783 const Amount nChange = nValueIn - nValueToSelect;
786 CTxOut newTxOut(nChange, scriptChange);
793 nChangePosInOut = -1;
796 if (nChangePosInOut == -1) {
799 }
else if ((
unsigned int)nChangePosInOut >
801 error =
_(
"Change index out of range");
805 std::vector<CTxOut>::iterator position =
806 txNew.
vout.begin() + nChangePosInOut;
807 txNew.
vout.insert(position, newTxOut);
810 nChangePosInOut = -1;
815 for (
const auto &coin : setCoins) {
823 error =
_(
"Signing transaction failed");
829 if (nFeeRet >= nFeeNeeded) {
840 if (nChangePosInOut == -1 && nSubtractFeeFromAmount == 0 &&
844 unsigned int tx_size_with_change =
847 wallet, tx_size_with_change, coin_control);
849 change_prototype_txout,
wallet.chain().relayDustFee());
851 fee_needed_with_change + minimum_value_for_change) {
852 pick_new_inputs =
false;
853 nFeeRet = fee_needed_with_change;
859 if (nFeeRet > nFeeNeeded && nChangePosInOut != -1 &&
860 nSubtractFeeFromAmount == 0) {
861 Amount extraFeePaid = nFeeRet - nFeeNeeded;
862 std::vector<CTxOut>::iterator change_position =
863 txNew.
vout.begin() + nChangePosInOut;
864 change_position->nValue += extraFeePaid;
865 nFeeRet -= extraFeePaid;
870 }
else if (!pick_new_inputs) {
875 error =
_(
"Transaction fee and change calculation failed");
880 if (nChangePosInOut != -1 && nSubtractFeeFromAmount == 0) {
881 Amount additionalFeeNeeded = nFeeNeeded - nFeeRet;
882 std::vector<CTxOut>::iterator change_position =
883 txNew.
vout.begin() + nChangePosInOut;
886 if (change_position->nValue >=
888 change_position->nValue -= additionalFeeNeeded;
889 nFeeRet += additionalFeeNeeded;
897 if (nSubtractFeeFromAmount > 0) {
898 pick_new_inputs =
false;
902 nFeeRet = nFeeNeeded;
908 if (scriptChange.
empty() && nChangePosInOut != -1) {
914 std::vector<CInputCoin> selected_coins(setCoins.begin(),
916 Shuffle(selected_coins.begin(), selected_coins.end(),
921 for (
const auto &coin : selected_coins) {
924 std::numeric_limits<uint32_t>::max() - 1));
927 if (sign && !
wallet.SignTransaction(txNew)) {
928 error =
_(
"Signing transaction failed");
937 error =
_(
"Transaction too large");
942 if (nFeeRet >
wallet.m_default_max_tx_fee) {
958 int nChangePosIn = nChangePosInOut;
962 error, coin_control, sign);
972 int nChangePosInOut2 = nChangePosIn;
976 nChangePosInOut2, error2, tmp_cc, sign)) {
979 const bool use_aps = nFeeRet2 <= nFeeRet +
wallet.m_max_aps_fee;
981 "Fee non-grouped = %lld, grouped = %lld, using %s\n", nFeeRet,
982 nFeeRet2, use_aps ?
"grouped" :
"non-grouped");
986 nChangePosInOut = nChangePosInOut2;
996 const std::set<int> &setSubtractFeeFromOutputs,
998 std::vector<CRecipient> vecSend;
1001 for (
size_t idx = 0; idx < tx.
vout.size(); idx++) {
1004 setSubtractFeeFromOutputs.count(idx) == 1};
1005 vecSend.push_back(recipient);
1020 error, coinControl,
false)) {
1024 if (nChangePosInOut != -1) {
1025 tx.
vout.insert(tx.
vout.begin() + nChangePosInOut,
1026 tx_new->vout[nChangePosInOut]);
1031 for (
size_t idx = 0; idx < tx.
vout.size(); idx++) {
1032 tx.
vout[idx].nValue = tx_new->vout[idx].nValue;
1036 for (
const CTxIn &txin : tx_new->vin) {
1038 tx.
vin.push_back(txin);
static constexpr Amount SATOSHI
static constexpr Amount MAX_MONEY
No amount larger than this (in satoshi) is valid.
#define CHECK_NONFATAL(condition)
Identity function.
std::optional< OutputType > m_change_type
Override the default change type if set, ignored if destChange is set.
std::optional< unsigned int > m_confirm_target
Override the default confirmation target if set.
bool IsSelected(const COutPoint &output) const
int m_max_depth
Maximum chain depth value for coin availability.
void Select(const COutPoint &output)
bool fAllowWatchOnly
Includes watch only addresses which are solvable.
int m_min_depth
Minimum chain depth value for coin availability.
std::optional< CFeeRate > m_feerate
Override the wallet's m_pay_tx_fee if set.
bool m_add_inputs
If false, only selected inputs are used.
CTxDestination destChange
bool m_avoid_address_reuse
Forbids inclusion of dirty (previously used) addresses.
bool m_avoid_partial_spends
Avoid partial use of funds sent to a given address.
bool fAllowOtherInputs
If false, allows unselected inputs, but requires all selected inputs be used.
void ListSelected(std::vector< COutPoint > &vOutpoints) const
Fee rate in satoshis per kilobyte: Amount / kB.
std::string ToString() const
Amount GetFee(size_t nBytes) const
Return the fee in satoshis for the given size in bytes.
A mutable version of CTransaction.
std::vector< CTxOut > vout
An outpoint - a combination of a transaction hash and an index n into its vout.
const TxId & GetTxId() const
std::string ToString() const
Serialized script, used inside transaction inputs and outputs.
The basic transaction that is broadcasted on the network and contained in blocks.
const std::vector< CTxOut > vout
const std::vector< CTxIn > vin
An input of a transaction.
An output of a transaction.
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
A transaction with a bunch of additional info that only the owner cares about.
mapValue_t mapValue
Key/value map with information about the transaction.
A wrapper to reserve an address from a wallet.
std::string ToString() const
Helper for findBlock to selectively return pieces of block data.
const int DEFAULT_MAX_DEPTH
const int DEFAULT_MIN_DEPTH
bool KnapsackSolver(const Amount nTargetValue, std::vector< OutputGroup > &groups, std::set< CInputCoin > &setCoinsRet, Amount &nValueRet)
bool SelectCoinsBnB(std::vector< OutputGroup > &utxo_pool, const Amount &target_value, const Amount &cost_of_change, std::set< CInputCoin > &out_set, Amount &value_ret, const Amount not_input_fees)
This is the Branch and Bound Coin Selection algorithm designed by Murch.
static const Amount MIN_FINAL_CHANGE
final minimum change amount after paying for fees
static std::vector< COutput > vCoins
CoinSelectionParams coin_selection_params(false, 0, 0, CFeeRate(Amount::zero()), 0)
bilingual_str TransactionErrorString(const TransactionError error)
void KeepDestination()
Keep the address.
bool GetReservedDestination(CTxDestination &pubkey, bool internal)
Reserve an address.
isminetype
IsMine() return codes.
std::string FormatMoney(const Amount amt)
Do not use these functions to represent or parse monetary amounts to or from JSON but use AmountFromV...
void insert(Tdst &dst, const Tsrc &src)
Simplification of std insertion.
Amount GetDustThreshold(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
static const unsigned int MAX_STANDARD_TX_SIZE
The maximum size for transactions we're willing to relay/mine.
static CTransactionRef MakeTransactionRef()
std::shared_ptr< const CTransaction > CTransactionRef
int GetRandInt(int nMax) noexcept
void Shuffle(I first, I last, R &&rng)
More efficient than using std::shuffle on a FastRandomContext.
bool CachedTxIsFromMe(const CWallet &wallet, const CWalletTx &wtx, const isminefilter &filter)
bool OutputIsChange(const CWallet &wallet, const CTxOut &txout)
bool CachedTxIsTrusted(const CWallet &wallet, const CWalletTx &wtx, std::set< TxId > &trusted_parents)
size_t GetSerializeSize(const T &t, int nVersion=0)
bool IsSolvable(const SigningProvider &provider, const CScript &script)
Check whether we know how to sign for an output like this, assuming we have all private keys.
int CalculateMaximumSignedInputSize(const CTxOut &txout, const CWallet *wallet, bool use_max_sig)
Get the marginal bytes of spending the specified output.
bool SelectCoinsMinConf(const CWallet &wallet, const Amount nTargetValue, const CoinEligibilityFilter &eligibility_filter, std::vector< OutputGroup > groups, std::set< CInputCoin > &setCoinsRet, Amount &nValueRet, const CoinSelectionParams &coin_selection_params, bool &bnb_used)
Shuffle and select coins until nTargetValue is reached while avoiding small change; This method is st...
bool FundTransaction(CWallet &wallet, CMutableTransaction &tx, Amount &nFeeRet, int &nChangePosInOut, bilingual_str &error, bool lockUnspents, const std::set< int > &setSubtractFeeFromOutputs, CCoinControl coinControl)
Insert additional inputs into the transaction by calling CreateTransaction();.
int64_t CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector< CTxOut > &txouts, bool use_max_sig)
Calculate the size of the transaction assuming all signatures are max size Use DummySignatureCreator,...
void AvailableCoins(const CWallet &wallet, std::vector< COutput > &vCoins, bool fOnlySafe, const CCoinControl *coinControl, const Amount nMinimumAmount, const Amount nMaximumAmount, const Amount nMinimumSumAmount, const uint64_t nMaximumCount)
populate vCoins with vector of available COutputs.
std::vector< OutputGroup > GroupOutputs(const CWallet &wallet, const std::vector< COutput > &outputs, bool single_coin, const size_t max_ancestors)
std::map< CTxDestination, std::vector< COutput > > ListCoins(const CWallet &wallet)
Return list of available coins and locked coins grouped by non-change output address.
bool CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, CTransactionRef &tx, Amount &nFeeRet, int &nChangePosInOut, bilingual_str &error, const CCoinControl &coin_control, bool sign)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
static bool CreateTransactionInternal(CWallet &wallet, const std::vector< CRecipient > &vecSend, CTransactionRef &tx, Amount &nFeeRet, int &nChangePosInOut, bilingual_str &error, const CCoinControl &coin_control, bool sign)
static const size_t OUTPUT_GROUP_MAX_ENTRIES
const CTxOut & FindNonChangeParentOutput(const CWallet &wallet, const CTransaction &tx, int output)
Find non-change parent output.
int GetTxSpendSize(const CWallet &wallet, const CWalletTx &wtx, unsigned int out, bool use_max_sig)
Get the marginal bytes if spending the specified output from this transaction.
Amount GetAvailableBalance(const CWallet &wallet, const CCoinControl *coinControl)
bool SelectCoins(const CWallet &wallet, const std::vector< COutput > &vAvailableCoins, const Amount nTargetValue, std::set< CInputCoin > &setCoinsRet, Amount &nValueRet, const CCoinControl &coin_control, CoinSelectionParams &coin_selection_params, bool &bnb_used)
Select a set of coins such that nValueRet >= nTargetValue and at least all coins from coin_control ar...
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
boost::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
static constexpr Amount zero() noexcept
bool m_subtract_fee_outputs
Indicate that we are subtracting the fee from outputs.
size_t change_output_size
OutputGroup GetPositiveOnlyGroup()
void Insert(const CInputCoin &output, int depth, bool from_me, size_t ancestors, size_t descendants)
A TxId is the identifier of a transaction.
bool error(const char *fmt, const Args &...args)
bilingual_str _(const char *psz)
Translation function.
static const int PROTOCOL_VERSION
network protocol versioning
Amount GetMinimumFee(const CWallet &wallet, unsigned int nTxBytes, const CCoinControl &coin_control)
Estimate the minimum fee considering user set parameters and the required fee.
CFeeRate GetMinimumFeeRate(const CWallet &wallet, const CCoinControl &coin_control)
Estimate the minimum fee rate considering user set parameters and the required fee.
static constexpr size_t DUMMY_P2PKH_INPUT_SIZE
Pre-calculated constants for input size estimation.
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
@ WALLET_FLAG_AVOID_REUSE