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