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