Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

rawtransaction.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 The Bitcoin Core developers
3 // Copyright (c) 2014-2019 The Dash Core developers
4 // Distributed under the MIT software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 #include <base58.h>
8 #include <chain.h>
9 #include <coins.h>
10 #include <consensus/validation.h>
11 #include <core_io.h>
12 #include <init.h>
13 #include <keystore.h>
14 #include <validation.h>
15 #include <validationinterface.h>
16 #include <merkleblock.h>
17 #include <net.h>
18 #include <policy/policy.h>
19 #include <primitives/transaction.h>
20 #include <rpc/safemode.h>
21 #include <rpc/server.h>
22 #include <script/script.h>
23 #include <script/script_error.h>
24 #include <script/sign.h>
25 #include <script/standard.h>
26 #include <txmempool.h>
27 #include <uint256.h>
28 #include <utilstrencodings.h>
29 #ifdef ENABLE_WALLET
30 #include <wallet/rpcwallet.h>
31 #include <wallet/wallet.h>
32 #endif
33 
34 #include <evo/specialtx.h>
35 #include <evo/providertx.h>
36 #include <evo/cbtx.h>
37 
41 
42 #include <future>
43 #include <stdint.h>
44 
45 #include <univalue.h>
46 
47 
48 void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry)
49 {
50  // Call into TxToUniv() in bitcoin-common to decode the transaction hex.
51  //
52  // Blockchain contextual information (confirmations and blocktime) is not
53  // available to code in bitcoin-common, so we query them here and push the
54  // data into the returned UniValue.
55 
56  uint256 txid = tx.GetHash();
57 
58  // Add spent information if spentindex is enabled
59  CSpentIndexTxInfo txSpentInfo;
60  for (const auto& txin : tx.vin) {
61  if (!tx.IsCoinBase()) {
62  CSpentIndexValue spentInfo;
63  CSpentIndexKey spentKey(txin.prevout.hash, txin.prevout.n);
64  if (GetSpentIndex(spentKey, spentInfo)) {
65  txSpentInfo.mSpentInfo.emplace(spentKey, spentInfo);
66  }
67  }
68  }
69  for (unsigned int i = 0; i < tx.vout.size(); i++) {
70  CSpentIndexValue spentInfo;
71  CSpentIndexKey spentKey(txid, i);
72  if (GetSpentIndex(spentKey, spentInfo)) {
73  txSpentInfo.mSpentInfo.emplace(spentKey, spentInfo);
74  }
75  }
76 
77  TxToUniv(tx, uint256(), entry, true, &txSpentInfo);
78 
79  bool chainLock = false;
80  if (!hashBlock.IsNull()) {
81  entry.push_back(Pair("blockhash", hashBlock.GetHex()));
82  BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
83  if (mi != mapBlockIndex.end() && (*mi).second) {
84  CBlockIndex* pindex = (*mi).second;
85  if (chainActive.Contains(pindex)) {
86  entry.push_back(Pair("height", pindex->nHeight));
87  entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
88  entry.push_back(Pair("time", pindex->GetBlockTime()));
89  entry.push_back(Pair("blocktime", pindex->GetBlockTime()));
90 
91  chainLock = llmq::chainLocksHandler->HasChainLock(pindex->nHeight, pindex->GetBlockHash());
92  } else {
93  entry.push_back(Pair("height", -1));
94  entry.push_back(Pair("confirmations", 0));
95  }
96  }
97  }
98 
99  bool fLocked = llmq::quorumInstantSendManager->IsLocked(txid);
100  entry.push_back(Pair("instantlock", fLocked || chainLock));
101  entry.push_back(Pair("instantlock_internal", fLocked));
102  entry.push_back(Pair("chainlock", chainLock));
103 }
104 
106 {
107  if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)
108  throw std::runtime_error(
109  "getrawtransaction \"txid\" ( verbose \"blockhash\" )\n"
110 
111  "\nNOTE: By default this function only works for mempool transactions. If the -txindex option is\n"
112  "enabled, it also works for blockchain transactions. If the block which contains the transaction\n"
113  "is known, its hash can be provided even for nodes without -txindex. Note that if a blockhash is\n"
114  "provided, only that block will be searched and if the transaction is in the mempool or other\n"
115  "blocks, or if this node does not have the given block available, the transaction will not be found.\n"
116  "DEPRECATED: for now, it also works for transactions with unspent outputs.\n"
117 
118  "\nReturn the raw transaction data.\n"
119  "\nIf verbose is 'true', returns an Object with information about 'txid'.\n"
120  "If verbose is 'false' or omitted, returns a string that is serialized, hex-encoded data for 'txid'.\n"
121 
122  "\nArguments:\n"
123  "1. \"txid\" (string, required) The transaction id\n"
124  "2. verbose (bool, optional, default=false) If false, return a string, otherwise return a json object\n"
125  "3. \"blockhash\" (string, optional) The block in which to look for the transaction\n"
126 
127  "\nResult (if verbose is not set or set to false):\n"
128  "\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
129 
130  "\nResult (if verbose is set to true):\n"
131  "{\n"
132  " \"in_active_chain\": b, (bool) Whether specified block is in the active chain or not (only present with explicit \"blockhash\" argument)\n"
133  " \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
134  " \"size\" : n, (numeric) The transaction size\n"
135  " \"version\" : n, (numeric) The version\n"
136  " \"locktime\" : ttt, (numeric) The lock time\n"
137  " \"vin\" : [ (array of json objects)\n"
138  " {\n"
139  " \"txid\": \"id\", (string) The transaction id\n"
140  " \"vout\": n, (numeric) \n"
141  " \"scriptSig\": { (json object) The script\n"
142  " \"asm\": \"asm\", (string) asm\n"
143  " \"hex\": \"hex\" (string) hex\n"
144  " },\n"
145  " \"sequence\": n (numeric) The script sequence number\n"
146  " }\n"
147  " ,...\n"
148  " ],\n"
149  " \"vout\" : [ (array of json objects)\n"
150  " {\n"
151  " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
152  " \"n\" : n, (numeric) index\n"
153  " \"scriptPubKey\" : { (json object)\n"
154  " \"asm\" : \"asm\", (string) the asm\n"
155  " \"hex\" : \"hex\", (string) the hex\n"
156  " \"reqSigs\" : n, (numeric) The required sigs\n"
157  " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
158  " \"addresses\" : [ (json array of string)\n"
159  " \"address\" (string) dash address\n"
160  " ,...\n"
161  " ]\n"
162  " }\n"
163  " }\n"
164  " ,...\n"
165  " ],\n"
166  " \"extraPayloadSize\" : n (numeric) Size of DIP2 extra payload. Only present if it's a special TX\n"
167  " \"extraPayload\" : \"hex\" (string) Hex encoded DIP2 extra payload data. Only present if it's a special TX\n"
168  " \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
169  " \"blockhash\" : \"hash\", (string) the block hash\n"
170  " \"height\" : n, (numeric) The block height\n"
171  " \"confirmations\" : n, (numeric) The confirmations\n"
172  " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
173  " \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
174  " \"instantlock\" : true|false, (bool) Current transaction lock state\n"
175  " \"instantlock_internal\" : true|false, (bool) Current internal transaction lock state\n"
176  " \"chainlock\" : true|false, (bool) The state of the corresponding block chainlock\n"
177  "}\n"
178 
179  "\nExamples:\n"
180  + HelpExampleCli("getrawtransaction", "\"mytxid\"")
181  + HelpExampleCli("getrawtransaction", "\"mytxid\" true")
182  + HelpExampleRpc("getrawtransaction", "\"mytxid\", true")
183  + HelpExampleCli("getrawtransaction", "\"mytxid\" false \"myblockhash\"")
184  + HelpExampleCli("getrawtransaction", "\"mytxid\" true \"myblockhash\"")
185  );
186 
187  LOCK(cs_main);
188 
189  bool in_active_chain = true;
190  uint256 hash = ParseHashV(request.params[0], "parameter 1");
191  CBlockIndex* blockindex = nullptr;
192 
193  if (hash == Params().GenesisBlock().hashMerkleRoot) {
194  // Special exception for the genesis block coinbase transaction
195  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "The genesis block coinbase is not considered an ordinary transaction and cannot be retrieved");
196  }
197 
198  // Accept either a bool (true) or a num (>=1) to indicate verbose output.
199  bool fVerbose = false;
200  if (!request.params[1].isNull()) {
201  fVerbose = request.params[1].isNum() ? (request.params[1].get_int() != 0) : request.params[1].get_bool();
202  }
203 
204  if (!request.params[2].isNull()) {
205  uint256 blockhash = ParseHashV(request.params[2], "parameter 3");
206  BlockMap::iterator it = mapBlockIndex.find(blockhash);
207  if (it == mapBlockIndex.end()) {
208  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block hash not found");
209  }
210  blockindex = it->second;
211  in_active_chain = chainActive.Contains(blockindex);
212  }
213 
214  CTransactionRef tx;
215  uint256 hash_block;
216  if (!GetTransaction(hash, tx, Params().GetConsensus(), hash_block, true, blockindex)) {
217  std::string errmsg;
218  if (blockindex) {
219  if (!(blockindex->nStatus & BLOCK_HAVE_DATA)) {
220  throw JSONRPCError(RPC_MISC_ERROR, "Block not available");
221  }
222  errmsg = "No such transaction found in the provided block";
223  } else {
224  errmsg = fTxIndex
225  ? "No such mempool or blockchain transaction"
226  : "No such mempool transaction. Use -txindex to enable blockchain transaction queries";
227  }
228  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, errmsg + ". Use gettransaction for wallet transactions.");
229  }
230 
231  if (!fVerbose) {
232  return EncodeHexTx(*tx);
233  }
234 
235  UniValue result(UniValue::VOBJ);
236  if (blockindex) result.push_back(Pair("in_active_chain", in_active_chain));
237  TxToJSON(*tx, hash_block, result);
238  return result;
239 }
240 
242 {
243  if (request.fHelp || (request.params.size() != 1 && request.params.size() != 2))
244  throw std::runtime_error(
245  "gettxoutproof [\"txid\",...] ( blockhash )\n"
246  "\nReturns a hex-encoded proof that \"txid\" was included in a block.\n"
247  "\nNOTE: By default this function only works sometimes. This is when there is an\n"
248  "unspent output in the utxo for this transaction. To make it always work,\n"
249  "you need to maintain a transaction index, using the -txindex command line option or\n"
250  "specify the block in which the transaction is included manually (by blockhash).\n"
251  "\nArguments:\n"
252  "1. \"txids\" (string) A json array of txids to filter\n"
253  " [\n"
254  " \"txid\" (string) A transaction hash\n"
255  " ,...\n"
256  " ]\n"
257  "2. \"blockhash\" (string, optional) If specified, looks for txid in the block with this hash\n"
258  "\nResult:\n"
259  "\"data\" (string) A string that is a serialized, hex-encoded data for the proof.\n"
260 
261  "\nExamples:\n"
262  + HelpExampleCli("gettxoutproof", "'[\"mytxid\",...]'")
263  + HelpExampleCli("gettxoutproof", "'[\"mytxid\",...]' \"blockhash\"")
264  + HelpExampleRpc("gettxoutproof", "[\"mytxid\",...], \"blockhash\"")
265  );
266 
267  std::set<uint256> setTxids;
268  uint256 oneTxid;
269  UniValue txids = request.params[0].get_array();
270  for (unsigned int idx = 0; idx < txids.size(); idx++) {
271  const UniValue& txid = txids[idx];
272  if (txid.get_str().length() != 64 || !IsHex(txid.get_str()))
273  throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid txid ")+txid.get_str());
274  uint256 hash(uint256S(txid.get_str()));
275  if (setTxids.count(hash))
276  throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated txid: ")+txid.get_str());
277  setTxids.insert(hash);
278  oneTxid = hash;
279  }
280 
281  LOCK(cs_main);
282 
283  CBlockIndex* pblockindex = nullptr;
284 
285  uint256 hashBlock;
286  if (!request.params[1].isNull())
287  {
288  hashBlock = uint256S(request.params[1].get_str());
289  if (!mapBlockIndex.count(hashBlock))
290  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
291  pblockindex = mapBlockIndex[hashBlock];
292  } else {
293  // Loop through txids and try to find which block they're in. Exit loop once a block is found.
294  for (const auto& tx : setTxids) {
295  const Coin& coin = AccessByTxid(*pcoinsTip, tx);
296  if (!coin.IsSpent()) {
297  pblockindex = chainActive[coin.nHeight];
298  break;
299  }
300  }
301  }
302 
303  if (pblockindex == nullptr)
304  {
305  CTransactionRef tx;
306  if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, false) || hashBlock.IsNull())
307  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block");
308  if (!mapBlockIndex.count(hashBlock))
309  throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt");
310  pblockindex = mapBlockIndex[hashBlock];
311  }
312 
313  CBlock block;
314  if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
315  throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
316 
317  unsigned int ntxFound = 0;
318  for (const auto& tx : block.vtx)
319  if (setTxids.count(tx->GetHash()))
320  ntxFound++;
321  if (ntxFound != setTxids.size())
322  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Not all transactions found in specified or retrieved block");
323 
325  CMerkleBlock mb(block, setTxids);
326  ssMB << mb;
327  std::string strHex = HexStr(ssMB.begin(), ssMB.end());
328  return strHex;
329 }
330 
332 {
333  if (request.fHelp || request.params.size() != 1)
334  throw std::runtime_error(
335  "verifytxoutproof \"proof\"\n"
336  "\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n"
337  "and throwing an RPC error if the block is not in our best chain\n"
338  "\nArguments:\n"
339  "1. \"proof\" (string, required) The hex-encoded proof generated by gettxoutproof\n"
340  "\nResult:\n"
341  "[\"txid\"] (array, strings) The txid(s) which the proof commits to, or empty array if the proof is invalid\n"
342 
343  "\nExamples:\n"
344  + HelpExampleCli("verifytxoutproof", "\"proof\"")
345  + HelpExampleRpc("gettxoutproof", "\"proof\"")
346  );
347 
348  CDataStream ssMB(ParseHexV(request.params[0], "proof"), SER_NETWORK, PROTOCOL_VERSION);
349  CMerkleBlock merkleBlock;
350  ssMB >> merkleBlock;
351 
353 
354  std::vector<uint256> vMatch;
355  std::vector<unsigned int> vIndex;
356  if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot)
357  return res;
358 
359  LOCK(cs_main);
360 
361  if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
362  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
363 
364  for (const uint256& hash : vMatch)
365  res.push_back(hash.GetHex());
366  return res;
367 }
368 
370 {
371  if (request.fHelp || request.params.size() < 2 || request.params.size() > 3)
372  throw std::runtime_error(
373  "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,\"data\":\"hex\",...} ( locktime )\n"
374  "\nCreate a transaction spending the given inputs and creating new outputs.\n"
375  "Outputs can be addresses or data.\n"
376  "Returns hex-encoded raw transaction.\n"
377  "Note that the transaction's inputs are not signed, and\n"
378  "it is not stored in the wallet or transmitted to the network.\n"
379 
380  "\nArguments:\n"
381  "1. \"inputs\" (array, required) A json array of json objects\n"
382  " [\n"
383  " {\n"
384  " \"txid\":\"id\", (string, required) The transaction id\n"
385  " \"vout\":n, (numeric, required) The output number\n"
386  " \"sequence\":n (numeric, optional) The sequence number\n"
387  " } \n"
388  " ,...\n"
389  " ]\n"
390  "2. \"outputs\" (object, required) a json object with outputs\n"
391  " {\n"
392  " \"address\": x.xxx, (numeric or string, required) The key is the dash address, the numeric value (can be string) is the " + CURRENCY_UNIT + " amount\n"
393  " \"data\": \"hex\" (string, required) The key is \"data\", the value is hex encoded data\n"
394  " ,...\n"
395  " }\n"
396  "3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n"
397  "\nResult:\n"
398  "\"transaction\" (string) hex string of the transaction\n"
399 
400  "\nExamples:\n"
401  + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"")
402  + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"data\\\":\\\"00010203\\\"}\"")
403  + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")
404  + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"data\\\":\\\"00010203\\\"}\"")
405  );
406 
407  RPCTypeCheck(request.params, {UniValue::VARR, UniValue::VOBJ, UniValue::VNUM, UniValue::VBOOL}, true);
408  if (request.params[0].isNull() || request.params[1].isNull())
409  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null");
410 
411  UniValue inputs = request.params[0].get_array();
412  UniValue sendTo = request.params[1].get_obj();
413 
414  CMutableTransaction rawTx;
415 
416  if (!request.params[2].isNull()) {
417  int64_t nLockTime = request.params[2].get_int64();
418  if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max())
419  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");
420  rawTx.nLockTime = nLockTime;
421  }
422 
423  for (unsigned int idx = 0; idx < inputs.size(); idx++) {
424  const UniValue& input = inputs[idx];
425  const UniValue& o = input.get_obj();
426 
427  uint256 txid = ParseHashO(o, "txid");
428 
429  const UniValue& vout_v = find_value(o, "vout");
430  if (!vout_v.isNum())
431  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
432  int nOutput = vout_v.get_int();
433  if (nOutput < 0)
434  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
435 
436  uint32_t nSequence = (rawTx.nLockTime ? std::numeric_limits<uint32_t>::max() - 1 : std::numeric_limits<uint32_t>::max());
437 
438  // set the sequence number if passed in the parameters object
439  const UniValue& sequenceObj = find_value(o, "sequence");
440  if (sequenceObj.isNum()) {
441  int64_t seqNr64 = sequenceObj.get_int64();
442  if (seqNr64 < 0 || seqNr64 > std::numeric_limits<uint32_t>::max())
443  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range");
444  else
445  nSequence = (uint32_t)seqNr64;
446  }
447 
448  CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
449 
450  rawTx.vin.push_back(in);
451  }
452 
453  std::set<CTxDestination> destinations;
454  std::vector<std::string> addrList = sendTo.getKeys();
455  for (const std::string& name_ : addrList) {
456 
457  if (name_ == "data") {
458  std::vector<unsigned char> data = ParseHexV(sendTo[name_].getValStr(),"Data");
459 
460  CTxOut out(0, CScript() << OP_RETURN << data);
461  rawTx.vout.push_back(out);
462  } else {
463  CTxDestination destination = DecodeDestination(name_);
464  if (!IsValidDestination(destination)) {
465  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Dash address: ") + name_);
466  }
467 
468  if (!destinations.insert(destination).second) {
469  throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + name_);
470  }
471 
472  CScript scriptPubKey = GetScriptForDestination(destination);
473  CAmount nAmount = AmountFromValue(sendTo[name_]);
474 
475  CTxOut out(nAmount, scriptPubKey);
476  rawTx.vout.push_back(out);
477  }
478  }
479 
480  return EncodeHexTx(rawTx);
481 }
482 
484 {
485  if (request.fHelp || request.params.size() != 1)
486  throw std::runtime_error(
487  "decoderawtransaction \"hexstring\"\n"
488  "\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
489 
490  "\nArguments:\n"
491  "1. \"hexstring\" (string, required) The transaction hex string\n"
492 
493  "\nResult:\n"
494  "{\n"
495  " \"txid\" : \"id\", (string) The transaction id\n"
496  " \"size\" : n, (numeric) The transaction size\n"
497  " \"version\" : n, (numeric) The version\n"
498  " \"type\" : n, (numeric) The type\n"
499  " \"locktime\" : ttt, (numeric) The lock time\n"
500  " \"vin\" : [ (array of json objects)\n"
501  " {\n"
502  " \"txid\": \"id\", (string) The transaction id\n"
503  " \"vout\": n, (numeric) The output number\n"
504  " \"scriptSig\": { (json object) The script\n"
505  " \"asm\": \"asm\", (string) asm\n"
506  " \"hex\": \"hex\" (string) hex\n"
507  " },\n"
508  " \"sequence\": n (numeric) The script sequence number\n"
509  " }\n"
510  " ,...\n"
511  " ],\n"
512  " \"vout\" : [ (array of json objects)\n"
513  " {\n"
514  " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
515  " \"n\" : n, (numeric) index\n"
516  " \"scriptPubKey\" : { (json object)\n"
517  " \"asm\" : \"asm\", (string) the asm\n"
518  " \"hex\" : \"hex\", (string) the hex\n"
519  " \"reqSigs\" : n, (numeric) The required sigs\n"
520  " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
521  " \"addresses\" : [ (json array of string)\n"
522  " \"XwnLY9Tf7Zsef8gMGL2fhWA9ZmMjt4KPwG\" (string) Dash address\n"
523  " ,...\n"
524  " ]\n"
525  " }\n"
526  " }\n"
527  " ,...\n"
528  " ],\n"
529  " \"extraPayloadSize\" : n (numeric) Size of DIP2 extra payload. Only present if it's a special TX\n"
530  " \"extraPayload\" : \"hex\" (string) Hex encoded DIP2 extra payload data. Only present if it's a special TX\n"
531  "}\n"
532 
533  "\nExamples:\n"
534  + HelpExampleCli("decoderawtransaction", "\"hexstring\"")
535  + HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
536  );
537 
538  LOCK(cs_main);
539  RPCTypeCheck(request.params, {UniValue::VSTR});
540 
542 
543  if (!DecodeHexTx(mtx, request.params[0].get_str()))
544  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
545 
546  UniValue result(UniValue::VOBJ);
547  TxToUniv(CTransaction(std::move(mtx)), uint256(), result, false);
548 
549  return result;
550 }
551 
553 {
554  if (request.fHelp || request.params.size() != 1)
555  throw std::runtime_error(
556  "decodescript \"hexstring\"\n"
557  "\nDecode a hex-encoded script.\n"
558  "\nArguments:\n"
559  "1. \"hexstring\" (string) the hex encoded script\n"
560  "\nResult:\n"
561  "{\n"
562  " \"asm\":\"asm\", (string) Script public key\n"
563  " \"hex\":\"hex\", (string) hex encoded public key\n"
564  " \"type\":\"type\", (string) The output type\n"
565  " \"reqSigs\": n, (numeric) The required signatures\n"
566  " \"addresses\": [ (json array of string)\n"
567  " \"address\" (string) dash address\n"
568  " ,...\n"
569  " ],\n"
570  " \"p2sh\",\"address\" (string) address of P2SH script wrapping this redeem script (not returned if the script is already a P2SH).\n"
571  "}\n"
572  "\nExamples:\n"
573  + HelpExampleCli("decodescript", "\"hexstring\"")
574  + HelpExampleRpc("decodescript", "\"hexstring\"")
575  );
576 
577  RPCTypeCheck(request.params, {UniValue::VSTR});
578 
580  CScript script;
581  if (request.params[0].get_str().size() > 0){
582  std::vector<unsigned char> scriptData(ParseHexV(request.params[0], "argument"));
583  script = CScript(scriptData.begin(), scriptData.end());
584  } else {
585  // Empty scripts are valid
586  }
587  ScriptPubKeyToUniv(script, r, false);
588 
589  UniValue type;
590 
591  type = find_value(r, "type");
592 
593  if (type.isStr() && type.get_str() != "scripthash") {
594  // P2SH cannot be wrapped in a P2SH. If this script is already a P2SH,
595  // don't return the address for a P2SH of the P2SH.
596  r.push_back(Pair("p2sh", EncodeDestination(CScriptID(script))));
597  }
598 
599  return r;
600 }
601 
603 static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)
604 {
605  UniValue entry(UniValue::VOBJ);
606  entry.push_back(Pair("txid", txin.prevout.hash.ToString()));
607  entry.push_back(Pair("vout", (uint64_t)txin.prevout.n));
608  entry.push_back(Pair("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
609  entry.push_back(Pair("sequence", (uint64_t)txin.nSequence));
610  entry.push_back(Pair("error", strMessage));
611  vErrorsRet.push_back(entry);
612 }
613 
615 {
616 
617  if (request.fHelp || request.params.size() != 1)
618  throw std::runtime_error(
619  "combinerawtransaction [\"hexstring\",...]\n"
620  "\nCombine multiple partially signed transactions into one transaction.\n"
621  "The combined transaction may be another partially signed transaction or a \n"
622  "fully signed transaction."
623 
624  "\nArguments:\n"
625  "1. \"txs\" (string) A json array of hex strings of partially signed transactions\n"
626  " [\n"
627  " \"hexstring\" (string) A transaction hash\n"
628  " ,...\n"
629  " ]\n"
630 
631  "\nResult:\n"
632  "\"hex\" (string) The hex-encoded raw transaction with signature(s)\n"
633 
634  "\nExamples:\n"
635  + HelpExampleCli("combinerawtransaction", "'[\"myhex1\", \"myhex2\", \"myhex3\"]'")
636  );
637 
638 
639  UniValue txs = request.params[0].get_array();
640  std::vector<CMutableTransaction> txVariants(txs.size());
641 
642  for (unsigned int idx = 0; idx < txs.size(); idx++) {
643  if (!DecodeHexTx(txVariants[idx], txs[idx].get_str())) {
644  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed for tx %d", idx));
645  }
646  }
647 
648  if (txVariants.empty()) {
649  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transactions");
650  }
651 
652  // mergedTx will end up with all the signatures; it
653  // starts as a clone of the rawtx:
654  CMutableTransaction mergedTx(txVariants[0]);
655 
656  // Fetch previous transactions (inputs):
657  CCoinsView viewDummy;
658  CCoinsViewCache view(&viewDummy);
659  {
660  LOCK(cs_main);
661  LOCK(mempool.cs);
662  CCoinsViewCache &viewChain = *pcoinsTip;
663  CCoinsViewMemPool viewMempool(&viewChain, mempool);
664  view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
665 
666  for (const CTxIn& txin : mergedTx.vin) {
667  view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
668  }
669 
670  view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
671  }
672 
673  // Use CTransaction for the constant parts of the
674  // transaction to avoid rehashing.
675  const CTransaction txConst(mergedTx);
676  // Sign what we can:
677  for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
678  CTxIn& txin = mergedTx.vin[i];
679  const Coin& coin = view.AccessCoin(txin.prevout);
680  if (coin.IsSpent()) {
681  throw JSONRPCError(RPC_VERIFY_ERROR, "Input not found or already spent");
682  }
683  const CScript& prevPubKey = coin.out.scriptPubKey;
684  const CAmount& amount = coin.out.nValue;
685 
686  SignatureData sigdata;
687 
688  // ... and merge in other signatures:
689  for (const CMutableTransaction& txv : txVariants) {
690  if (txv.vin.size() > i) {
691  sigdata = CombineSignatures(prevPubKey, TransactionSignatureChecker(&txConst, i, amount), sigdata, DataFromTransaction(txv, i));
692  }
693  }
694 
695  UpdateTransaction(mergedTx, i, sigdata);
696  }
697 
698  return EncodeHexTx(mergedTx);
699 }
700 
702 {
703 #ifdef ENABLE_WALLET
704  CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
705 #endif
706 
707  if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
708  throw std::runtime_error(
709  "signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
710  "\nSign inputs for raw transaction (serialized, hex-encoded).\n"
711  "The second optional argument (may be null) is an array of previous transaction outputs that\n"
712  "this transaction depends on but may not yet be in the block chain.\n"
713  "The third optional argument (may be null) is an array of base58-encoded private\n"
714  "keys that, if given, will be the only keys used to sign the transaction.\n"
715 #ifdef ENABLE_WALLET
716  + HelpRequiringPassphrase(pwallet) + "\n"
717 #endif
718 
719  "\nArguments:\n"
720  "1. \"hexstring\" (string, required) The transaction hex string\n"
721  "2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
722  " [ (json array of json objects, or 'null' if none provided)\n"
723  " {\n"
724  " \"txid\":\"id\", (string, required) The transaction id\n"
725  " \"vout\":n, (numeric, required) The output number\n"
726  " \"scriptPubKey\": \"hex\", (string, required) script key\n"
727  " \"redeemScript\": \"hex\", (string, required for P2SH) redeem script\n"
728  " \"amount\": value (numeric, required) The amount spent\n"
729  " }\n"
730  " ,...\n"
731  " ]\n"
732  "3. \"privkeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
733  " [ (json array of strings, or 'null' if none provided)\n"
734  " \"privatekey\" (string) private key in base58-encoding\n"
735  " ,...\n"
736  " ]\n"
737  "4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
738  " \"ALL\"\n"
739  " \"NONE\"\n"
740  " \"SINGLE\"\n"
741  " \"ALL|ANYONECANPAY\"\n"
742  " \"NONE|ANYONECANPAY\"\n"
743  " \"SINGLE|ANYONECANPAY\"\n"
744 
745  "\nResult:\n"
746  "{\n"
747  " \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"
748  " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
749  " \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n"
750  " {\n"
751  " \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n"
752  " \"vout\" : n, (numeric) The index of the output to spent and used as input\n"
753  " \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n"
754  " \"sequence\" : n, (numeric) Script sequence number\n"
755  " \"error\" : \"text\" (string) Verification or signing error related to the input\n"
756  " }\n"
757  " ,...\n"
758  " ]\n"
759  "}\n"
760 
761  "\nExamples:\n"
762  + HelpExampleCli("signrawtransaction", "\"myhex\"")
763  + HelpExampleRpc("signrawtransaction", "\"myhex\"")
764  );
765 
766  ObserveSafeMode();
767 
768  LOCK(cs_main);
769 
770  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR, UniValue::VARR, UniValue::VSTR}, true);
771 
773  if (!DecodeHexTx(mtx, request.params[0].get_str()))
774  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
775 
776  // Fetch previous transactions (inputs):
777  CCoinsView viewDummy;
778  CCoinsViewCache view(&viewDummy);
779  {
780  LOCK(mempool.cs);
781  CCoinsViewCache &viewChain = *pcoinsTip;
782  CCoinsViewMemPool viewMempool(&viewChain, mempool);
783  view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
784 
785  for (const CTxIn& txin : mtx.vin) {
786  view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
787  }
788 
789  view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
790  }
791 
792 #ifdef ENABLE_WALLET
793  LOCK(pwallet ? &pwallet->cs_wallet : nullptr);
794 #endif
795 
796  bool fGivenKeys = false;
797  CBasicKeyStore tempKeystore;
798  if (!request.params[2].isNull()) {
799  fGivenKeys = true;
800  UniValue keys = request.params[2].get_array();
801  for (unsigned int idx = 0; idx < keys.size(); idx++) {
802  UniValue k = keys[idx];
803  CBitcoinSecret vchSecret;
804  bool fGood = vchSecret.SetString(k.get_str());
805  if (!fGood)
806  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
807  CKey key = vchSecret.GetKey();
808  if (!key.IsValid())
809  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
810  tempKeystore.AddKey(key);
811  }
812  }
813 #ifdef ENABLE_WALLET
814  else if (pwallet) {
815  EnsureWalletIsUnlocked(pwallet);
816  }
817 #endif
818 
819  // Add previous txouts given in the RPC call:
820  if (!request.params[1].isNull()) {
821  UniValue prevTxs = request.params[1].get_array();
822  for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {
823  const UniValue& p = prevTxs[idx];
824  if (!p.isObject())
825  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
826 
827  UniValue prevOut = p.get_obj();
828 
829  RPCTypeCheckObj(prevOut,
830  {
831  {"txid", UniValueType(UniValue::VSTR)},
832  {"vout", UniValueType(UniValue::VNUM)},
833  {"scriptPubKey", UniValueType(UniValue::VSTR)},
834  });
835 
836  uint256 txid = ParseHashO(prevOut, "txid");
837 
838  int nOut = find_value(prevOut, "vout").get_int();
839  if (nOut < 0)
840  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
841 
842  COutPoint out(txid, nOut);
843  std::vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
844  CScript scriptPubKey(pkData.begin(), pkData.end());
845 
846  {
847  const Coin& coin = view.AccessCoin(out);
848  if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
849  std::string err("Previous output scriptPubKey mismatch:\n");
850  err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
851  ScriptToAsmStr(scriptPubKey);
853  }
854  Coin newcoin;
855  newcoin.out.scriptPubKey = scriptPubKey;
856  newcoin.out.nValue = 0;
857  if (prevOut.exists("amount")) {
858  newcoin.out.nValue = AmountFromValue(find_value(prevOut, "amount"));
859  }
860  newcoin.nHeight = 1;
861  view.AddCoin(out, std::move(newcoin), true);
862  }
863 
864  // if redeemScript given and not using the local wallet (private keys
865  // given), add redeemScript to the tempKeystore so it can be signed:
866  if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) {
867  RPCTypeCheckObj(prevOut,
868  {
869  {"txid", UniValueType(UniValue::VSTR)},
870  {"vout", UniValueType(UniValue::VNUM)},
871  {"scriptPubKey", UniValueType(UniValue::VSTR)},
872  {"redeemScript", UniValueType(UniValue::VSTR)},
873  });
874  UniValue v = find_value(prevOut, "redeemScript");
875  if (!v.isNull()) {
876  std::vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
877  CScript redeemScript(rsData.begin(), rsData.end());
878  tempKeystore.AddCScript(redeemScript);
879  }
880  }
881  }
882  }
883 
884 #ifdef ENABLE_WALLET
885  const CKeyStore& keystore = ((fGivenKeys || !pwallet) ? tempKeystore : *pwallet);
886 #else
887  const CKeyStore& keystore = tempKeystore;
888 #endif
889 
890  int nHashType = SIGHASH_ALL;
891  if (!request.params[3].isNull()) {
892  static std::map<std::string, int> mapSigHashValues = {
893  {std::string("ALL"), int(SIGHASH_ALL)},
894  {std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},
895  {std::string("NONE"), int(SIGHASH_NONE)},
896  {std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},
897  {std::string("SINGLE"), int(SIGHASH_SINGLE)},
898  {std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},
899  };
900  std::string strHashType = request.params[3].get_str();
901  if (mapSigHashValues.count(strHashType))
902  nHashType = mapSigHashValues[strHashType];
903  else
904  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
905  }
906 
907  bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
908 
909  // Script verification errors
910  UniValue vErrors(UniValue::VARR);
911 
912  // Use CTransaction for the constant parts of the
913  // transaction to avoid rehashing.
914  const CTransaction txConst(mtx);
915  // Sign what we can:
916  for (unsigned int i = 0; i < mtx.vin.size(); i++) {
917  CTxIn& txin = mtx.vin[i];
918  const Coin& coin = view.AccessCoin(txin.prevout);
919  if (coin.IsSpent()) {
920  TxInErrorToJSON(txin, vErrors, "Input not found or already spent");
921  continue;
922  }
923  const CScript& prevPubKey = coin.out.scriptPubKey;
924  const CAmount& amount = coin.out.nValue;
925 
926  SignatureData sigdata;
927  // Only sign SIGHASH_SINGLE if there's a corresponding output:
928  if (!fHashSingle || (i < mtx.vout.size()))
929  ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mtx, i, amount, nHashType), prevPubKey, sigdata);
930  sigdata = CombineSignatures(prevPubKey, TransactionSignatureChecker(&txConst, i, amount), sigdata, DataFromTransaction(mtx, i));
931 
932  UpdateTransaction(mtx, i, sigdata);
933 
934  ScriptError serror = SCRIPT_ERR_OK;
935  if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount), &serror)) {
936  if (serror == SCRIPT_ERR_INVALID_STACK_OPERATION) {
937  // Unable to sign input and verification failed (possible attempt to partially sign).
938  TxInErrorToJSON(txin, vErrors, "Unable to sign input, invalid stack size (possibly missing key)");
939  } else {
940  TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));
941  }
942  }
943  }
944  bool fComplete = vErrors.empty();
945 
946  UniValue result(UniValue::VOBJ);
947  result.push_back(Pair("hex", EncodeHexTx(mtx)));
948  result.push_back(Pair("complete", fComplete));
949  if (!vErrors.empty()) {
950  result.push_back(Pair("errors", vErrors));
951  }
952 
953  return result;
954 }
955 
957 {
958  if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
959  throw std::runtime_error(
960  "sendrawtransaction \"hexstring\" ( allowhighfees instantsend bypasslimits)\n"
961  "\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
962  "\nAlso see createrawtransaction and signrawtransaction calls.\n"
963  "\nArguments:\n"
964  "1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
965  "2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
966  "3. instantsend (boolean, optional, default=false) Deprecated and ignored\n"
967  "4. bypasslimits (boolean, optional, default=false) Bypass transaction policy limits\n"
968  "\nResult:\n"
969  "\"hex\" (string) The transaction hash in hex\n"
970  "\nExamples:\n"
971  "\nCreate a transaction\n"
972  + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
973  "Sign the transaction, and get back the hex\n"
974  + HelpExampleCli("signrawtransaction", "\"myhex\"") +
975  "\nSend the transaction (signed hex)\n"
976  + HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
977  "\nAs a json rpc call\n"
978  + HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
979  );
980 
981  ObserveSafeMode();
982 
983  std::promise<void> promise;
984 
985  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL, UniValue::VBOOL});
986 
987  // parse hex string from parameter
989  if (!DecodeHexTx(mtx, request.params[0].get_str()))
990  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
991  CTransactionRef tx(MakeTransactionRef(std::move(mtx)));
992  const uint256& hashTx = tx->GetHash();
993 
994  CAmount nMaxRawTxFee = maxTxFee;
995  if (!request.params[1].isNull() && request.params[1].get_bool())
996  nMaxRawTxFee = 0;
997 
998  bool fBypassLimits = false;
999  if (!request.params[3].isNull())
1000  fBypassLimits = request.params[3].get_bool();
1001 
1002  { // cs_main scope
1003  LOCK(cs_main);
1004  CCoinsViewCache &view = *pcoinsTip;
1005  bool fHaveChain = false;
1006  for (size_t o = 0; !fHaveChain && o < tx->vout.size(); o++) {
1007  const Coin& existingCoin = view.AccessCoin(COutPoint(hashTx, o));
1008  fHaveChain = !existingCoin.IsSpent();
1009  }
1010  bool fHaveMempool = mempool.exists(hashTx);
1011  if (!fHaveMempool && !fHaveChain) {
1012  // push to local node and sync with wallets
1013  CValidationState state;
1014  bool fMissingInputs;
1015  if (!AcceptToMemoryPool(mempool, state, std::move(tx), &fMissingInputs,
1016  fBypassLimits /* bypass_limits */, nMaxRawTxFee)) {
1017  if (state.IsInvalid()) {
1018  throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
1019  } else {
1020  if (fMissingInputs) {
1021  throw JSONRPCError(RPC_TRANSACTION_ERROR, "Missing inputs");
1022  }
1024  }
1025  } else {
1026  // If wallet is enabled, ensure that the wallet has been made aware
1027  // of the new transaction prior to returning. This prevents a race
1028  // where a user might call sendrawtransaction with a transaction
1029  // to/from their wallet, immediately call some wallet RPC, and get
1030  // a stale result because callbacks have not yet been processed.
1032  promise.set_value();
1033  });
1034  }
1035  } else if (fHaveChain) {
1036  throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
1037  } else {
1038  // Make sure we don't block forever if re-sending
1039  // a transaction already in mempool.
1040  promise.set_value();
1041  }
1042 
1043  } // cs_main
1044 
1045  promise.get_future().wait();
1046 
1047  if(!g_connman)
1048  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
1049 
1050  g_connman->RelayTransaction(*tx);
1051 
1052  return hashTx.GetHex();
1053 }
1054 
1055 static const CRPCCommand commands[] =
1056 { // category name actor (function) argNames
1057  // --------------------- ------------------------ ----------------------- ----------
1058  { "rawtransactions", "getrawtransaction", &getrawtransaction, {"txid","verbose","blockhash"} },
1059  { "rawtransactions", "createrawtransaction", &createrawtransaction, {"inputs","outputs","locktime"} },
1060  { "rawtransactions", "decoderawtransaction", &decoderawtransaction, {"hexstring"} },
1061  { "rawtransactions", "decodescript", &decodescript, {"hexstring"} },
1062  { "rawtransactions", "sendrawtransaction", &sendrawtransaction, {"hexstring","allowhighfees","instantsend","bypasslimits"} },
1063  { "rawtransactions", "combinerawtransaction", &combinerawtransaction, {"txs"} },
1064  { "rawtransactions", "signrawtransaction", &signrawtransaction, {"hexstring","prevtxs","privkeys","sighashtype"} }, /* uses wallet if enabled */
1065 
1066  { "blockchain", "gettxoutproof", &gettxoutproof, {"txids", "blockhash"} },
1067  { "blockchain", "verifytxoutproof", &verifytxoutproof, {"proof"} },
1068 };
1069 
1071 {
1072  for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
1073  t.appendCommand(commands[vcidx].name, &commands[vcidx]);
1074 }
CAmount nValue
Definition: transaction.h:147
const Coin & AccessByTxid(const CCoinsViewCache &view, const uint256 &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:249
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull, bool fStrict)
Definition: server.cpp:79
Aliases for backward compatibility.
Definition: protocol.h:63
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: server.cpp:134
CTxMemPool mempool
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string strKey)
Definition: server.cpp:147
bool IsSpent() const
Definition: coins.h:75
void UpdateTransaction(CMutableTransaction &tx, unsigned int nIn, const SignatureData &data)
Definition: sign.cpp:161
bool isObject() const
Definition: univalue.h:85
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn)
Extract signature data from a transaction, and insert it.
Definition: sign.cpp:153
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:80
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool potential_overwrite)
Add a coin.
Definition: coins.cpp:66
UniValue combinerawtransaction(const JSONRPCRequest &request)
bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params &consensusParams, uint256 &hashBlock, bool fAllowSlow, CBlockIndex *blockIndex)
Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock...
Definition: validation.cpp:950
Dash RPC command dispatcher.
Definition: server.h:140
int64_t GetBlockTime() const
Definition: chain.h:297
enum ScriptError_t ScriptError
CScript scriptPubKey
Definition: transaction.h:148
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:207
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or a pruned one if not found.
Definition: coins.cpp:116
bool get_bool() const
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:27
CKey GetKey()
Definition: base58.cpp:304
A UTXO entry.
Definition: coins.h:29
Definition: block.h:72
CCriticalSection cs_wallet
Definition: wallet.h:836
#define strprintf
Definition: tinyformat.h:1066
CAmount maxTxFee
Absolute maximum transaction fee (in duffs) used by wallet and mempool (rejects high fee in sendrawtr...
Definition: validation.cpp:247
bool HasChainLock(int nHeight, const uint256 &blockHash)
std::vector< CTxIn > vin
Definition: transaction.h:293
BlockMap & mapBlockIndex
Definition: validation.cpp:215
int Height() const
Return the maximal height in the chain.
Definition: chain.h:484
CCriticalSection cs_main
Definition: validation.cpp:213
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:281
CTxOut out
unspent transaction output
Definition: coins.h:33
CTxDestination DecodeDestination(const std::string &str)
Definition: base58.cpp:336
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
bool AddCScript(const CScript &redeemScript) override
Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki.
Definition: keystore.cpp:64
UniValue decoderawtransaction(const JSONRPCRequest &request)
const std::string & get_str() const
bool isNum() const
Definition: univalue.h:83
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: server.cpp:583
const UniValue & get_array() const
const std::string CURRENCY_UNIT
Definition: feerate.cpp:10
bool isStr() const
Definition: univalue.h:82
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:103
int64_t get_int64() const
const std::vector< std::string > & getKeys() const
void TxToJSON(const CTransaction &tx, const uint256 hashBlock, UniValue &entry)
static void TxInErrorToJSON(const CTxIn &txin, UniValue &vErrorsRet, const std::string &strMessage)
Pushes a JSON object for script verification or signing errors to vErrorsRet.
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:345
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:353
bool ProduceSignature(const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
Definition: sign.cpp:124
bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx)
Definition: core_read.cpp:90
bool IsNull() const
Definition: uint256.h:33
bool IsCoinBase() const
Definition: transaction.h:272
std::string HelpRequiringPassphrase(CWallet *const pwallet)
Definition: rpcwallet.cpp:59
void RPCTypeCheck(const UniValue &params, const std::list< UniValue::VType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: server.cpp:54
const std::vector< CTxIn > vin
Definition: transaction.h:215
Invalid, missing or duplicate parameter.
Definition: protocol.h:53
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: server.cpp:121
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:236
bool SetString(const char *pszSecret)
Definition: base58.cpp:319
const char * ScriptErrorString(const ScriptError serror)
Definition: script_error.cpp:8
CInstantSendManager * quorumInstantSendManager
std::unique_ptr< CCoinsViewCache > pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:300
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
uint256 GetBlockHash() const
Definition: chain.h:292
General error during transaction or block submission.
Definition: protocol.h:56
uint32_t nHeight
at which height this containing transaction was included in the active block chain ...
Definition: coins.h:39
iterator end()
Definition: prevector.h:320
static CTransactionRef MakeTransactionRef()
Definition: transaction.h:346
std::string name
Definition: server.h:132
Used to relay blocks as header + vector<merkle branch> to filtered nodes.
Definition: merkleblock.h:127
CChainLocksHandler * chainLocksHandler
bool push_back(const UniValue &val)
Definition: univalue.cpp:110
std::map< CSpentIndexKey, CSpentIndexValue, CSpentIndexKeyCompare > mSpentInfo
Definition: spentindex.h:102
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode=false)
Create the assembly string representation of a CScript object.
Definition: core_write.cpp:86
bool IsInvalid() const
Definition: validation.h:64
Abstract view on the open txout dataset.
Definition: coins.h:145
UniValue params
Definition: server.h:42
An input of a transaction.
Definition: transaction.h:70
#define LOCK(cs)
Definition: sync.h:178
A base58-encoded secret key.
Definition: base58.h:101
const uint256 & GetHash() const
Definition: transaction.h:256
bool exists(const std::string &key) const
Definition: univalue.h:76
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:471
uint256 uint256S(const char *str)
Definition: uint256.h:143
std::string GetRejectReason() const
Definition: validation.h:81
uint32_t n
Definition: transaction.h:30
UniValue decodescript(const JSONRPCRequest &request)
bool IsLocked(const uint256 &txHash)
bool IsHex(const std::string &str)
const std::vector< CTxOut > vout
Definition: transaction.h:216
bool empty() const
Definition: univalue.h:67
General application defined errors.
Definition: protocol.h:48
bool exists(uint256 hash) const
Definition: txmempool.h:672
void CallFunctionInValidationInterfaceQueue(std::function< void()> func)
Pushes a function to callback onto the notification queue, guaranteeing any callbacks generated prior...
An output of a transaction.
Definition: transaction.h:144
int get_int() const
std::string ToString() const
Definition: uint256.cpp:62
Invalid address or key.
Definition: protocol.h:51
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:256
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: server.cpp:578
bool GetSpentIndex(CSpentIndexKey &key, CSpentIndexValue &value)
Definition: validation.cpp:908
static std::pair< std::string, UniValue > Pair(const char *cKey, const char *cVal)
Definition: univalue.h:185
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:26
virtual bool AddKey(const CKey &key)
Definition: keystore.cpp:10
std::vector< CTxOut > vout
Definition: transaction.h:294
bool fTxIndex
Definition: validation.cpp:225
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, unsigned int flags, const BaseSignatureChecker &checker, ScriptError *serror)
bool isNull() const
Definition: univalue.h:78
void RegisterRawTransactionRPCCommands(CRPCTable &t)
Register raw transaction RPC commands.
CCriticalSection cs
Definition: txmempool.h:488
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string strName)
Definition: server.cpp:138
CScript scriptSig
Definition: transaction.h:74
UniValue createrawtransaction(const JSONRPCRequest &request)
bool fHelp
Definition: server.h:43
Capture information about block/transaction validation.
Definition: validation.h:22
256-bit opaque blob.
Definition: uint256.h:123
std::string EncodeHexTx(const CTransaction &tx)
Definition: core_write.cpp:130
std::vector< CTransactionRef > vtx
Definition: block.h:76
static const unsigned int STANDARD_SCRIPT_VERIFY_FLAGS
Standard script verification flags that standard transactions will comply with.
Definition: policy.h:44
const_iterator end() const
Definition: streams.h:192
#define ARRAYLEN(array)
std::string EncodeDestination(const CTxDestination &dest)
Definition: base58.cpp:329
const_iterator begin() const
Definition: streams.h:190
UniValue getrawtransaction(const JSONRPCRequest &request)
UniValue verifytxoutproof(const JSONRPCRequest &request)
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:170
const CChainParams & Params()
Return the currently selected parameters.
UniValue sendrawtransaction(const JSONRPCRequest &request)
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:389
uint32_t nSequence
Definition: transaction.h:75
static const CRPCCommand commands[]
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:14
const UniValue & get_obj() const
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool *pfMissingInputs, bool bypass_limits, const CAmount nAbsurdFee, bool fDryRun)
(try to) add transaction to memory pool
Definition: validation.cpp:890
A virtual base class for key stores.
Definition: keystore.h:19
std::string GetHex() const
Definition: uint256.cpp:21
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
Definition: wallet.h:715
UniValue gettxoutproof(const JSONRPCRequest &request)
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:97
void TxToUniv(const CTransaction &tx, const uint256 &hashBlock, UniValue &entry, bool include_hex=true, const CSpentIndexTxInfo *ptxSpentInfo=nullptr)
Definition: core_write.cpp:163
CWallet * GetWalletForJSONRPCRequest(const JSONRPCRequest &request)
Figures out what wallet, if any, to use for a JSONRPCRequest.
Definition: rpcwallet.cpp:45
static Stacks CombineSignatures(const CScript &scriptPubKey, const BaseSignatureChecker &checker, const txnouttype txType, const std::vector< valtype > &vSolutions, Stacks sigs1, Stacks sigs2, SigVersion sigversion)
Definition: sign.cpp:265
iterator begin()
Definition: prevector.h:318
unsigned int GetRejectCode() const
Definition: validation.h:80
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
Definition: core_write.cpp:137
void ObserveSafeMode()
Definition: safemode.cpp:7
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:22
A mutable version of CTransaction.
Definition: transaction.h:291
UniValue signrawtransaction(const JSONRPCRequest &request)
UniValue JSONRPCError(int code, const std::string &message)
Definition: protocol.cpp:54
No valid connection manager instance found.
Definition: protocol.h:74
size_t size() const
Definition: univalue.h:69
An encapsulated private key.
Definition: key.h:27
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:198
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:183
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:201
full block available in blk*.dat
Definition: chain.h:154
static CAmount AmountFromValue(const UniValue &value)
Definition: dash-tx.cpp:486
CChain & chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:217
COutPoint prevout
Definition: transaction.h:73
CCoinsView that brings transactions from a memorypool into view.
Definition: txmempool.h:739
Basic key store, that keeps keys in an address->secret map.
Definition: keystore.h:56
Wrapper for UniValue::VType, which includes typeAny: Used to denote don&#39;t care type.
Definition: server.h:30
Error parsing or validating structure in raw format.
Definition: protocol.h:55
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:93
void EnsureWalletIsUnlocked(CWallet *const pwallet)
Definition: rpcwallet.cpp:83
uint256 hash
Definition: transaction.h:29
Released under the MIT license