Bitcoin Core  26.1.0
P2P Digital Currency
rawtransaction_util.cpp
Go to the documentation of this file.
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 
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/strencodings.h>
22 #include <util/translation.h>
23 
24 void AddInputs(CMutableTransaction& rawTx, const UniValue& inputs_in, std::optional<bool> rbf)
25 {
26  UniValue inputs;
27  if (inputs_in.isNull()) {
28  inputs = UniValue::VARR;
29  } else {
30  inputs = inputs_in.get_array();
31  }
32 
33  for (unsigned int idx = 0; idx < inputs.size(); idx++) {
34  const UniValue& input = inputs[idx];
35  const UniValue& o = input.get_obj();
36 
37  uint256 txid = ParseHashO(o, "txid");
38 
39  const UniValue& vout_v = o.find_value("vout");
40  if (!vout_v.isNum())
41  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
42  int nOutput = vout_v.getInt<int>();
43  if (nOutput < 0)
44  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout cannot be negative");
45 
46  uint32_t nSequence;
47 
48  if (rbf.value_or(true)) {
49  nSequence = MAX_BIP125_RBF_SEQUENCE; /* CTxIn::SEQUENCE_FINAL - 2 */
50  } else if (rawTx.nLockTime) {
51  nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; /* CTxIn::SEQUENCE_FINAL - 1 */
52  } else {
53  nSequence = CTxIn::SEQUENCE_FINAL;
54  }
55 
56  // set the sequence number if passed in the parameters object
57  const UniValue& sequenceObj = o.find_value("sequence");
58  if (sequenceObj.isNum()) {
59  int64_t seqNr64 = sequenceObj.getInt<int64_t>();
60  if (seqNr64 < 0 || seqNr64 > CTxIn::SEQUENCE_FINAL) {
61  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range");
62  } else {
63  nSequence = (uint32_t)seqNr64;
64  }
65  }
66 
67  CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
68 
69  rawTx.vin.push_back(in);
70  }
71 }
72 
73 void AddOutputs(CMutableTransaction& rawTx, const UniValue& outputs_in)
74 {
75  if (outputs_in.isNull()) {
76  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, output argument must be non-null");
77  }
78 
79  const bool outputs_is_obj = outputs_in.isObject();
80  UniValue outputs = outputs_is_obj ? outputs_in.get_obj() : outputs_in.get_array();
81 
82  if (!outputs_is_obj) {
83  // Translate array of key-value pairs into dict
84  UniValue outputs_dict = UniValue(UniValue::VOBJ);
85  for (size_t i = 0; i < outputs.size(); ++i) {
86  const UniValue& output = outputs[i];
87  if (!output.isObject()) {
88  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, key-value pair not an object as expected");
89  }
90  if (output.size() != 1) {
91  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, key-value pair must contain exactly one key");
92  }
93  outputs_dict.pushKVs(output);
94  }
95  outputs = std::move(outputs_dict);
96  }
97 
98  // Duplicate checking
99  std::set<CTxDestination> destinations;
100  bool has_data{false};
101 
102  for (const std::string& name_ : outputs.getKeys()) {
103  if (name_ == "data") {
104  if (has_data) {
105  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, duplicate key: data");
106  }
107  has_data = true;
108  std::vector<unsigned char> data = ParseHexV(outputs[name_].getValStr(), "Data");
109 
110  CTxOut out(0, CScript() << OP_RETURN << data);
111  rawTx.vout.push_back(out);
112  } else {
113  CTxDestination destination = DecodeDestination(name_);
114  if (!IsValidDestination(destination)) {
115  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Bitcoin address: ") + name_);
116  }
117 
118  if (!destinations.insert(destination).second) {
119  throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + name_);
120  }
121 
122  CScript scriptPubKey = GetScriptForDestination(destination);
123  CAmount nAmount = AmountFromValue(outputs[name_]);
124 
125  CTxOut out(nAmount, scriptPubKey);
126  rawTx.vout.push_back(out);
127  }
128  }
129 }
130 
131 CMutableTransaction ConstructTransaction(const UniValue& inputs_in, const UniValue& outputs_in, const UniValue& locktime, std::optional<bool> rbf)
132 {
133  CMutableTransaction rawTx;
134 
135  if (!locktime.isNull()) {
136  int64_t nLockTime = locktime.getInt<int64_t>();
137  if (nLockTime < 0 || nLockTime > LOCKTIME_MAX)
138  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");
139  rawTx.nLockTime = nLockTime;
140  }
141 
142  AddInputs(rawTx, inputs_in, rbf);
143  AddOutputs(rawTx, outputs_in);
144 
145  if (rbf.has_value() && rbf.value() && rawTx.vin.size() > 0 && !SignalsOptInRBF(CTransaction(rawTx))) {
146  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter combination: Sequence number(s) contradict replaceable option");
147  }
148 
149  return rawTx;
150 }
151 
153 static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)
154 {
155  UniValue entry(UniValue::VOBJ);
156  entry.pushKV("txid", txin.prevout.hash.ToString());
157  entry.pushKV("vout", (uint64_t)txin.prevout.n);
158  UniValue witness(UniValue::VARR);
159  for (unsigned int i = 0; i < txin.scriptWitness.stack.size(); i++) {
160  witness.push_back(HexStr(txin.scriptWitness.stack[i]));
161  }
162  entry.pushKV("witness", witness);
163  entry.pushKV("scriptSig", HexStr(txin.scriptSig));
164  entry.pushKV("sequence", (uint64_t)txin.nSequence);
165  entry.pushKV("error", strMessage);
166  vErrorsRet.push_back(entry);
167 }
168 
169 void ParsePrevouts(const UniValue& prevTxsUnival, FillableSigningProvider* keystore, std::map<COutPoint, Coin>& coins)
170 {
171  if (!prevTxsUnival.isNull()) {
172  const UniValue& prevTxs = prevTxsUnival.get_array();
173  for (unsigned int idx = 0; idx < prevTxs.size(); ++idx) {
174  const UniValue& p = prevTxs[idx];
175  if (!p.isObject()) {
176  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
177  }
178 
179  const UniValue& prevOut = p.get_obj();
180 
181  RPCTypeCheckObj(prevOut,
182  {
183  {"txid", UniValueType(UniValue::VSTR)},
184  {"vout", UniValueType(UniValue::VNUM)},
185  {"scriptPubKey", UniValueType(UniValue::VSTR)},
186  });
187 
188  uint256 txid = ParseHashO(prevOut, "txid");
189 
190  int nOut = prevOut.find_value("vout").getInt<int>();
191  if (nOut < 0) {
192  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout cannot be negative");
193  }
194 
195  COutPoint out(txid, nOut);
196  std::vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
197  CScript scriptPubKey(pkData.begin(), pkData.end());
198 
199  {
200  auto coin = coins.find(out);
201  if (coin != coins.end() && !coin->second.IsSpent() && coin->second.out.scriptPubKey != scriptPubKey) {
202  std::string err("Previous output scriptPubKey mismatch:\n");
203  err = err + ScriptToAsmStr(coin->second.out.scriptPubKey) + "\nvs:\n"+
204  ScriptToAsmStr(scriptPubKey);
206  }
207  Coin newcoin;
208  newcoin.out.scriptPubKey = scriptPubKey;
209  newcoin.out.nValue = MAX_MONEY;
210  if (prevOut.exists("amount")) {
211  newcoin.out.nValue = AmountFromValue(prevOut.find_value("amount"));
212  }
213  newcoin.nHeight = 1;
214  coins[out] = std::move(newcoin);
215  }
216 
217  // if redeemScript and private keys were given, add redeemScript to the keystore so it can be signed
218  const bool is_p2sh = scriptPubKey.IsPayToScriptHash();
219  const bool is_p2wsh = scriptPubKey.IsPayToWitnessScriptHash();
220  if (keystore && (is_p2sh || is_p2wsh)) {
221  RPCTypeCheckObj(prevOut,
222  {
223  {"redeemScript", UniValueType(UniValue::VSTR)},
224  {"witnessScript", UniValueType(UniValue::VSTR)},
225  }, true);
226  const UniValue& rs{prevOut.find_value("redeemScript")};
227  const UniValue& ws{prevOut.find_value("witnessScript")};
228  if (rs.isNull() && ws.isNull()) {
229  throw JSONRPCError(RPC_INVALID_PARAMETER, "Missing redeemScript/witnessScript");
230  }
231 
232  // work from witnessScript when possible
233  std::vector<unsigned char> scriptData(!ws.isNull() ? ParseHexV(ws, "witnessScript") : ParseHexV(rs, "redeemScript"));
234  CScript script(scriptData.begin(), scriptData.end());
235  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  CScript witness_output_script{GetScriptForDestination(WitnessV0ScriptHash(script))};
239  keystore->AddCScript(witness_output_script);
240 
241  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  if (ws.get_str() != rs.get_str()) {
247  std::vector<unsigned char> redeemScriptData(ParseHexV(rs, "redeemScript"));
248  CScript redeemScript(redeemScriptData.begin(), redeemScriptData.end());
249  if (redeemScript != witness_output_script) {
250  throw JSONRPCError(RPC_INVALID_PARAMETER, "redeemScript does not correspond to witnessScript");
251  }
252  }
253  }
254 
255  if (is_p2sh) {
256  const CTxDestination p2sh{ScriptHash(script)};
257  const CTxDestination p2sh_p2wsh{ScriptHash(witness_output_script)};
258  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  } 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  } else {
271  // otherwise, can't generate scriptPubKey from
272  // either script, so we got unusable parameters
273  throw JSONRPCError(RPC_INVALID_PARAMETER, "redeemScript/witnessScript does not match scriptPubKey");
274  }
275  } 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  const CTxDestination p2wsh{WitnessV0ScriptHash(script)};
281  if (scriptPubKey != GetScriptForDestination(p2wsh)) {
282  throw JSONRPCError(RPC_INVALID_PARAMETER, "redeemScript/witnessScript does not match scriptPubKey");
283  }
284  }
285  }
286  }
287  }
288 }
289 
290 void SignTransaction(CMutableTransaction& mtx, const SigningProvider* keystore, const std::map<COutPoint, Coin>& coins, const UniValue& hashType, UniValue& result)
291 {
292  int nHashType = ParseSighashString(hashType);
293 
294  // Script verification errors
295  std::map<int, bilingual_str> input_errors;
296 
297  bool complete = SignTransaction(mtx, keystore, coins, nHashType, input_errors);
298  SignTransactionResultToJSON(mtx, complete, coins, input_errors, result);
299 }
300 
301 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  UniValue vErrors(UniValue::VARR);
305  for (const auto& err_pair : input_errors) {
306  if (err_pair.second.original == "Missing amount") {
307  // This particular error needs to be an exception for some reason
308  throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing amount for %s", coins.at(mtx.vin.at(err_pair.first).prevout).out.ToString()));
309  }
310  TxInErrorToJSON(mtx.vin.at(err_pair.first), vErrors, err_pair.second.original);
311  }
312 
313  result.pushKV("hex", EncodeHexTx(CTransaction(mtx)));
314  result.pushKV("complete", complete);
315  if (!vErrors.empty()) {
316  if (result.exists("errors")) {
317  vErrors.push_backV(result["errors"].getValues());
318  }
319  result.pushKV("errors", vErrors);
320  }
321 }
CAmount nValue
Definition: transaction.h:160
void AddInputs(CMutableTransaction &rawTx, const UniValue &inputs_in, std::optional< bool > rbf)
bool isObject() const
Definition: univalue.h:85
void push_back(UniValue val)
Definition: univalue.cpp:104
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.
CScript scriptPubKey
Definition: transaction.h:161
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull, bool fStrict)
Definition: util.cpp:38
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination corresponds to one with an address.
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.
A UTXO entry.
Definition: coins.h:31
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1162
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string strName)
Definition: util.cpp:90
void pushKVs(UniValue obj)
Definition: univalue.cpp:137
std::vector< CTxIn > vin
Definition: transaction.h:381
CScriptWitness scriptWitness
Only serialized through CTransaction.
Definition: transaction.h:80
static const uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime/IsFinalTx().
Definition: transaction.h:89
virtual bool AddCScript(const CScript &redeemScript)
int ParseSighashString(const UniValue &sighash)
Returns a sighash value corresponding to the passed in argument.
Definition: util.cpp:327
CTxOut out
unspent transaction output
Definition: coins.h:35
std::vector< std::vector< unsigned char > > stack
Definition: script.h:568
bool isNum() const
Definition: univalue.h:83
const UniValue & get_array() const
const std::vector< std::string > & getKeys() const
Int getInt() const
Definition: univalue.h:137
bool SignalsOptInRBF(const CTransaction &tx)
Check whether the sequence numbers on this transaction are signaling opt-in to replace-by-fee, according to BIP 125.
Definition: rbf.cpp:9
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 AddOutputs(CMutableTransaction &rawTx, const UniValue &outputs_in)
Normalize univalue-represented outputs and add them to the transaction.
void SignTransactionResultToJSON(CMutableTransaction &mtx, bool complete, const std::map< COutPoint, Coin > &coins, const std::map< int, bilingual_str > &input_errors, UniValue &result)
Invalid, missing or duplicate parameter.
Definition: protocol.h:43
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
const UniValue & find_value(std::string_view key) const
Definition: univalue.cpp:233
uint32_t nHeight
at which height this containing transaction was included in the active block chain ...
Definition: coins.h:41
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: util.cpp:86
static constexpr uint32_t MAX_BIP125_RBF_SEQUENCE
Definition: rbf.h:12
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:58
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode=false)
Create the assembly string representation of a CScript object.
Definition: core_write.cpp:98
static CAmount AmountFromValue(const UniValue &value)
Definition: bitcoin-tx.cpp:553
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
An input of a transaction.
Definition: transaction.h:74
bool exists(const std::string &key) const
Definition: univalue.h:76
Fillable signing provider that keeps keys in an address->secret map.
uint32_t n
Definition: transaction.h:39
Unexpected type was passed as parameter.
Definition: protocol.h:40
static const uint32_t LOCKTIME_MAX
Definition: script.h:51
bool empty() const
Definition: univalue.h:68
CMutableTransaction ConstructTransaction(const UniValue &inputs_in, const UniValue &outputs_in, const UniValue &locktime, std::optional< bool > rbf)
Create a transaction from univalue parameters.
void push_backV(const std::vector< UniValue > &vec)
Definition: univalue.cpp:111
An output of a transaction.
Definition: transaction.h:157
std::string ToString() const
Definition: uint256.cpp:55
Invalid address or key.
Definition: protocol.h:41
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:35
std::vector< CTxOut > vout
Definition: transaction.h:382
bool isNull() const
Definition: univalue.h:78
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
CScript scriptSig
Definition: transaction.h:78
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
Definition: addresstype.h:129
256-bit opaque blob.
Definition: uint256.h:106
An interface to be implemented by keystores that support signing.
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:126
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:412
uint32_t nSequence
Definition: transaction.h:79
const UniValue & get_obj() const
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Definition: core_write.cpp:143
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string strKey)
Definition: util.cpp:99
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:26
A mutable version of CTransaction.
Definition: transaction.h:379
static const uint32_t MAX_SEQUENCE_NONFINAL
This is the maximum sequence number that enables both nLockTime and OP_CHECKLOCKTIMEVERIFY (BIP 65)...
Definition: transaction.h:95
size_t size() const
Definition: univalue.h:70
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:294
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
Definition: key_io.cpp:292
COutPoint prevout
Definition: transaction.h:77
Wrapper for UniValue::VType, which includes typeAny: Used to denote don&#39;t care type.
Definition: util.h:75
Error parsing or validating structure in raw format.
Definition: protocol.h:45
uint256 hash
Definition: transaction.h:38