diff --git a/src/Makefile.am b/src/Makefile.am --- a/src/Makefile.am +++ b/src/Makefile.am @@ -169,6 +169,7 @@ rpc/server.h \ rpc/tojson.h \ rpc/register.h \ + rpc/util.h \ scheduler.h \ script/scriptcache.h \ script/sigcache.h \ @@ -423,6 +424,7 @@ logging.cpp \ random.cpp \ rpc/protocol.cpp \ + rpc/util.cpp \ support/cleanse.cpp \ sync.cpp \ threadinterrupt.cpp \ diff --git a/src/rpc/misc.cpp b/src/rpc/misc.cpp --- a/src/rpc/misc.cpp +++ b/src/rpc/misc.cpp @@ -284,88 +284,7 @@ // Needed even with !ENABLE_WALLET, to pass (ignored) pointers around class CWallet; -/** - * Used by addmultisigaddress / createmultisig: - */ -CScript createmultisig_redeemScript(CWallet *const pwallet, - const UniValue ¶ms) { - int nRequired = params[0].get_int(); - const UniValue &keys = params[1].get_array(); - - // Gather public keys - if (nRequired < 1) { - throw std::runtime_error( - "a multisignature address must require at least one key to redeem"); - } - if ((int)keys.size() < nRequired) { - throw std::runtime_error( - strprintf("not enough keys supplied " - "(got %u keys, but need at least %d to redeem)", - keys.size(), nRequired)); - } - if (keys.size() > 16) { - throw std::runtime_error( - "Number of addresses involved in the " - "multisignature address creation > 16\nReduce the " - "number"); - } - std::vector pubkeys; - pubkeys.resize(keys.size()); - for (size_t i = 0; i < keys.size(); i++) { - const std::string &ks = keys[i].get_str(); -#ifdef ENABLE_WALLET - // Case 1: Bitcoin address and we have full public key: - if (pwallet) { - CTxDestination dest = DecodeDestination(ks, pwallet->chainParams); - if (IsValidDestination(dest)) { - const CKeyID *keyID = boost::get(&dest); - if (!keyID) { - throw std::runtime_error( - strprintf("%s does not refer to a key", ks)); - } - CPubKey vchPubKey; - if (!pwallet->GetPubKey(*keyID, vchPubKey)) { - throw std::runtime_error( - strprintf("no full public key for address %s", ks)); - } - if (!vchPubKey.IsFullyValid()) { - throw std::runtime_error(" Invalid public key: " + ks); - } - pubkeys[i] = vchPubKey; - continue; - } - } -#endif - // Case 2: hex public key - if (IsHex(ks)) { - CPubKey vchPubKey(ParseHex(ks)); - if (!vchPubKey.IsFullyValid()) { - throw std::runtime_error(" Invalid public key: " + ks); - } - pubkeys[i] = vchPubKey; - } else { - throw std::runtime_error(" Invalid public key: " + ks); - } - } - - CScript result = GetScriptForMultisig(nRequired, pubkeys); - if (result.size() > MAX_SCRIPT_ELEMENT_SIZE) { - throw std::runtime_error( - strprintf("redeemScript exceeds size limit: %d > %d", result.size(), - MAX_SCRIPT_ELEMENT_SIZE)); - } - - return result; -} - -static UniValue createmultisig(const Config &config, - const JSONRPCRequest &request) { -#ifdef ENABLE_WALLET - CWallet *const pwallet = GetWalletForJSONRPCRequest(request); -#else - CWallet *const pwallet = nullptr; -#endif - +UniValue createmultisig(const Config &config, const JSONRPCRequest &request) { if (request.fHelp || request.params.size() < 2 || request.params.size() > 2) { std::string msg = @@ -373,7 +292,12 @@ "\nCreates a multi-signature address with n signature of m keys " "required.\n" "It returns a json object with the address and redeemScript.\n" - + "DEPRECATION WARNING: Using addresses with createmultisig is " + "deprecated. Clients must\n" + "transition to using addmultisigaddress to create multisig " + "addresses with addresses known\n" + "to the wallet before upgrading to v0.17. To use the deprecated " + "functionality, start bitcoind with -deprecatedrpc=createmultisig\n" "\nArguments:\n" "1. nrequired (numeric, required) The number of required " "signatures out of the n keys or addresses.\n" @@ -407,8 +331,40 @@ throw std::runtime_error(msg); } + int required = request.params[0].get_int(); + + // Get the public keys + const UniValue &keys = request.params[1].get_array(); + std::vector pubkeys; + for (unsigned int i = 0; i < keys.size(); ++i) { + if (IsHex(keys[i].get_str()) && (keys[i].get_str().length() == 66 || + keys[i].get_str().length() == 130)) { + pubkeys.push_back(HexToPubKey(keys[i].get_str())); + } else { +#ifdef ENABLE_WALLET + CWallet *const pwallet = GetWalletForJSONRPCRequest(request); + if (IsDeprecatedRPCEnabled(gArgs, "createmultisig") && + EnsureWalletIsAvailable(pwallet, false)) { + pubkeys.push_back(AddrToPubKey(config.GetChainParams(), pwallet, + keys[i].get_str())); + } else +#endif + throw JSONRPCError( + RPC_INVALID_ADDRESS_OR_KEY, + strprintf("Invalid public key: %s\nNote that from v0.16, " + "createmultisig no longer accepts addresses." + " Clients must transition to using " + "addmultisigaddress to create multisig addresses " + "with addresses known to the wallet before " + "upgrading to v0.17." + " To use the deprecated functionality, start " + "bitcoind with -deprecatedrpc=createmultisig", + keys[i].get_str())); + } + } + // Construct using pay-to-script-hash: - CScript inner = createmultisig_redeemScript(pwallet, request.params); + CScript inner = CreateMultisigRedeemscript(required, pubkeys); CScriptID innerID(inner); UniValue result(UniValue::VOBJ); diff --git a/src/rpc/util.h b/src/rpc/util.h new file mode 100644 --- /dev/null +++ b/src/rpc/util.h @@ -0,0 +1,22 @@ +// Copyright (c) 2017 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef BITCOIN_RPC_UTIL_H +#define BITCOIN_RPC_UTIL_H + +#include +#include + +class CChainParams; +class CKeyStore; +class CPubKey; +class CScript; + +CPubKey HexToPubKey(const std::string &hex_in); +CPubKey AddrToPubKey(const CChainParams &chainparams, CKeyStore *const keystore, + const std::string &addr_in); +CScript CreateMultisigRedeemscript(const int required, + const std::vector &pubkeys); + +#endif // BITCOIN_RPC_UTIL_H diff --git a/src/rpc/util.cpp b/src/rpc/util.cpp new file mode 100644 --- /dev/null +++ b/src/rpc/util.cpp @@ -0,0 +1,87 @@ +// Copyright (c) 2017 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Converts a hex string to a public key if possible +CPubKey HexToPubKey(const std::string &hex_in) { + if (!IsHex(hex_in)) { + throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, + "Invalid public key: " + hex_in); + } + CPubKey vchPubKey(ParseHex(hex_in)); + if (!vchPubKey.IsFullyValid()) { + throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, + "Invalid public key: " + hex_in); + } + return vchPubKey; +} + +// Retrieves a public key for an address from the given CKeyStore +CPubKey AddrToPubKey(const CChainParams &chainparams, CKeyStore *const keystore, + const std::string &addr_in) { + CTxDestination dest = DecodeDestination(addr_in, chainparams); + if (!IsValidDestination(dest)) { + throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, + "Invalid address: " + addr_in); + } + CKeyID key = boost::get(dest); + if (key.IsNull()) { + throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, + strprintf("%s does not refer to a key", addr_in)); + } + CPubKey vchPubKey; + if (!keystore->GetPubKey(key, vchPubKey)) { + throw JSONRPCError( + RPC_INVALID_ADDRESS_OR_KEY, + strprintf("no full public key for address %s", addr_in)); + } + if (!vchPubKey.IsFullyValid()) { + throw JSONRPCError(RPC_INTERNAL_ERROR, + "Wallet contains an invalid public key"); + } + return vchPubKey; +} + +// Creates a multisig redeemscript from a given list of public keys and number +// required. +CScript CreateMultisigRedeemscript(const int required, + const std::vector &pubkeys) { + // Gather public keys + if (required < 1) { + throw JSONRPCError( + RPC_INVALID_PARAMETER, + "a multisignature address must require at least one key to redeem"); + } + if ((int)pubkeys.size() < required) { + throw JSONRPCError(RPC_INVALID_PARAMETER, + strprintf("not enough keys supplied (got %u keys, " + "but need at least %d to redeem)", + pubkeys.size(), required)); + } + if (pubkeys.size() > 16) { + throw JSONRPCError(RPC_INVALID_PARAMETER, + "Number of keys involved in the multisignature " + "address creation > 16\nReduce the number"); + } + + CScript result = GetScriptForMultisig(required, pubkeys); + + if (result.size() > MAX_SCRIPT_ELEMENT_SIZE) { + throw JSONRPCError( + RPC_INVALID_PARAMETER, + (strprintf("redeemScript exceeds size limit: %d > %d", + result.size(), MAX_SCRIPT_ELEMENT_SIZE))); + } + + return result; +} diff --git a/src/util.cpp b/src/util.cpp --- a/src/util.cpp +++ b/src/util.cpp @@ -10,6 +10,7 @@ #include "util.h" #include "chainparamsbase.h" +#include "dstencode.h" #include "fs.h" #include "random.h" #include "serialize.h" diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -17,6 +17,7 @@ #include "rpc/misc.h" #include "rpc/safemode.h" #include "rpc/server.h" +#include "rpc/util.h" #include "timedata.h" #include "util.h" #include "utilmoneystr.h" @@ -1316,8 +1317,8 @@ return wtx.GetId().GetHex(); } -static UniValue addmultisigaddress(const Config &config, - const JSONRPCRequest &request) { +UniValue addmultisigaddress(const Config &config, + const JSONRPCRequest &request) { CWallet *const pwallet = GetWalletForJSONRPCRequest(request); if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) { return NullUniValue; @@ -1347,8 +1348,18 @@ "assign the addresses to.\n" "\nResult:\n" - "\"address\" (string) A bitcoin address associated with " - "the keys.\n" + "{\n" + " \"address\":\"multisigaddress\", (string) The value of the " + "new multisig address.\n" + " \"redeemScript\":\"script\" (string) The string value " + "of the hex-encoded redemption script.\n" + "}\n" + "\nResult (DEPRECATED. To see this result in v0.16 instead, please " + "start bitcoind with -deprecatedrpc=addmultisigaddress).\n" + " clients should transition to the new output api before " + "upgrading to v0.17.\n" + "\"address\" (string) A bitcoin address " + "associated with the keys.\n" "\nExamples:\n" "\nAdd a multisig address from 2 addresses\n" + @@ -1371,13 +1382,38 @@ strAccount = AccountFromValue(request.params[2]); } + int required = request.params[0].get_int(); + + // Get the public keys + const UniValue &keys_or_addrs = request.params[1].get_array(); + std::vector pubkeys; + for (unsigned int i = 0; i < keys_or_addrs.size(); ++i) { + if (IsHex(keys_or_addrs[i].get_str()) && + (keys_or_addrs[i].get_str().length() == 66 || + keys_or_addrs[i].get_str().length() == 130)) { + pubkeys.push_back(HexToPubKey(keys_or_addrs[i].get_str())); + } else { + pubkeys.push_back(AddrToPubKey(config.GetChainParams(), pwallet, + keys_or_addrs[i].get_str())); + } + } + // Construct using pay-to-script-hash: - CScript inner = createmultisig_redeemScript(pwallet, request.params); + CScript inner = CreateMultisigRedeemscript(required, pubkeys); CScriptID innerID(inner); pwallet->AddCScript(inner); pwallet->SetAddressBook(innerID, strAccount, "send"); - return EncodeDestination(innerID); + + // Return old style interface + if (IsDeprecatedRPCEnabled(gArgs, "addmultisigaddress")) { + return EncodeDestination(innerID); + } + + UniValue result(UniValue::VOBJ); + result.pushKV("address", EncodeDestination(innerID)); + result.pushKV("redeemScript", HexStr(inner.begin(), inner.end())); + return result; } struct tallyitem { diff --git a/test/functional/deprecated_rpc.py b/test/functional/deprecated_rpc.py --- a/test/functional/deprecated_rpc.py +++ b/test/functional/deprecated_rpc.py @@ -11,7 +11,8 @@ def set_test_params(self): self.num_nodes = 2 self.setup_clean_chain = True - self.extra_args = [[], ["-deprecatedrpc=estimatefee"]] + self.extra_args = [ + [], ["-deprecatedrpc=estimatefee", "-deprecatedrpc=createmultisig"]] def run_test(self): self.log.info("estimatefee: Shows deprecated message") @@ -21,6 +22,12 @@ self.log.info("Using -deprecatedrpc=estimatefee bypasses the error") self.nodes[1].estimatefee(1) + self.log.info( + "Make sure that -deprecatedrpc=createmultisig allows it to take addresses") + assert_raises_rpc_error(-5, "Invalid public key", + self.nodes[0].createmultisig, 1, [self.nodes[0].getnewaddress()]) + self.nodes[1].createmultisig(1, [self.nodes[1].getnewaddress()]) + if __name__ == '__main__': DeprecatedRpcTest().main() diff --git a/test/functional/fundrawtransaction.py b/test/functional/fundrawtransaction.py --- a/test/functional/fundrawtransaction.py +++ b/test/functional/fundrawtransaction.py @@ -371,7 +371,7 @@ addr2Obj = self.nodes[1].validateaddress(addr2) mSigObj = self.nodes[1].addmultisigaddress( - 2, [addr1Obj['pubkey'], addr2Obj['pubkey']]) + 2, [addr1Obj['pubkey'], addr2Obj['pubkey']])['address'] inputs = [] outputs = {mSigObj: 1.1} @@ -431,7 +431,7 @@ addr2Obj = self.nodes[2].validateaddress(addr2) mSigObj = self.nodes[2].addmultisigaddress( - 2, [addr1Obj['pubkey'], addr2Obj['pubkey']]) + 2, [addr1Obj['pubkey'], addr2Obj['pubkey']])['address'] # send 1.2 BTC to msig addr txId = self.nodes[0].sendtoaddress(mSigObj, 1.2) diff --git a/test/functional/importmulti.py b/test/functional/importmulti.py --- a/test/functional/importmulti.py +++ b/test/functional/importmulti.py @@ -251,7 +251,7 @@ sig_address_3 = self.nodes[0].validateaddress( self.nodes[0].getnewaddress()) multi_sig_script = self.nodes[0].createmultisig( - 2, [sig_address_1['address'], sig_address_2['address'], sig_address_3['pubkey']]) + 2, [sig_address_1['pubkey'], sig_address_2['pubkey'], sig_address_3['pubkey']]) self.nodes[1].generate(100) transactionid = self.nodes[1].sendtoaddress( multi_sig_script['address'], 10.00) @@ -286,7 +286,7 @@ sig_address_3 = self.nodes[0].validateaddress( self.nodes[0].getnewaddress()) multi_sig_script = self.nodes[0].createmultisig( - 2, [sig_address_1['address'], sig_address_2['address'], sig_address_3['pubkey']]) + 2, [sig_address_1['pubkey'], sig_address_2['pubkey'], sig_address_3['pubkey']]) self.nodes[1].generate(100) transactionid = self.nodes[1].sendtoaddress( multi_sig_script['address'], 10.00) @@ -321,7 +321,7 @@ sig_address_3 = self.nodes[0].validateaddress( self.nodes[0].getnewaddress()) multi_sig_script = self.nodes[0].createmultisig( - 2, [sig_address_1['address'], sig_address_2['address'], sig_address_3['pubkey']]) + 2, [sig_address_1['pubkey'], sig_address_2['pubkey'], sig_address_3['pubkey']]) self.nodes[1].generate(100) transactionid = self.nodes[1].sendtoaddress( multi_sig_script['address'], 10.00) @@ -358,7 +358,7 @@ sig_address_3 = self.nodes[0].validateaddress( self.nodes[0].getnewaddress()) multi_sig_script = self.nodes[0].createmultisig( - 2, [sig_address_1['address'], sig_address_2['address'], sig_address_3['pubkey']]) + 2, [sig_address_1['pubkey'], sig_address_2['pubkey'], sig_address_3['pubkey']]) self.nodes[1].generate(100) transactionid = self.nodes[1].sendtoaddress( multi_sig_script['address'], 10.00) diff --git a/test/functional/listtransactions.py b/test/functional/listtransactions.py --- a/test/functional/listtransactions.py +++ b/test/functional/listtransactions.py @@ -83,8 +83,9 @@ {"category": "receive", "amount": Decimal("0.44")}, {"txid": txid, "account": "toself"}) - multisig = self.nodes[1].createmultisig( - 1, [self.nodes[1].getnewaddress()]) + pubkey = self.nodes[1].validateaddress( + self.nodes[1].getnewaddress())['pubkey'] + multisig = self.nodes[1].createmultisig(1, [pubkey]) self.nodes[0].importaddress( multisig["redeemScript"], "watchonly", False, True) txid = self.nodes[1].sendtoaddress(multisig["address"], 0.1) diff --git a/test/functional/nulldummy.py b/test/functional/nulldummy.py --- a/test/functional/nulldummy.py +++ b/test/functional/nulldummy.py @@ -48,7 +48,8 @@ def run_test(self): self.address = self.nodes[0].getnewaddress() - self.ms_address = self.nodes[0].addmultisigaddress(1, [self.address]) + self.ms_address = self.nodes[0].addmultisigaddress(1, [self.address])[ + 'address'] NetworkThread().start() # Start up network handling in another thread self.coinbase_blocks = self.nodes[0].generate(2) # Block 2 diff --git a/test/functional/rawtransactions.py b/test/functional/rawtransactions.py --- a/test/functional/rawtransactions.py +++ b/test/functional/rawtransactions.py @@ -66,9 +66,18 @@ addr1Obj = self.nodes[2].validateaddress(addr1) addr2Obj = self.nodes[2].validateaddress(addr2) - mSigObj = self.nodes[2].addmultisigaddress( + # Tests for createmultisig and addmultisigaddress + assert_raises_rpc_error(-5, "Invalid public key", + self.nodes[0].createmultisig, 1, ["01020304"]) + # createmultisig can only take public keys + self.nodes[0].createmultisig( 2, [addr1Obj['pubkey'], addr2Obj['pubkey']]) - mSigObjValid = self.nodes[2].validateaddress(mSigObj) + # addmultisigaddress can take both pubkeys and addresses so long as they are in the wallet, which is tested here. + assert_raises_rpc_error(-5, "Invalid public key", + self.nodes[0].createmultisig, 2, [addr1Obj['pubkey'], addr1]) + + mSigObj = self.nodes[2].addmultisigaddress( + 2, [addr1Obj['pubkey'], addr1])['address'] # use balance deltas instead of absolute values bal = self.nodes[2].getbalance() @@ -93,8 +102,7 @@ addr3Obj = self.nodes[2].validateaddress(addr3) mSigObj = self.nodes[2].addmultisigaddress( - 2, [addr1Obj['pubkey'], addr2Obj['pubkey'], addr3Obj['pubkey']]) - mSigObjValid = self.nodes[2].validateaddress(mSigObj) + 2, [addr1Obj['pubkey'], addr2Obj['pubkey'], addr3Obj['pubkey']])['address'] txId = self.nodes[0].sendtoaddress(mSigObj, 2.2) decTx = self.nodes[0].gettransaction(txId) @@ -152,9 +160,9 @@ addr2Obj = self.nodes[2].validateaddress(addr2) self.nodes[1].addmultisigaddress( - 2, [addr1Obj['pubkey'], addr2Obj['pubkey']]) + 2, [addr1Obj['pubkey'], addr2Obj['pubkey']])['address'] mSigObj = self.nodes[2].addmultisigaddress( - 2, [addr1Obj['pubkey'], addr2Obj['pubkey']]) + 2, [addr1Obj['pubkey'], addr2Obj['pubkey']])['address'] mSigObjValid = self.nodes[2].validateaddress(mSigObj) txId = self.nodes[0].sendtoaddress(mSigObj, 2.2) diff --git a/test/functional/wallet-accounts.py b/test/functional/wallet-accounts.py --- a/test/functional/wallet-accounts.py +++ b/test/functional/wallet-accounts.py @@ -131,7 +131,7 @@ for x in range(10): addresses.append(node.getnewaddress()) multisig_address = node.addmultisigaddress( - 5, addresses, account.name) + 5, addresses, account.name)['address'] account.add_address(multisig_address) account.verify(node) node.sendfrom("", multisig_address, 50)