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