/Users/eugenesiegel/btc/bitcoin/src/rpc/rawtransaction_util.cpp
Line | Count | Source (jump to first uncovered line) |
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 | | void AddInputs(CMutableTransaction& rawTx, const UniValue& inputs_in, std::optional<bool> rbf) |
26 | 0 | { |
27 | 0 | UniValue inputs; |
28 | 0 | if (inputs_in.isNull()) { |
29 | 0 | inputs = UniValue::VARR; |
30 | 0 | } else { |
31 | 0 | inputs = inputs_in.get_array(); |
32 | 0 | } |
33 | |
|
34 | 0 | for (unsigned int idx = 0; idx < inputs.size(); idx++) { |
35 | 0 | const UniValue& input = inputs[idx]; |
36 | 0 | const UniValue& o = input.get_obj(); |
37 | |
|
38 | 0 | 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 | 0 | nSequence = MAX_BIP125_RBF_SEQUENCE; /* CTxIn::SEQUENCE_FINAL - 2 */ |
51 | 0 | } else if (rawTx.nLockTime) { |
52 | 0 | nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; /* CTxIn::SEQUENCE_FINAL - 1 */ |
53 | 0 | } else { |
54 | 0 | nSequence = CTxIn::SEQUENCE_FINAL; |
55 | 0 | } |
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 | 0 | } else { |
64 | 0 | nSequence = (uint32_t)seqNr64; |
65 | 0 | } |
66 | 0 | } |
67 | | |
68 | 0 | CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence); |
69 | |
|
70 | 0 | rawTx.vin.push_back(in); |
71 | 0 | } |
72 | 0 | } |
73 | | |
74 | | UniValue NormalizeOutputs(const UniValue& outputs_in) |
75 | 0 | { |
76 | 0 | if (outputs_in.isNull()) { |
77 | 0 | throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, output argument must be non-null"); |
78 | 0 | } |
79 | | |
80 | 0 | const bool outputs_is_obj = outputs_in.isObject(); |
81 | 0 | UniValue outputs = outputs_is_obj ? outputs_in.get_obj() : outputs_in.get_array(); |
82 | |
|
83 | 0 | if (!outputs_is_obj) { |
84 | | // Translate array of key-value pairs into dict |
85 | 0 | UniValue outputs_dict = UniValue(UniValue::VOBJ); |
86 | 0 | for (size_t i = 0; i < outputs.size(); ++i) { |
87 | 0 | const UniValue& output = outputs[i]; |
88 | 0 | if (!output.isObject()) { |
89 | 0 | throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, key-value pair not an object as expected"); |
90 | 0 | } |
91 | 0 | if (output.size() != 1) { |
92 | 0 | throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, key-value pair must contain exactly one key"); |
93 | 0 | } |
94 | 0 | outputs_dict.pushKVs(output); |
95 | 0 | } |
96 | 0 | outputs = std::move(outputs_dict); |
97 | 0 | } |
98 | 0 | return outputs; |
99 | 0 | } |
100 | | |
101 | | std::vector<std::pair<CTxDestination, CAmount>> ParseOutputs(const UniValue& outputs) |
102 | 0 | { |
103 | | // Duplicate checking |
104 | 0 | std::set<CTxDestination> destinations; |
105 | 0 | std::vector<std::pair<CTxDestination, CAmount>> parsed_outputs; |
106 | 0 | bool has_data{false}; |
107 | 0 | 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 | 0 | } |
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 | 0 | } |
123 | | |
124 | 0 | if (!destinations.insert(destination).second) { |
125 | 0 | throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + name_); |
126 | 0 | } |
127 | 0 | parsed_outputs.emplace_back(destination, amount); |
128 | 0 | } |
129 | 0 | } |
130 | 0 | return parsed_outputs; |
131 | 0 | } |
132 | | |
133 | | void AddOutputs(CMutableTransaction& rawTx, const UniValue& outputs_in) |
134 | 0 | { |
135 | 0 | UniValue outputs(UniValue::VOBJ); |
136 | 0 | outputs = NormalizeOutputs(outputs_in); |
137 | |
|
138 | 0 | std::vector<std::pair<CTxDestination, CAmount>> parsed_outputs = ParseOutputs(outputs); |
139 | 0 | 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 | 0 | } |
146 | | |
147 | | CMutableTransaction ConstructTransaction(const UniValue& inputs_in, const UniValue& outputs_in, const UniValue& locktime, std::optional<bool> rbf, const uint32_t version) |
148 | 0 | { |
149 | 0 | CMutableTransaction rawTx; |
150 | |
|
151 | 0 | if (!locktime.isNull()) { |
152 | 0 | int64_t nLockTime = locktime.getInt<int64_t>(); |
153 | 0 | if (nLockTime < 0 || nLockTime > LOCKTIME_MAX) |
154 | 0 | throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range"); |
155 | 0 | rawTx.nLockTime = nLockTime; |
156 | 0 | } |
157 | | |
158 | 0 | 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)); Line | Count | Source | 1172 | 0 | #define strprintf tfm::format |
|
160 | 0 | } |
161 | 0 | rawTx.version = version; |
162 | |
|
163 | 0 | AddInputs(rawTx, inputs_in, rbf); |
164 | 0 | AddOutputs(rawTx, outputs_in); |
165 | |
|
166 | 0 | 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 | 0 | } |
169 | | |
170 | 0 | return rawTx; |
171 | 0 | } |
172 | | |
173 | | /** Pushes a JSON object for script verification or signing errors to vErrorsRet. */ |
174 | | static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage) |
175 | 0 | { |
176 | 0 | UniValue entry(UniValue::VOBJ); |
177 | 0 | entry.pushKV("txid", txin.prevout.hash.ToString()); |
178 | 0 | entry.pushKV("vout", (uint64_t)txin.prevout.n); |
179 | 0 | UniValue witness(UniValue::VARR); |
180 | 0 | for (unsigned int i = 0; i < txin.scriptWitness.stack.size(); i++) { |
181 | 0 | witness.push_back(HexStr(txin.scriptWitness.stack[i])); |
182 | 0 | } |
183 | 0 | entry.pushKV("witness", std::move(witness)); |
184 | 0 | entry.pushKV("scriptSig", HexStr(txin.scriptSig)); |
185 | 0 | entry.pushKV("sequence", (uint64_t)txin.nSequence); |
186 | 0 | entry.pushKV("error", strMessage); |
187 | 0 | vErrorsRet.push_back(std::move(entry)); |
188 | 0 | } |
189 | | |
190 | | void ParsePrevouts(const UniValue& prevTxsUnival, FlatSigningProvider* keystore, std::map<COutPoint, Coin>& coins) |
191 | 0 | { |
192 | 0 | if (!prevTxsUnival.isNull()) { |
193 | 0 | const UniValue& prevTxs = prevTxsUnival.get_array(); |
194 | 0 | for (unsigned int idx = 0; idx < prevTxs.size(); ++idx) { |
195 | 0 | const UniValue& p = prevTxs[idx]; |
196 | 0 | if (!p.isObject()) { |
197 | 0 | throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}"); |
198 | 0 | } |
199 | | |
200 | 0 | const UniValue& prevOut = p.get_obj(); |
201 | |
|
202 | 0 | RPCTypeCheckObj(prevOut, |
203 | 0 | { |
204 | 0 | {"txid", UniValueType(UniValue::VSTR)}, |
205 | 0 | {"vout", UniValueType(UniValue::VNUM)}, |
206 | 0 | {"scriptPubKey", UniValueType(UniValue::VSTR)}, |
207 | 0 | }); |
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 | 0 | } |
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 | 0 | } |
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 | 0 | { |
244 | 0 | {"redeemScript", UniValueType(UniValue::VSTR)}, |
245 | 0 | {"witnessScript", UniValueType(UniValue::VSTR)}, |
246 | 0 | }, 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 | 0 | } |
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 | 0 | } |
273 | 0 | } |
274 | 0 | } |
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 | 0 | } 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 | 0 | } |
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 | 0 | } |
305 | 0 | } |
306 | 0 | } |
307 | 0 | } |
308 | 0 | } |
309 | 0 | } |
310 | | |
311 | | void SignTransaction(CMutableTransaction& mtx, const SigningProvider* keystore, const std::map<COutPoint, Coin>& coins, const UniValue& hashType, UniValue& result) |
312 | 0 | { |
313 | 0 | std::optional<int> nHashType = ParseSighashString(hashType); |
314 | 0 | if (!nHashType) { |
315 | 0 | nHashType = SIGHASH_DEFAULT; |
316 | 0 | } |
317 | | |
318 | | // Script verification errors |
319 | 0 | std::map<int, bilingual_str> input_errors; |
320 | |
|
321 | 0 | bool complete = SignTransaction(mtx, keystore, coins, *nHashType, input_errors); |
322 | 0 | SignTransactionResultToJSON(mtx, complete, coins, input_errors, result); |
323 | 0 | } |
324 | | |
325 | | void SignTransactionResultToJSON(CMutableTransaction& mtx, bool complete, const std::map<COutPoint, Coin>& coins, const std::map<int, bilingual_str>& input_errors, UniValue& result) |
326 | 0 | { |
327 | | // Make errors UniValue |
328 | 0 | UniValue vErrors(UniValue::VARR); |
329 | 0 | for (const auto& err_pair : input_errors) { |
330 | 0 | 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())); Line | Count | Source | 1172 | 0 | #define strprintf tfm::format |
|
333 | 0 | } |
334 | 0 | TxInErrorToJSON(mtx.vin.at(err_pair.first), vErrors, err_pair.second.original); |
335 | 0 | } |
336 | | |
337 | 0 | result.pushKV("hex", EncodeHexTx(CTransaction(mtx))); |
338 | 0 | result.pushKV("complete", complete); |
339 | 0 | if (!vErrors.empty()) { |
340 | 0 | if (result.exists("errors")) { |
341 | 0 | vErrors.push_backV(result["errors"].getValues()); |
342 | 0 | } |
343 | 0 | result.pushKV("errors", std::move(vErrors)); |
344 | 0 | } |
345 | 0 | } |