Bitcoin ABC 0.32.5
P2P Digital Currency
rawtransaction_util.cpp
Go to the documentation of this file.
1// Copyright (c) 2010 Satoshi Nakamoto
2// Copyright (c) 2009-2019 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
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>
14#include <rpc/request.h>
15#include <rpc/util.h>
16#include <script/sign.h>
18#include <tinyformat.h>
19#include <univalue.h>
20#include <util/strencodings.h>
21#include <util/vector.h>
22
24 const UniValue &inputs_in,
25 const UniValue &outputs_in,
26 const UniValue &locktime) {
27 if (outputs_in.isNull()) {
28 throw JSONRPCError(
30 "Invalid parameter, output argument must be non-null");
31 }
32
33 UniValue inputs;
34 if (inputs_in.isNull()) {
35 inputs = UniValue::VARR;
36 } else {
37 inputs = inputs_in.get_array();
38 }
39
40 const bool outputs_is_obj = outputs_in.isObject();
41 UniValue outputs =
42 outputs_is_obj ? outputs_in.get_obj() : outputs_in.get_array();
43
45
46 if (!locktime.isNull()) {
47 int64_t nLockTime = locktime.getInt<int64_t>();
48 if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max()) {
50 "Invalid parameter, locktime out of range");
51 }
52
53 rawTx.nLockTime = nLockTime;
54 }
55
56 for (size_t idx = 0; idx < inputs.size(); idx++) {
57 const UniValue &input = inputs[idx];
58 const UniValue &o = input.get_obj();
59
60 TxId txid(ParseHashO(o, "txid"));
61
62 const UniValue &vout_v = o.find_value("vout");
63 if (vout_v.isNull()) {
65 "Invalid parameter, missing vout key");
66 }
67
68 if (!vout_v.isNum()) {
70 "Invalid parameter, vout must be a number");
71 }
72
73 int nOutput = vout_v.getInt<int>();
74 if (nOutput < 0) {
76 "Invalid parameter, vout cannot be negative");
77 }
78
79 uint32_t nSequence =
80 (rawTx.nLockTime ? std::numeric_limits<uint32_t>::max() - 1
81 : std::numeric_limits<uint32_t>::max());
82
83 // Set the sequence number if passed in the parameters object.
84 const UniValue &sequenceObj = o.find_value("sequence");
85 if (sequenceObj.isNum()) {
86 int64_t seqNr64 = sequenceObj.getInt<int64_t>();
87 if (seqNr64 < 0 || seqNr64 > std::numeric_limits<uint32_t>::max()) {
88 throw JSONRPCError(
90 "Invalid parameter, sequence number is out of range");
91 }
92
93 nSequence = uint32_t(seqNr64);
94 }
95
96 CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
97 rawTx.vin.push_back(in);
98 }
99
100 if (!outputs_is_obj) {
101 // Translate array of key-value pairs into dict
102 UniValue outputs_dict = UniValue(UniValue::VOBJ);
103 for (size_t i = 0; i < outputs.size(); ++i) {
104 const UniValue &output = outputs[i];
105 if (!output.isObject()) {
107 "Invalid parameter, key-value pair not an "
108 "object as expected");
109 }
110 if (output.size() != 1) {
112 "Invalid parameter, key-value pair must "
113 "contain exactly one key");
114 }
115 outputs_dict.pushKVs(output);
116 }
117 outputs = std::move(outputs_dict);
118 }
119
120 // Duplicate checking
121 std::set<CTxDestination> destinations;
122 bool has_data{false};
123
124 for (const std::string &name_ : outputs.getKeys()) {
125 if (name_ == "data") {
126 if (has_data) {
128 "Invalid parameter, duplicate key: data");
129 }
130 has_data = true;
131 std::vector<uint8_t> data =
132 ParseHexV(outputs[name_].getValStr(), "Data");
133
134 CTxOut out(Amount::zero(), CScript() << OP_RETURN << data);
135 rawTx.vout.push_back(out);
136 } else {
137 CTxDestination destination = DecodeDestination(name_, params);
138 if (!IsValidDestination(destination)) {
140 std::string("Invalid Bitcoin address: ") +
141 name_);
142 }
143
144 if (!destinations.insert(destination).second) {
145 throw JSONRPCError(
147 std::string("Invalid parameter, duplicated address: ") +
148 name_);
149 }
150
151 CScript scriptPubKey = GetScriptForDestination(destination);
152 Amount nAmount = AmountFromValue(outputs[name_]);
153
154 CTxOut out(nAmount, scriptPubKey);
155 rawTx.vout.push_back(out);
156 }
157 }
158
159 return rawTx;
160}
161
165static void TxInErrorToJSON(const CTxIn &txin, UniValue &vErrorsRet,
166 const std::string &strMessage) {
168 entry.pushKV("txid", txin.prevout.GetTxId().ToString());
169 entry.pushKV("vout", uint64_t(txin.prevout.GetN()));
170 entry.pushKV("scriptSig", HexStr(txin.scriptSig));
171 entry.pushKV("sequence", uint64_t(txin.nSequence));
172 entry.pushKV("error", strMessage);
173 vErrorsRet.push_back(entry);
174}
175
176void ParsePrevouts(const UniValue &prevTxsUnival,
177 FillableSigningProvider *keystore,
178 std::map<COutPoint, Coin> &coins) {
179 if (!prevTxsUnival.isNull()) {
180 const UniValue &prevTxs = prevTxsUnival.get_array();
181 for (size_t idx = 0; idx < prevTxs.size(); ++idx) {
182 const UniValue &p = prevTxs[idx];
183 if (!p.isObject()) {
185 "expected object with "
186 "{\"txid'\",\"vout\",\"scriptPubKey\"}");
187 }
188
189 const UniValue &prevOut = p.get_obj();
190
191 RPCTypeCheckObj(prevOut,
192 {
193 {"txid", UniValueType(UniValue::VSTR)},
194 {"vout", UniValueType(UniValue::VNUM)},
195 {"scriptPubKey", UniValueType(UniValue::VSTR)},
196 // "amount" is also required but check is done
197 // below due to UniValue::VNUM erroneously
198 // not accepting quoted numerics
199 // (which are valid JSON)
200 });
201
202 TxId txid(ParseHashO(prevOut, "txid"));
203
204 int nOut = prevOut.find_value("vout").getInt<int>();
205 if (nOut < 0) {
207 "vout cannot be negative");
208 }
209
210 COutPoint out(txid, nOut);
211 std::vector<uint8_t> pkData(ParseHexO(prevOut, "scriptPubKey"));
212 CScript scriptPubKey(pkData.begin(), pkData.end());
213
214 {
215 auto coin = coins.find(out);
216 if (coin != coins.end() && !coin->second.IsSpent() &&
217 coin->second.GetTxOut().scriptPubKey != scriptPubKey) {
218 std::string err("Previous output scriptPubKey mismatch:\n");
219 err = err +
220 ScriptToAsmStr(coin->second.GetTxOut().scriptPubKey) +
221 "\nvs:\n" + ScriptToAsmStr(scriptPubKey);
223 }
224
225 CTxOut txout;
226 txout.scriptPubKey = scriptPubKey;
227 txout.nValue = MAX_MONEY;
228 if (prevOut.exists("amount")) {
229 txout.nValue =
230 AmountFromValue(prevOut.find_value("amount"));
231 } else {
232 // amount param is required in replay-protected txs.
233 // Note that we must check for its presence here rather
234 // than use RPCTypeCheckObj() above, since UniValue::VNUM
235 // parser incorrectly parses numerics with quotes, eg
236 // "3.12" as a string when JSON allows it to also parse
237 // as numeric. And we have to accept numerics with quotes
238 // because our own dogfood (our rpc results) always
239 // produces decimal numbers that are quoted
240 // eg getbalance returns "3.14152" rather than 3.14152
241 throw JSONRPCError(RPC_INVALID_PARAMETER, "Missing amount");
242 }
243 coins[out] = Coin(txout, 1, false);
244 }
245
246 // If redeemScript and private keys were given, add redeemScript to
247 // the keystore so it can be signed
248 if (keystore && scriptPubKey.IsPayToScriptHash()) {
250 prevOut, {
251 {"redeemScript", UniValueType(UniValue::VSTR)},
252 });
253 const UniValue &v{prevOut.find_value("redeemScript")};
254 if (!v.isNull()) {
255 std::vector<uint8_t> rsData(ParseHexV(v, "redeemScript"));
256 CScript redeemScript(rsData.begin(), rsData.end());
257 keystore->AddCScript(redeemScript);
258 }
259 }
260 }
261 }
262}
263
265 const std::map<COutPoint, Coin> &coins,
266 const UniValue &hashType, UniValue &result) {
267 SigHashType sigHashType = ParseSighashString(hashType);
268 if (!sigHashType.hasForkId()) {
270 "Signature must use SIGHASH_FORKID");
271 }
272
273 // Script verification errors
274 std::map<int, std::string> input_errors;
275
276 bool complete =
277 SignTransaction(mtx, keystore, coins, sigHashType, input_errors);
278 SignTransactionResultToJSON(mtx, complete, coins, input_errors, result);
279}
280
282 const std::map<COutPoint, Coin> &coins,
283 const std::map<int, std::string> &input_errors,
284 UniValue &result) {
285 // Make errors UniValue
286 UniValue vErrors(UniValue::VARR);
287 for (const auto &err_pair : input_errors) {
288 if (err_pair.second == "Missing amount") {
289 // This particular error needs to be an exception for some reason
290 throw JSONRPCError(
292 strprintf("Missing amount for %s",
293 coins.at(mtx.vin.at(err_pair.first).prevout)
294 .GetTxOut()
295 .ToString()));
296 }
297 TxInErrorToJSON(mtx.vin.at(err_pair.first), vErrors, err_pair.second);
298 }
299
300 result.pushKV("hex", EncodeHexTx(CTransaction(mtx)));
301 result.pushKV("complete", complete);
302 if (!vErrors.empty()) {
303 if (result.exists("errors")) {
304 vErrors.push_backV(result["errors"].getValues());
305 }
306 result.pushKV("errors", vErrors);
307 }
308}
309
310std::vector<RPCResult> DecodeTxDoc(const std::string &txid_field_doc,
311 bool wallet) {
312 return {
313 {RPCResult::Type::STR_HEX, "txid", txid_field_doc},
314 {RPCResult::Type::STR_HEX, "hash", "The transaction hash"},
315 {RPCResult::Type::NUM, "size", "The serialized transaction size"},
316 {RPCResult::Type::NUM, "version", "The version"},
317 {RPCResult::Type::NUM_TIME, "locktime", "The lock time"},
319 "vin",
320 "",
321 {
323 "",
324 "",
325 {
326 {RPCResult::Type::STR_HEX, "coinbase", /*optional=*/true,
327 "The coinbase value (only if coinbase transaction)"},
328 {RPCResult::Type::STR_HEX, "txid", /*optional=*/true,
329 "The transaction id (if not coinbase transaction)"},
330 {RPCResult::Type::NUM, "vout", /*optional=*/true,
331 "The output number (if not coinbase transaction)"},
333 "scriptSig",
334 /*optional=*/true,
335 "The script (if not coinbase transaction)",
336 {
337 {RPCResult::Type::STR, "asm", "asm"},
338 {RPCResult::Type::STR_HEX, "hex", "hex"},
339 }},
340 {RPCResult::Type::NUM, "sequence",
341 "The script sequence number"},
342 }},
343 }},
345 "vout",
346 "",
347 {
348 {RPCResult::Type::OBJ, "", "",
349 Cat(
350 {
352 "The value in " + Currency::get().ticker},
353 {RPCResult::Type::NUM, "n", "index"},
355 "scriptPubKey",
356 "",
357 {
358 {RPCResult::Type::STR, "asm", "the asm"},
359 {RPCResult::Type::STR_HEX, "hex", "the hex"},
360 {RPCResult::Type::NUM, "reqSigs",
361 "The required sigs"},
362 {RPCResult::Type::STR, "type",
363 "The type, eg 'pubkeyhash'"},
365 "addresses",
366 "",
367 {
368 {RPCResult::Type::STR, "address",
369 /*optional=*/true,
370 "The eCash address (only if a well-defined "
371 "address exists)"},
372 }},
373 }},
374 },
375 wallet
376 ? std::vector<RPCResult>{{RPCResult::Type::BOOL,
377 "ischange", /*optional=*/true,
378 "Output script is change (only "
379 "present if true)"}}
380 : std::vector<RPCResult>{})},
381 }},
382 };
383}
static constexpr Amount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:165
const CScript redeemScript
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system.
Definition: chainparams.h:86
A mutable version of CTransaction.
Definition: transaction.h:274
std::vector< CTxOut > vout
Definition: transaction.h:277
std::vector< CTxIn > vin
Definition: transaction.h:276
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:20
const TxId & GetTxId() const
Definition: transaction.h:35
uint32_t GetN() const
Definition: transaction.h:36
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:432
bool IsPayToScriptHash() const
Definition: script.cpp:373
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:192
An input of a transaction.
Definition: transaction.h:59
uint32_t nSequence
Definition: transaction.h:63
CScript scriptSig
Definition: transaction.h:62
COutPoint prevout
Definition: transaction.h:61
An output of a transaction.
Definition: transaction.h:128
CScript scriptPubKey
Definition: transaction.h:131
Amount nValue
Definition: transaction.h:130
A UTXO entry.
Definition: coins.h:29
Fillable signing provider that keeps keys in an address->secret map.
virtual bool AddCScript(const CScript &redeemScript)
Signature hash type wrapper class.
Definition: sighashtype.h:37
bool hasForkId() const
Definition: sighashtype.h:77
An interface to be implemented by keystores that support signing.
void push_back(UniValue val)
Definition: univalue.cpp:96
const UniValue & find_value(std::string_view key) const
Definition: univalue.cpp:229
@ VOBJ
Definition: univalue.h:31
@ VSTR
Definition: univalue.h:33
@ VARR
Definition: univalue.h:32
@ VNUM
Definition: univalue.h:34
bool isNull() const
Definition: univalue.h:104
const UniValue & get_obj() const
size_t size() const
Definition: univalue.h:92
void pushKVs(UniValue obj)
Definition: univalue.cpp:126
const std::vector< std::string > & getKeys() const
bool empty() const
Definition: univalue.h:90
Int getInt() const
Definition: univalue.h:157
const UniValue & get_array() const
bool exists(const std::string &key) const
Definition: univalue.h:99
bool isNum() const
Definition: univalue.h:109
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:115
void push_backV(const std::vector< UniValue > &vec)
Definition: univalue.cpp:102
bool isObject() const
Definition: univalue.h:111
std::string ToString() const
Definition: uint256.h:80
std::string EncodeHexTx(const CTransaction &tx)
Definition: core_write.cpp:173
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode=false)
Create the assembly string representation of a CScript object.
Definition: core_write.cpp:106
SigHashType ParseSighashString(const UniValue &sighash)
Definition: core_read.cpp:273
CTxDestination DecodeDestination(const std::string &addr, const CChainParams &params)
Definition: key_io.cpp:174
void SignTransaction(CMutableTransaction &mtx, const SigningProvider *keystore, const std::map< COutPoint, Coin > &coins, const UniValue &hashType, UniValue &result)
Sign a transaction with the given keystore and previous transactions.
void SignTransactionResultToJSON(CMutableTransaction &mtx, bool complete, const std::map< COutPoint, Coin > &coins, const std::map< int, std::string > &input_errors, UniValue &result)
CMutableTransaction ConstructTransaction(const CChainParams &params, const UniValue &inputs_in, const UniValue &outputs_in, const UniValue &locktime)
Create a transaction from univalue parameters.
std::vector< RPCResult > DecodeTxDoc(const std::string &txid_field_doc, bool wallet)
Explain the UniValue "decoded" transaction object, may include extra fields if processed by wallet.
static void TxInErrorToJSON(const CTxIn &txin, UniValue &vErrorsRet, const std::string &strMessage)
Pushes a JSON object for script verification or signing errors to vErrorsRet.
void ParsePrevouts(const UniValue &prevTxsUnival, FillableSigningProvider *keystore, std::map< COutPoint, Coin > &coins)
Parse a prevtxs UniValue array and get the map of coins from it.
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:58
@ RPC_TYPE_ERROR
Unexpected type was passed as parameter.
Definition: protocol.h:40
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:46
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
Definition: protocol.h:50
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
Definition: protocol.h:42
Amount AmountFromValue(const UniValue &value)
Definition: util.cpp:58
std::vector< uint8_t > ParseHexV(const UniValue &v, std::string strName)
Definition: util.cpp:97
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: util.cpp:93
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull, bool fStrict)
Check for expected keys/value types in an Object.
Definition: util.cpp:29
std::vector< uint8_t > ParseHexO(const UniValue &o, std::string strKey)
Definition: util.cpp:111
@ OP_RETURN
Definition: script.h:88
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:260
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:240
std::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:85
Definition: amount.h:19
static constexpr Amount zero() noexcept
Definition: amount.h:32
static const Currency & get()
Definition: amount.cpp:18
std::string ticker
Definition: amount.h:150
@ NUM_TIME
Special numeric to denote unix epoch time.
@ STR_HEX
Special string with only hex chars.
@ STR_AMOUNT
Special string to represent a floating point amount.
A TxId is the identifier of a transaction.
Definition: txid.h:14
Wrapper for UniValue::VType, which includes typeAny: used to denote don't care type.
Definition: util.h:61
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1202
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
V Cat(V v1, V &&v2)
Concatenate two vectors, moving elements.
Definition: vector.h:34