Bitcoin ABC  0.22.13
P2P Digital Currency
rawtransaction_util.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2019 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/strencodings.h>
20 
22  const UniValue &inputs_in,
23  const UniValue &outputs_in,
24  const UniValue &locktime) {
25  if (inputs_in.isNull() || outputs_in.isNull()) {
26  throw JSONRPCError(
28  "Invalid parameter, arguments 1 and 2 must be non-null");
29  }
30 
31  UniValue inputs = inputs_in.get_array();
32  const bool outputs_is_obj = outputs_in.isObject();
33  UniValue outputs =
34  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 > std::numeric_limits<uint32_t>::max()) {
42  "Invalid parameter, locktime out of range");
43  }
44 
45  rawTx.nLockTime = nLockTime;
46  }
47 
48  for (size_t idx = 0; idx < inputs.size(); idx++) {
49  const UniValue &input = inputs[idx];
50  const UniValue &o = input.get_obj();
51 
52  TxId txid(ParseHashO(o, "txid"));
53 
54  const UniValue &vout_v = find_value(o, "vout");
55  if (vout_v.isNull()) {
57  "Invalid parameter, missing vout key");
58  }
59 
60  if (!vout_v.isNum()) {
62  "Invalid parameter, vout must be a number");
63  }
64 
65  int nOutput = vout_v.get_int();
66  if (nOutput < 0) {
68  "Invalid parameter, vout must be positive");
69  }
70 
71  uint32_t nSequence =
72  (rawTx.nLockTime ? std::numeric_limits<uint32_t>::max() - 1
73  : std::numeric_limits<uint32_t>::max());
74 
75  // Set the sequence number if passed in the parameters object.
76  const UniValue &sequenceObj = find_value(o, "sequence");
77  if (sequenceObj.isNum()) {
78  int64_t seqNr64 = sequenceObj.get_int64();
79  if (seqNr64 < 0 || seqNr64 > std::numeric_limits<uint32_t>::max()) {
80  throw JSONRPCError(
82  "Invalid parameter, sequence number is out of range");
83  }
84 
85  nSequence = uint32_t(seqNr64);
86  }
87 
88  CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
89  rawTx.vin.push_back(in);
90  }
91 
92  if (!outputs_is_obj) {
93  // Translate array of key-value pairs into dict
94  UniValue outputs_dict = UniValue(UniValue::VOBJ);
95  for (size_t i = 0; i < outputs.size(); ++i) {
96  const UniValue &output = outputs[i];
97  if (!output.isObject()) {
99  "Invalid parameter, key-value pair not an "
100  "object as expected");
101  }
102  if (output.size() != 1) {
104  "Invalid parameter, key-value pair must "
105  "contain exactly one key");
106  }
107  outputs_dict.pushKVs(output);
108  }
109  outputs = std::move(outputs_dict);
110  }
111 
112  // Duplicate checking
113  std::set<CTxDestination> destinations;
114  bool has_data{false};
115 
116  for (const std::string &name_ : outputs.getKeys()) {
117  if (name_ == "data") {
118  if (has_data) {
120  "Invalid parameter, duplicate key: data");
121  }
122  has_data = true;
123  std::vector<uint8_t> data =
124  ParseHexV(outputs[name_].getValStr(), "Data");
125 
126  CTxOut out(Amount::zero(), CScript() << OP_RETURN << data);
127  rawTx.vout.push_back(out);
128  } else {
129  CTxDestination destination = DecodeDestination(name_, params);
130  if (!IsValidDestination(destination)) {
132  std::string("Invalid Bitcoin address: ") +
133  name_);
134  }
135 
136  if (!destinations.insert(destination).second) {
137  throw JSONRPCError(
139  std::string("Invalid parameter, duplicated address: ") +
140  name_);
141  }
142 
143  CScript scriptPubKey = GetScriptForDestination(destination);
144  Amount nAmount = AmountFromValue(outputs[name_]);
145 
146  CTxOut out(nAmount, scriptPubKey);
147  rawTx.vout.push_back(out);
148  }
149  }
150 
151  return rawTx;
152 }
153 
157 static void TxInErrorToJSON(const CTxIn &txin, UniValue &vErrorsRet,
158  const std::string &strMessage) {
159  UniValue entry(UniValue::VOBJ);
160  entry.pushKV("txid", txin.prevout.GetTxId().ToString());
161  entry.pushKV("vout", uint64_t(txin.prevout.GetN()));
162  entry.pushKV("scriptSig",
163  HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
164  entry.pushKV("sequence", uint64_t(txin.nSequence));
165  entry.pushKV("error", strMessage);
166  vErrorsRet.push_back(entry);
167 }
168 
169 void ParsePrevouts(const UniValue &prevTxsUnival,
170  FillableSigningProvider *keystore,
171  std::map<COutPoint, Coin> &coins) {
172  if (!prevTxsUnival.isNull()) {
173  UniValue prevTxs = prevTxsUnival.get_array();
174  for (size_t idx = 0; idx < prevTxs.size(); ++idx) {
175  const UniValue &p = prevTxs[idx];
176  if (!p.isObject()) {
178  "expected object with "
179  "{\"txid'\",\"vout\",\"scriptPubKey\"}");
180  }
181 
182  UniValue prevOut = p.get_obj();
183 
184  RPCTypeCheckObj(prevOut,
185  {
186  {"txid", UniValueType(UniValue::VSTR)},
187  {"vout", UniValueType(UniValue::VNUM)},
188  {"scriptPubKey", UniValueType(UniValue::VSTR)},
189  // "amount" is also required but check is done
190  // below due to UniValue::VNUM erroneously
191  // not accepting quoted numerics
192  // (which are valid JSON)
193  });
194 
195  TxId txid(ParseHashO(prevOut, "txid"));
196 
197  int nOut = find_value(prevOut, "vout").get_int();
198  if (nOut < 0) {
200  "vout must be positive");
201  }
202 
203  COutPoint out(txid, nOut);
204  std::vector<uint8_t> pkData(ParseHexO(prevOut, "scriptPubKey"));
205  CScript scriptPubKey(pkData.begin(), pkData.end());
206 
207  {
208  auto coin = coins.find(out);
209  if (coin != coins.end() && !coin->second.IsSpent() &&
210  coin->second.GetTxOut().scriptPubKey != scriptPubKey) {
211  std::string err("Previous output scriptPubKey mismatch:\n");
212  err = err +
213  ScriptToAsmStr(coin->second.GetTxOut().scriptPubKey) +
214  "\nvs:\n" + ScriptToAsmStr(scriptPubKey);
216  }
217 
218  CTxOut txout;
219  txout.scriptPubKey = scriptPubKey;
220  txout.nValue = MAX_MONEY;
221  if (prevOut.exists("amount")) {
222  txout.nValue =
223  AmountFromValue(find_value(prevOut, "amount"));
224  } else {
225  // amount param is required in replay-protected txs.
226  // Note that we must check for its presence here rather
227  // than use RPCTypeCheckObj() above, since UniValue::VNUM
228  // parser incorrectly parses numerics with quotes, eg
229  // "3.12" as a string when JSON allows it to also parse
230  // as numeric. And we have to accept numerics with quotes
231  // because our own dogfood (our rpc results) always
232  // produces decimal numbers that are quoted
233  // eg getbalance returns "3.14152" rather than 3.14152
234  throw JSONRPCError(RPC_INVALID_PARAMETER, "Missing amount");
235  }
236  coins[out] = Coin(txout, 1, false);
237  }
238 
239  // If redeemScript and private keys were given, add redeemScript to
240  // the keystore so it can be signed
241  if (keystore && scriptPubKey.IsPayToScriptHash()) {
243  prevOut, {
244  {"redeemScript", UniValueType(UniValue::VSTR)},
245  });
246  UniValue v = find_value(prevOut, "redeemScript");
247  if (!v.isNull()) {
248  std::vector<uint8_t> rsData(ParseHexV(v, "redeemScript"));
249  CScript redeemScript(rsData.begin(), rsData.end());
250  keystore->AddCScript(redeemScript);
251  }
252  }
253  }
254  }
255 }
256 
258  const std::map<COutPoint, Coin> &coins,
259  const UniValue &hashType, UniValue &result) {
260  SigHashType sigHashType = ParseSighashString(hashType);
261  if (!sigHashType.hasForkId()) {
263  "Signature must use SIGHASH_FORKID");
264  }
265 
266  // Script verification errors
267  std::map<int, std::string> input_errors;
268 
269  bool complete =
270  SignTransaction(mtx, keystore, coins, sigHashType, input_errors);
271  SignTransactionResultToJSON(mtx, complete, coins, input_errors, result);
272 }
273 
275  const std::map<COutPoint, Coin> &coins,
276  std::map<int, std::string> &input_errors,
277  UniValue &result) {
278  // Make errors UniValue
279  UniValue vErrors(UniValue::VARR);
280  for (const auto &err_pair : input_errors) {
281  if (err_pair.second == "Missing amount") {
282  // This particular error needs to be an exception for some reason
283  throw JSONRPCError(
285  strprintf("Missing amount for %s",
286  coins.at(mtx.vin.at(err_pair.first).prevout)
287  .GetTxOut()
288  .ToString()));
289  }
290  TxInErrorToJSON(mtx.vin.at(err_pair.first), vErrors, err_pair.second);
291  }
292 
293  result.pushKV("hex", EncodeHexTx(CTransaction(mtx)));
294  result.pushKV("complete", complete);
295  if (!vErrors.empty()) {
296  if (result.exists("errors")) {
297  vErrors.push_backV(result["errors"].getValues());
298  }
299  result.pushKV("errors", vErrors);
300  }
301 }
uint32_t GetN() const
Definition: transaction.h:44
bool isObject() const
Definition: univalue.h:96
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.
std::vector< uint8_t > ParseHexO(const UniValue &o, std::string strKey)
Definition: util.cpp:134
static constexpr Amount zero()
Definition: amount.h:35
bool hasForkId() const
Definition: sighashtype.h:77
CScript scriptPubKey
Definition: transaction.h:144
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull, bool fStrict)
Check for expected keys/value types in an Object.
Definition: util.cpp:52
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.
static Amount AmountFromValue(const UniValue &value)
Definition: bitcoin-tx.cpp:562
A UTXO entry.
Definition: coins.h:27
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
virtual bool AddCScript(const CScript &redeemScript)
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:269
Definition: amount.h:17
const TxId & GetTxId() const
Definition: transaction.h:43
static const Amount MAX_MONEY
No amount larger than this (in satoshi) is valid.
Definition: amount.h:165
bool isNum() const
Definition: univalue.h:94
const UniValue & get_array() const
std::vector< CTxOut > vout
Definition: transaction.h:298
CChainParams defines various tweakable parameters of a given instance of the Bitcoin system...
Definition: chainparams.h:47
SigHashType ParseSighashString(const UniValue &sighash)
Definition: core_read.cpp:265
int64_t get_int64() const
std::vector< uint8_t > ParseHexV(const UniValue &v, std::string strName)
Definition: util.cpp:120
bool pushKVs(const UniValue &obj)
Definition: univalue.cpp:146
const std::vector< std::string > & getKeys() const
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:46
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)
std::vector< CTxIn > vin
Definition: transaction.h:297
CMutableTransaction ConstructTransaction(const CChainParams &params, const UniValue &inputs_in, const UniValue &outputs_in, const UniValue &locktime)
Create a transaction from univalue parameters.
iterator end()
Definition: prevector.h:390
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: util.cpp:116
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:52
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:107
An input of a transaction.
Definition: transaction.h:67
bool exists(const std::string &key) const
Definition: univalue.h:87
Fillable signing provider that keeps keys in an address->secret map.
Unexpected type was passed as parameter.
Definition: protocol.h:40
bool empty() const
Definition: univalue.h:78
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
CTxDestination DecodeDestination(const std::string &addr, const CChainParams &params)
Definition: key_io.cpp:177
An output of a transaction.
Definition: transaction.h:141
int get_int() const
std::string ToString() const
Definition: uint256.h:74
Invalid address or key.
Definition: protocol.h:42
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:246
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:22
bool isNull() const
Definition: univalue.h:89
CScript scriptSig
Definition: transaction.h:70
An interface to be implemented by keystores that support signing.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:430
uint32_t nSequence
Definition: transaction.h:71
A TxId is the identifier of a transaction.
Definition: txid.h:14
const UniValue & get_obj() const
bool push_backV(const std::vector< UniValue > &vec)
Definition: univalue.cpp:117
A mutable version of CTransaction.
Definition: transaction.h:295
std::string HexStr(const T itbegin, const T itend)
Definition: strencodings.h:132
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Definition: core_write.cpp:172
iterator begin()
Definition: prevector.h:388
size_t size() const
Definition: univalue.h:80
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:211
COutPoint prevout
Definition: transaction.h:69
Amount nValue
Definition: transaction.h:143
Wrapper for UniValue::VType, which includes typeAny: used to denote don&#39;t care type.
Definition: util.h:45
boost::variant< CNoDestination, PKHash, ScriptHash > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:87
Error parsing or validating structure in raw format.
Definition: protocol.h:50
Signature hash type wrapper class.
Definition: sighashtype.h:37