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