Branch data Line data Source code
1 : : // Copyright (c) 2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-2022 The Bitcoin Core developers
3 : : // Distributed under the MIT software license, see the accompanying
4 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 : :
6 : : #include <rpc/rawtransaction_util.h>
7 : :
8 : : #include <coins.h>
9 : : #include <consensus/amount.h>
10 : : #include <core_io.h>
11 : : #include <key_io.h>
12 : : #include <policy/policy.h>
13 : : #include <primitives/transaction.h>
14 : : #include <rpc/request.h>
15 : : #include <rpc/util.h>
16 : : #include <script/sign.h>
17 [ + - ]: 2 : #include <script/signingprovider.h>
18 [ + - ]: 2 : #include <tinyformat.h>
19 : : #include <univalue.h>
20 : : #include <util/rbf.h>
21 : : #include <util/strencodings.h>
22 : : #include <util/translation.h>
23 : :
24 : 0 : void AddInputs(CMutableTransaction& rawTx, const UniValue& inputs_in, std::optional<bool> rbf)
25 : : {
26 : 0 : UniValue inputs;
27 [ # # # # ]: 2 : if (inputs_in.isNull()) {
28 [ # # ]: 0 : inputs = UniValue::VARR;
29 : 0 : } else {
30 [ # # # # ]: 0 : inputs = inputs_in.get_array();
31 : : }
32 : :
33 [ # # # # ]: 0 : for (unsigned int idx = 0; idx < inputs.size(); idx++) {
34 [ # # ]: 0 : const UniValue& input = inputs[idx];
35 [ # # ]: 0 : const UniValue& o = input.get_obj();
36 : :
37 [ # # # # ]: 0 : uint256 txid = ParseHashO(o, "txid");
38 : :
39 [ # # ]: 0 : const UniValue& vout_v = o.find_value("vout");
40 [ # # # # ]: 0 : if (!vout_v.isNum())
41 [ # # # # : 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
# # ]
42 [ # # ]: 0 : int nOutput = vout_v.getInt<int>();
43 [ # # ]: 0 : if (nOutput < 0)
44 [ # # # # : 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout cannot be negative");
# # ]
45 : :
46 : : uint32_t nSequence;
47 : :
48 [ # # # # ]: 0 : if (rbf.value_or(true)) {
49 : 0 : nSequence = MAX_BIP125_RBF_SEQUENCE; /* CTxIn::SEQUENCE_FINAL - 2 */
50 [ # # ]: 0 : } else if (rawTx.nLockTime) {
51 : 0 : nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; /* CTxIn::SEQUENCE_FINAL - 1 */
52 : 0 : } else {
53 : 0 : nSequence = CTxIn::SEQUENCE_FINAL;
54 : : }
55 : :
56 : : // set the sequence number if passed in the parameters object
57 [ # # ]: 0 : const UniValue& sequenceObj = o.find_value("sequence");
58 [ # # # # ]: 0 : if (sequenceObj.isNum()) {
59 [ # # ]: 0 : int64_t seqNr64 = sequenceObj.getInt<int64_t>();
60 [ # # ]: 0 : if (seqNr64 < 0 || seqNr64 > CTxIn::SEQUENCE_FINAL) {
61 [ # # # # : 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range");
# # ]
62 : : } else {
63 : 0 : nSequence = (uint32_t)seqNr64;
64 : : }
65 : 0 : }
66 : :
67 [ # # # # : 0 : CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
# # ]
68 : :
69 [ # # ]: 0 : rawTx.vin.push_back(in);
70 : 0 : }
71 : 0 : }
72 : :
73 : 0 : void AddOutputs(CMutableTransaction& rawTx, const UniValue& outputs_in)
74 : 2 : {
75 [ # # ]: 0 : if (outputs_in.isNull()) {
76 [ # # # # : 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, output argument must be non-null");
# # ]
77 : : }
78 : :
79 : 0 : const bool outputs_is_obj = outputs_in.isObject();
80 [ # # ]: 0 : UniValue outputs = outputs_is_obj ? outputs_in.get_obj() : outputs_in.get_array();
81 : :
82 [ # # ]: 0 : if (!outputs_is_obj) {
83 : : // Translate array of key-value pairs into dict
84 [ # # ]: 0 : UniValue outputs_dict = UniValue(UniValue::VOBJ);
85 [ # # # # ]: 0 : for (size_t i = 0; i < outputs.size(); ++i) {
86 [ # # ]: 0 : const UniValue& output = outputs[i];
87 [ # # # # ]: 0 : if (!output.isObject()) {
88 [ # # # # : 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, key-value pair not an object as expected");
# # ]
89 : : }
90 [ # # # # ]: 0 : if (output.size() != 1) {
91 [ # # # # : 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, key-value pair must contain exactly one key");
# # ]
92 : : }
93 [ # # # # ]: 0 : outputs_dict.pushKVs(output);
94 : 0 : }
95 : 0 : outputs = std::move(outputs_dict);
96 : 0 : }
97 : :
98 : : // Duplicate checking
99 : 0 : std::set<CTxDestination> destinations;
100 : 0 : bool has_data{false};
101 : :
102 [ # # # # ]: 0 : for (const std::string& name_ : outputs.getKeys()) {
103 [ # # # # ]: 0 : if (name_ == "data") {
104 [ # # ]: 0 : if (has_data) {
105 [ # # # # : 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, duplicate key: data");
# # ]
106 : : }
107 : 0 : has_data = true;
108 [ # # # # : 0 : std::vector<unsigned char> data = ParseHexV(outputs[name_].getValStr(), "Data");
# # # # #
# ]
109 : :
110 [ # # # # : 0 : CTxOut out(0, CScript() << OP_RETURN << data);
# # # # #
# ]
111 [ # # ]: 0 : rawTx.vout.push_back(out);
112 : 0 : } else {
113 [ # # ]: 0 : CTxDestination destination = DecodeDestination(name_);
114 [ # # # # ]: 0 : if (!IsValidDestination(destination)) {
115 [ # # # # : 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Bitcoin address: ") + name_);
# # # # ]
116 : : }
117 : :
118 [ # # # # ]: 0 : if (!destinations.insert(destination).second) {
119 [ # # # # : 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + name_);
# # # # ]
120 : : }
121 : :
122 [ # # ]: 0 : CScript scriptPubKey = GetScriptForDestination(destination);
123 [ # # # # ]: 0 : CAmount nAmount = AmountFromValue(outputs[name_]);
124 : :
125 [ # # # # ]: 0 : CTxOut out(nAmount, scriptPubKey);
126 [ # # ]: 0 : rawTx.vout.push_back(out);
127 : 0 : }
128 : : }
129 : 0 : }
130 : :
131 : 0 : CMutableTransaction ConstructTransaction(const UniValue& inputs_in, const UniValue& outputs_in, const UniValue& locktime, std::optional<bool> rbf)
132 : : {
133 : 0 : CMutableTransaction rawTx;
134 : :
135 [ # # # # ]: 0 : if (!locktime.isNull()) {
136 [ # # ]: 0 : int64_t nLockTime = locktime.getInt<int64_t>();
137 [ # # ]: 0 : if (nLockTime < 0 || nLockTime > LOCKTIME_MAX)
138 [ # # # # : 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");
# # ]
139 : 0 : rawTx.nLockTime = nLockTime;
140 : 0 : }
141 : :
142 [ # # ]: 0 : AddInputs(rawTx, inputs_in, rbf);
143 [ # # ]: 0 : AddOutputs(rawTx, outputs_in);
144 : :
145 [ # # # # : 0 : if (rbf.has_value() && rbf.value() && rawTx.vin.size() > 0 && !SignalsOptInRBF(CTransaction(rawTx))) {
# # # # #
# # # # #
# # # # ]
146 [ # # # # : 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter combination: Sequence number(s) contradict replaceable option");
# # ]
147 : : }
148 : :
149 : 0 : return rawTx;
150 [ # # ]: 0 : }
151 : :
152 : : /** Pushes a JSON object for script verification or signing errors to vErrorsRet. */
153 : 0 : static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)
154 : : {
155 [ # # ]: 0 : UniValue entry(UniValue::VOBJ);
156 [ # # # # : 0 : entry.pushKV("txid", txin.prevout.hash.ToString());
# # # # ]
157 [ # # # # : 0 : entry.pushKV("vout", (uint64_t)txin.prevout.n);
# # ]
158 [ # # ]: 0 : UniValue witness(UniValue::VARR);
159 [ # # ]: 0 : for (unsigned int i = 0; i < txin.scriptWitness.stack.size(); i++) {
160 [ # # # # : 0 : witness.push_back(HexStr(txin.scriptWitness.stack[i]));
# # # # ]
161 : 0 : }
162 [ # # # # : 0 : entry.pushKV("witness", witness);
# # ]
163 [ # # # # : 0 : entry.pushKV("scriptSig", HexStr(txin.scriptSig));
# # # # #
# ]
164 [ # # # # : 0 : entry.pushKV("sequence", (uint64_t)txin.nSequence);
# # ]
165 [ # # # # : 0 : entry.pushKV("error", strMessage);
# # ]
166 [ # # # # ]: 0 : vErrorsRet.push_back(entry);
167 : 0 : }
168 : :
169 : 0 : void ParsePrevouts(const UniValue& prevTxsUnival, FillableSigningProvider* keystore, std::map<COutPoint, Coin>& coins)
170 : : {
171 [ # # ]: 0 : if (!prevTxsUnival.isNull()) {
172 : 0 : const UniValue& prevTxs = prevTxsUnival.get_array();
173 [ # # ]: 0 : for (unsigned int idx = 0; idx < prevTxs.size(); ++idx) {
174 : 0 : const UniValue& p = prevTxs[idx];
175 [ # # ]: 0 : if (!p.isObject()) {
176 [ # # # # : 0 : throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
# # ]
177 : : }
178 : :
179 : 0 : const UniValue& prevOut = p.get_obj();
180 : :
181 [ # # ]: 0 : RPCTypeCheckObj(prevOut,
182 [ # # ]: 0 : {
183 [ # # # # ]: 0 : {"txid", UniValueType(UniValue::VSTR)},
184 [ # # # # ]: 0 : {"vout", UniValueType(UniValue::VNUM)},
185 [ # # # # ]: 0 : {"scriptPubKey", UniValueType(UniValue::VSTR)},
186 : : });
187 : :
188 [ # # # # ]: 0 : uint256 txid = ParseHashO(prevOut, "txid");
189 : :
190 : 0 : int nOut = prevOut.find_value("vout").getInt<int>();
191 [ # # ]: 0 : if (nOut < 0) {
192 [ # # # # : 0 : throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout cannot be negative");
# # ]
193 : : }
194 : :
195 : 0 : COutPoint out(txid, nOut);
196 [ # # # # ]: 0 : std::vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
197 [ # # ]: 0 : CScript scriptPubKey(pkData.begin(), pkData.end());
198 : :
199 : : {
200 [ # # ]: 0 : auto coin = coins.find(out);
201 [ # # # # : 0 : if (coin != coins.end() && !coin->second.IsSpent() && coin->second.out.scriptPubKey != scriptPubKey) {
# # # # #
# ]
202 [ # # ]: 0 : std::string err("Previous output scriptPubKey mismatch:\n");
203 [ # # # # : 0 : err = err + ScriptToAsmStr(coin->second.out.scriptPubKey) + "\nvs:\n"+
# # # # ]
204 [ # # ]: 0 : ScriptToAsmStr(scriptPubKey);
205 [ # # ]: 0 : throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
206 : 0 : }
207 [ # # ]: 0 : Coin newcoin;
208 [ # # ]: 0 : newcoin.out.scriptPubKey = scriptPubKey;
209 : 0 : newcoin.out.nValue = MAX_MONEY;
210 [ # # # # : 0 : if (prevOut.exists("amount")) {
# # ]
211 [ # # # # ]: 0 : newcoin.out.nValue = AmountFromValue(prevOut.find_value("amount"));
212 : 0 : }
213 : 0 : newcoin.nHeight = 1;
214 [ # # ]: 0 : coins[out] = std::move(newcoin);
215 : 0 : }
216 : :
217 : : // if redeemScript and private keys were given, add redeemScript to the keystore so it can be signed
218 [ # # ]: 0 : const bool is_p2sh = scriptPubKey.IsPayToScriptHash();
219 [ # # ]: 0 : const bool is_p2wsh = scriptPubKey.IsPayToWitnessScriptHash();
220 [ # # # # : 0 : if (keystore && (is_p2sh || is_p2wsh)) {
# # ]
221 [ # # ]: 0 : RPCTypeCheckObj(prevOut,
222 [ # # ]: 0 : {
223 [ # # # # ]: 0 : {"redeemScript", UniValueType(UniValue::VSTR)},
224 [ # # # # ]: 0 : {"witnessScript", UniValueType(UniValue::VSTR)},
225 : : }, true);
226 [ # # ]: 0 : const UniValue& rs{prevOut.find_value("redeemScript")};
227 [ # # ]: 0 : const UniValue& ws{prevOut.find_value("witnessScript")};
228 [ # # # # : 0 : if (rs.isNull() && ws.isNull()) {
# # # # ]
229 [ # # # # : 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Missing redeemScript/witnessScript");
# # ]
230 : : }
231 : :
232 : : // work from witnessScript when possible
233 [ # # # # : 0 : std::vector<unsigned char> scriptData(!ws.isNull() ? ParseHexV(ws, "witnessScript") : ParseHexV(rs, "redeemScript"));
# # # # #
# # # # #
# # # # #
# # # # #
# # # # ]
234 [ # # ]: 0 : CScript script(scriptData.begin(), scriptData.end());
235 [ # # ]: 0 : keystore->AddCScript(script);
236 : : // Automatically also add the P2WSH wrapped version of the script (to deal with P2SH-P2WSH).
237 : : // This is done for redeemScript only for compatibility, it is encouraged to use the explicit witnessScript field instead.
238 [ # # # # ]: 0 : CScript witness_output_script{GetScriptForDestination(WitnessV0ScriptHash(script))};
239 [ # # ]: 0 : keystore->AddCScript(witness_output_script);
240 : :
241 [ # # # # : 0 : if (!ws.isNull() && !rs.isNull()) {
# # # # ]
242 : : // if both witnessScript and redeemScript are provided,
243 : : // they should either be the same (for backwards compat),
244 : : // or the redeemScript should be the encoded form of
245 : : // the witnessScript (ie, for p2sh-p2wsh)
246 [ # # # # : 0 : if (ws.get_str() != rs.get_str()) {
# # ]
247 [ # # # # ]: 0 : std::vector<unsigned char> redeemScriptData(ParseHexV(rs, "redeemScript"));
248 [ # # ]: 0 : CScript redeemScript(redeemScriptData.begin(), redeemScriptData.end());
249 [ # # # # ]: 0 : if (redeemScript != witness_output_script) {
250 [ # # # # : 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "redeemScript does not correspond to witnessScript");
# # ]
251 : : }
252 : 0 : }
253 : 0 : }
254 : :
255 [ # # ]: 0 : if (is_p2sh) {
256 [ # # ]: 0 : const CTxDestination p2sh{ScriptHash(script)};
257 [ # # ]: 0 : const CTxDestination p2sh_p2wsh{ScriptHash(witness_output_script)};
258 [ # # # # : 0 : if (scriptPubKey == GetScriptForDestination(p2sh)) {
# # ]
259 : : // traditional p2sh; arguably an error if
260 : : // we got here with rs.IsNull(), because
261 : : // that means the p2sh script was specified
262 : : // via witnessScript param, but for now
263 : : // we'll just quietly accept it
264 [ # # # # : 0 : } else if (scriptPubKey == GetScriptForDestination(p2sh_p2wsh)) {
# # ]
265 : : // p2wsh encoded as p2sh; ideally the witness
266 : : // script was specified in the witnessScript
267 : : // param, but also support specifying it via
268 : : // redeemScript param for backwards compat
269 : : // (in which case ws.IsNull() == true)
270 : 0 : } else {
271 : : // otherwise, can't generate scriptPubKey from
272 : : // either script, so we got unusable parameters
273 [ # # # # : 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "redeemScript/witnessScript does not match scriptPubKey");
# # ]
274 : : }
275 [ # # ]: 0 : } else if (is_p2wsh) {
276 : : // plain p2wsh; could throw an error if script
277 : : // was specified by redeemScript rather than
278 : : // witnessScript (ie, ws.IsNull() == true), but
279 : : // accept it for backwards compat
280 [ # # ]: 0 : const CTxDestination p2wsh{WitnessV0ScriptHash(script)};
281 [ # # # # : 0 : if (scriptPubKey != GetScriptForDestination(p2wsh)) {
# # ]
282 [ # # # # : 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "redeemScript/witnessScript does not match scriptPubKey");
# # ]
283 : : }
284 : 0 : }
285 : 0 : }
286 : 0 : }
287 : 0 : }
288 : 0 : }
289 : :
290 : 0 : void SignTransaction(CMutableTransaction& mtx, const SigningProvider* keystore, const std::map<COutPoint, Coin>& coins, const UniValue& hashType, UniValue& result)
291 : : {
292 : 0 : int nHashType = ParseSighashString(hashType);
293 : :
294 : : // Script verification errors
295 : 0 : std::map<int, bilingual_str> input_errors;
296 : :
297 [ # # ]: 0 : bool complete = SignTransaction(mtx, keystore, coins, nHashType, input_errors);
298 [ # # ]: 0 : SignTransactionResultToJSON(mtx, complete, coins, input_errors, result);
299 : 0 : }
300 : :
301 : 0 : void SignTransactionResultToJSON(CMutableTransaction& mtx, bool complete, const std::map<COutPoint, Coin>& coins, const std::map<int, bilingual_str>& input_errors, UniValue& result)
302 : : {
303 : : // Make errors UniValue
304 [ # # ]: 0 : UniValue vErrors(UniValue::VARR);
305 [ # # ]: 0 : for (const auto& err_pair : input_errors) {
306 [ # # # # ]: 0 : if (err_pair.second.original == "Missing amount") {
307 : : // This particular error needs to be an exception for some reason
308 [ # # # # : 0 : throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing amount for %s", coins.at(mtx.vin.at(err_pair.first).prevout).out.ToString()));
# # # # #
# # # #
# ]
309 : : }
310 [ # # # # ]: 0 : TxInErrorToJSON(mtx.vin.at(err_pair.first), vErrors, err_pair.second.original);
311 : : }
312 : :
313 [ # # # # : 0 : result.pushKV("hex", EncodeHexTx(CTransaction(mtx)));
# # # # #
# ]
314 [ # # # # : 0 : result.pushKV("complete", complete);
# # ]
315 [ # # # # ]: 0 : if (!vErrors.empty()) {
316 [ # # # # : 0 : if (result.exists("errors")) {
# # ]
317 [ # # # # : 0 : vErrors.push_backV(result["errors"].getValues());
# # # # ]
318 : 0 : }
319 [ # # # # : 0 : result.pushKV("errors", vErrors);
# # ]
320 : 0 : }
321 : 0 : }
|