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