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