Skip to content

Commit 08fc6f6

Browse files
committed
[rpc] refactor: consolidate sendmany and sendtoaddress code
The only new behavior is some error codes are changed from -4 to -6.
1 parent 0101110 commit 08fc6f6

File tree

4 files changed

+68
-81
lines changed

4 files changed

+68
-81
lines changed

doc/release-notes-18202.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
Low-level RPC Changes
2+
---------------------
3+
4+
- To make RPC `sendtoaddress` more consistent with `sendmany` the following error
5+
`sendtoaddress` codes were changed from `-4` to `-6`:
6+
- Insufficient funds
7+
- Fee estimation failed
8+
- Transaction has too long of a mempool chain

src/wallet/rpcwallet.cpp

Lines changed: 54 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -321,36 +321,54 @@ static UniValue setlabel(const JSONRPCRequest& request)
321321
return NullUniValue;
322322
}
323323

324+
void ParseRecipients(const UniValue& address_amounts, const UniValue& subtract_fee_outputs, std::vector<CRecipient> &recipients) {
325+
std::set<CTxDestination> destinations;
326+
int i = 0;
327+
for (const std::string& address: address_amounts.getKeys()) {
328+
CTxDestination dest = DecodeDestination(address);
329+
if (!IsValidDestination(dest)) {
330+
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Bitcoin address: ") + address);
331+
}
324332

325-
static CTransactionRef SendMoney(CWallet* const pwallet, const CTxDestination& address, CAmount nValue, bool fSubtractFeeFromAmount, const CCoinControl& coin_control, mapValue_t mapValue)
326-
{
327-
CAmount curBalance = pwallet->GetBalance(0, coin_control.m_avoid_address_reuse).m_mine_trusted;
333+
if (destinations.count(dest)) {
334+
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + address);
335+
}
336+
destinations.insert(dest);
328337

329-
// Check amount
330-
if (nValue <= 0)
331-
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount");
338+
CScript script_pub_key = GetScriptForDestination(dest);
339+
CAmount amount = AmountFromValue(address_amounts[i++]);
332340

333-
if (nValue > curBalance)
334-
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
341+
bool subtract_fee = false;
342+
for (unsigned int idx = 0; idx < subtract_fee_outputs.size(); idx++) {
343+
const UniValue& addr = subtract_fee_outputs[idx];
344+
if (addr.get_str() == address) {
345+
subtract_fee = true;
346+
}
347+
}
335348

336-
// Parse Bitcoin address
337-
CScript scriptPubKey = GetScriptForDestination(address);
349+
CRecipient recipient = {script_pub_key, amount, subtract_fee};
350+
recipients.push_back(recipient);
351+
}
352+
}
353+
354+
UniValue SendMoney(CWallet* const pwallet, const CCoinControl &coin_control, std::vector<CRecipient> &recipients, mapValue_t map_value)
355+
{
356+
EnsureWalletIsUnlocked(pwallet);
338357

339-
// Create and send the transaction
358+
// Shuffle recipient list
359+
std::shuffle(recipients.begin(), recipients.end(), FastRandomContext());
360+
361+
// Send
340362
CAmount nFeeRequired = 0;
341-
bilingual_str error;
342-
std::vector<CRecipient> vecSend;
343363
int nChangePosRet = -1;
344-
CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount};
345-
vecSend.push_back(recipient);
364+
bilingual_str error;
346365
CTransactionRef tx;
347-
if (!pwallet->CreateTransaction(vecSend, tx, nFeeRequired, nChangePosRet, error, coin_control)) {
348-
if (!fSubtractFeeFromAmount && nValue + nFeeRequired > curBalance)
349-
error = strprintf(Untranslated("Error: This transaction requires a transaction fee of at least %s"), FormatMoney(nFeeRequired));
350-
throw JSONRPCError(RPC_WALLET_ERROR, error.original);
366+
bool fCreated = pwallet->CreateTransaction(recipients, tx, nFeeRequired, nChangePosRet, error, coin_control, !pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
367+
if (!fCreated) {
368+
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, error.original);
351369
}
352-
pwallet->CommitTransaction(tx, std::move(mapValue), {} /* orderForm */);
353-
return tx;
370+
pwallet->CommitTransaction(tx, std::move(map_value), {} /* orderForm */);
371+
return tx->GetHash().GetHex();
354372
}
355373

356374
static UniValue sendtoaddress(const JSONRPCRequest& request)
@@ -398,16 +416,6 @@ static UniValue sendtoaddress(const JSONRPCRequest& request)
398416

399417
LOCK(pwallet->cs_wallet);
400418

401-
CTxDestination dest = DecodeDestination(request.params[0].get_str());
402-
if (!IsValidDestination(dest)) {
403-
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
404-
}
405-
406-
// Amount
407-
CAmount nAmount = AmountFromValue(request.params[1]);
408-
if (nAmount <= 0)
409-
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
410-
411419
// Wallet comments
412420
mapValue_t mapValue;
413421
if (!request.params[2].isNull() && !request.params[2].get_str().empty())
@@ -441,8 +449,18 @@ static UniValue sendtoaddress(const JSONRPCRequest& request)
441449

442450
EnsureWalletIsUnlocked(pwallet);
443451

444-
CTransactionRef tx = SendMoney(pwallet, dest, nAmount, fSubtractFeeFromAmount, coin_control, std::move(mapValue));
445-
return tx->GetHash().GetHex();
452+
UniValue address_amounts(UniValue::VOBJ);
453+
const std::string address = request.params[0].get_str();
454+
address_amounts.pushKV(address, request.params[1]);
455+
UniValue subtractFeeFromAmount(UniValue::VARR);
456+
if (fSubtractFeeFromAmount) {
457+
subtractFeeFromAmount.push_back(address);
458+
}
459+
460+
std::vector<CRecipient> recipients;
461+
ParseRecipients(address_amounts, subtractFeeFromAmount, recipients);
462+
463+
return SendMoney(pwallet, coin_control, recipients, mapValue);
446464
}
447465

448466
static UniValue listaddressgroupings(const JSONRPCRequest& request)
@@ -840,52 +858,10 @@ static UniValue sendmany(const JSONRPCRequest& request)
840858
}
841859
}
842860

843-
std::set<CTxDestination> destinations;
844-
std::vector<CRecipient> vecSend;
861+
std::vector<CRecipient> recipients;
862+
ParseRecipients(sendTo, subtractFeeFromAmount, recipients);
845863

846-
std::vector<std::string> keys = sendTo.getKeys();
847-
for (const std::string& name_ : keys) {
848-
CTxDestination dest = DecodeDestination(name_);
849-
if (!IsValidDestination(dest)) {
850-
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Bitcoin address: ") + name_);
851-
}
852-
853-
if (destinations.count(dest)) {
854-
throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + name_);
855-
}
856-
destinations.insert(dest);
857-
858-
CScript scriptPubKey = GetScriptForDestination(dest);
859-
CAmount nAmount = AmountFromValue(sendTo[name_]);
860-
if (nAmount <= 0)
861-
throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
862-
863-
bool fSubtractFeeFromAmount = false;
864-
for (unsigned int idx = 0; idx < subtractFeeFromAmount.size(); idx++) {
865-
const UniValue& addr = subtractFeeFromAmount[idx];
866-
if (addr.get_str() == name_)
867-
fSubtractFeeFromAmount = true;
868-
}
869-
870-
CRecipient recipient = {scriptPubKey, nAmount, fSubtractFeeFromAmount};
871-
vecSend.push_back(recipient);
872-
}
873-
874-
EnsureWalletIsUnlocked(pwallet);
875-
876-
// Shuffle recipient list
877-
std::shuffle(vecSend.begin(), vecSend.end(), FastRandomContext());
878-
879-
// Send
880-
CAmount nFeeRequired = 0;
881-
int nChangePosRet = -1;
882-
bilingual_str error;
883-
CTransactionRef tx;
884-
bool fCreated = pwallet->CreateTransaction(vecSend, tx, nFeeRequired, nChangePosRet, error, coin_control);
885-
if (!fCreated)
886-
throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, error.original);
887-
pwallet->CommitTransaction(tx, std::move(mapValue), {} /* orderForm */);
888-
return tx->GetHash().GetHex();
864+
return SendMoney(pwallet, coin_control, recipients, std::move(mapValue));
889865
}
890866

891867
static UniValue addmultisigaddress(const JSONRPCRequest& request)

test/functional/wallet_basic.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ def run_test(self):
119119
assert_raises_rpc_error(-8, "Invalid parameter, expected locked output", self.nodes[2].lockunspent, True, [unspent_0])
120120
self.nodes[2].lockunspent(False, [unspent_0])
121121
assert_raises_rpc_error(-8, "Invalid parameter, output already locked", self.nodes[2].lockunspent, False, [unspent_0])
122-
assert_raises_rpc_error(-4, "Insufficient funds", self.nodes[2].sendtoaddress, self.nodes[2].getnewaddress(), 20)
122+
assert_raises_rpc_error(-6, "Insufficient funds", self.nodes[2].sendtoaddress, self.nodes[2].getnewaddress(), 20)
123123
assert_equal([unspent_0], self.nodes[2].listlockunspent())
124124
self.nodes[2].lockunspent(True, [unspent_0])
125125
assert_equal(len(self.nodes[2].listlockunspent()), 0)
@@ -309,6 +309,9 @@ def run_test(self):
309309
assert_equal(tx_obj['amount'], Decimal('-0.0001'))
310310

311311
# General checks for errors from incorrect inputs
312+
# This will raise an exception because the amount is negative
313+
assert_raises_rpc_error(-3, "Amount out of range", self.nodes[0].sendtoaddress, self.nodes[2].getnewaddress(), "-1")
314+
312315
# This will raise an exception because the amount type is wrong
313316
assert_raises_rpc_error(-3, "Invalid amount", self.nodes[0].sendtoaddress, self.nodes[2].getnewaddress(), "1f-4")
314317

@@ -468,7 +471,7 @@ def run_test(self):
468471

469472
node0_balance = self.nodes[0].getbalance()
470473
# With walletrejectlongchains we will not create the tx and store it in our wallet.
471-
assert_raises_rpc_error(-4, "Transaction has too long of a mempool chain", self.nodes[0].sendtoaddress, sending_addr, node0_balance - Decimal('0.01'))
474+
assert_raises_rpc_error(-6, "Transaction has too long of a mempool chain", self.nodes[0].sendtoaddress, sending_addr, node0_balance - Decimal('0.01'))
472475

473476
# Verify nothing new in wallet
474477
assert_equal(total_txs, len(self.nodes[0].listtransactions("*", 99999)))

test/functional/wallet_fallbackfee.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def run_test(self):
2222

2323
# test sending a tx with disabled fallback fee (must fail)
2424
self.restart_node(0, extra_args=["-fallbackfee=0"])
25-
assert_raises_rpc_error(-4, "Fee estimation failed", lambda: self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1))
25+
assert_raises_rpc_error(-6, "Fee estimation failed", lambda: self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1))
2626
assert_raises_rpc_error(-4, "Fee estimation failed", lambda: self.nodes[0].fundrawtransaction(self.nodes[0].createrawtransaction([], {self.nodes[0].getnewaddress(): 1})))
2727
assert_raises_rpc_error(-6, "Fee estimation failed", lambda: self.nodes[0].sendmany("", {self.nodes[0].getnewaddress(): 1}))
2828

0 commit comments

Comments
 (0)