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