PRCYCoin  2.0.0.7rc1
P2P Digital Currency
rawtransaction.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin developers
3 // Copyright (c) 2014-2015 The Dash developers
4 // Copyright (c) 2015-2018 The PIVX developers
5 // Copyright (c) 2018-2020 The DAPS Project developers
6 // Distributed under the MIT software license, see the accompanying
7 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
8 
9 #include "base58.h"
10 #include "core_io.h"
11 #include "init.h"
12 #include "keystore.h"
13 #include "main.h"
14 #include "net.h"
15 #include "primitives/transaction.h"
16 #include "rpc/server.h"
17 #include "script/script.h"
18 #include "script/script_error.h"
19 #include "script/sign.h"
20 #include "script/standard.h"
21 #include "uint256.h"
22 #include "utilmoneystr.h"
23 #include "wallet/wallet.h"
24 #ifdef ENABLE_WALLET
25 #include "wallet/wallet.h"
26 #endif
27 
28 #include <stdint.h>
29 
30 #include <univalue.h>
31 #include <boost/assign/list_of.hpp>
32 
33 
34 void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex)
35 {
36  txnouttype type;
37  std::vector<CTxDestination> addresses;
38  int nRequired;
39 
40  out.push_back(Pair("asm", scriptPubKey.ToString()));
41  if (fIncludeHex)
42  out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
43 
44  if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) {
45  out.push_back(Pair("type", GetTxnOutputType(type)));
46  return;
47  }
48 
49  out.push_back(Pair("reqSigs", nRequired));
50  out.push_back(Pair("type", GetTxnOutputType(type)));
51 
53  for (const CTxDestination& addr : addresses)
54  a.push_back(CBitcoinAddress(addr).ToString());
55  out.push_back(Pair("addresses", a));
56 }
57 
58 
59 void PoSBlockInfoToJSON(const uint256 hashBlock, int64_t nTime, int height, UniValue& entry) {
60  entry.push_back(Pair("posblockhash", hashBlock.GetHex()));
61  entry.push_back(Pair("time", nTime));
62  entry.push_back(Pair("height", height));
63  entry.push_back(Pair("isauditsuccessful", nTime > 0? "true":"false"));
64 }
65 
66 void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry)
67 {
68  entry.push_back(Pair("txid", tx.GetHash().GetHex()));
69  entry.push_back(Pair("version", tx.nVersion));
70  entry.push_back(Pair("size", (int)::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION)));
71  entry.push_back(Pair("locktime", (int64_t)tx.nLockTime));
72  entry.push_back(Pair("txfee", ValueFromAmount(tx.nTxFee)));
73  if (tx.hasPaymentID && pwalletMain->IsMine(tx)) {
74  entry.push_back(Pair("paymentid", tx.paymentID));
75  }
76  entry.push_back(Pair("txType", (int64_t)tx.txType));
77 #ifdef ENABLE_WALLET
79  entry.push_back(Pair("direction", pwalletMain->GetTransactionType(tx)));
80 #endif
82  for (const CTxIn& txin : tx.vin) {
84  if (tx.IsCoinBase())
85  in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
86  else {
87  {
88  //decoys
89  UniValue decoys(UniValue::VARR);
90  std::vector<COutPoint> allDecoys = txin.decoys;
91  srand (time(NULL));
92  allDecoys.insert(allDecoys.begin(), txin.prevout);
93  for (size_t i = 0; i < allDecoys.size(); i++) {
94  UniValue decoy(UniValue::VOBJ);
95  decoy.push_back(Pair("txid", allDecoys[i].hash.GetHex()));
96  decoy.push_back(Pair("vout", (int64_t)allDecoys[i].n));
97 #ifdef ENABLE_WALLET
98  std::map<uint256, CWalletTx>::const_iterator mi = pwalletMain->mapWallet.find(allDecoys[i].hash);
99  if (mi != pwalletMain->mapWallet.end()) {
100  const CWalletTx& prev = (*mi).second;
101  if (allDecoys[i].n < prev.vout.size()) {
102  if (pwalletMain->IsMine(prev.vout[allDecoys[i].n])) {
103  std::string outString = allDecoys[i].hash.GetHex() + std::to_string(allDecoys[i].n);
104  if (pwalletMain->outpointToKeyImages.count(outString) == 1) {
105  CKeyImage ki = pwalletMain->outpointToKeyImages[outString];
106  if (ki == txin.keyImage) {
107  CAmount decodedAmount;
108  CKey blind;
109  pwalletMain->RevealTxOutAmount(prev, prev.vout[allDecoys[i].n], decodedAmount, blind);
110  if (pwalletMain->IsLocked()) {
111  decoy.push_back(Pair("decoded_amount", "Wallet is Locked"));
112  } else {
113  decoy.push_back(Pair("decoded_amount", ValueFromAmount(decodedAmount)));
114  }
115 
116  decoy.push_back(Pair("isMine", true));
117  }
118  }
119  } else {
120  decoy.push_back(Pair("isMine", false));
121  }
122  }
123  }
124 #endif
125  decoys.push_back(decoy);
126  }
127  in.push_back(Pair("decoys", decoys));
128  }
130  o.push_back(Pair("asm", txin.scriptSig.ToString()));
131  o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
132  in.push_back(Pair("scriptSig", o));
133  }
134  in.push_back(Pair("sequence", (int64_t)txin.nSequence));
135  in.push_back(Pair("keyimage", txin.keyImage.GetHex()));
136  in.push_back(Pair("ringsize", (int64_t) (txin.decoys.size() + 1)));
137  vin.push_back(in);
138  }
139  entry.push_back(Pair("vin", vin));
140  UniValue vout(UniValue::VARR);
141  for (unsigned int i = 0; i < tx.vout.size(); i++) {
142  const CTxOut& txout = tx.vout[i];
144  out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
145  out.push_back(Pair("n", (int64_t)i));
147  ScriptPubKeyToJSON(txout.scriptPubKey, o, true);
148  out.push_back(Pair("scriptPubKey", o));
149  out.push_back(Pair("encoded_amount", txout.maskValue.amount.GetHex()));
150  out.push_back(Pair("encoded_mask", txout.maskValue.mask.GetHex()));
151  CPubKey txPubKey(txout.txPub);
152  out.push_back(Pair("txpubkey", txPubKey.GetHex()));
153  out.push_back(Pair("commitment", HexStr(txout.commitment.begin(), txout.commitment.end())));
154 
155 #ifdef ENABLE_WALLET
156  if (pwalletMain->IsMine(txout)) {
157  CAmount decodedAmount;
158  CKey blind;
159  unsigned char zeroBlind[32];
160  memset(zeroBlind, 0, 32);
161  const unsigned char* pBlind;
162  pwalletMain->RevealTxOutAmount(tx, txout, decodedAmount, blind);
163  if (txout.nValue >0) {
164  pBlind = zeroBlind;
165  } else {
166  pBlind = blind.begin();
167  }
168  if (pwalletMain->IsLocked()) {
169  out.push_back(Pair("decoded_amount", "Wallet is Locked"));
170  } else {
171  out.push_back(Pair("decoded_amount", ValueFromAmount(decodedAmount)));
172  }
173 
174  out.push_back(Pair("isMine", true));
175  } else {
176  out.push_back(Pair("isMine", false));
177  }
178 #endif
179  vout.push_back(out);
180  }
181  entry.push_back(Pair("vout", vout));
182 
183  if (!hashBlock.IsNull()) {
184  entry.push_back(Pair("blockhash", hashBlock.GetHex()));
185  BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
186  if (mi != mapBlockIndex.end() && (*mi).second) {
187  CBlockIndex* pindex = (*mi).second;
188  if (chainActive.Contains(pindex)) {
189  entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
190  entry.push_back(Pair("time", pindex->GetBlockTime()));
191  entry.push_back(Pair("blocktime", pindex->GetBlockTime()));
192  }
193  else
194  entry.push_back(Pair("confirmations", 0));
195  }
196  }
197 }
198 
199 //for mobile wallet fast sync
201 {
202  if (fHelp || params.size() != 1)
203  throw std::runtime_error(
204  "getrawtransactionbyblockheight \"blockheight\" ( verbose )\n"
205  "\nNOTE: By default this function only works sometimes. This is when the tx is in the mempool\n"
206  "or there is an unspent output in the utxo for this transaction. To make it always work,\n"
207  "you need to maintain a transaction index, using the -txindex command line option.\n"
208  "\nReturn the raw transaction data.\n"
209  "\nIf verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\n"
210  "If verbose is non-zero, returns an Object with information about 'txid'.\n"
211 
212  "\nArguments:\n"
213  "1. \"blockheight\" (numeric, required) The transaction id\n"
214 
215  "\nResult (if verbose is not set or set to 0):\n"
216  "\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
217 
218  "\nResult (if verbose > 0):\n"
219  "{\n"
220  " \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
221  " \"blockhash\" : \"hash\", (string) the block hash\n"
222  " \"confirmations\" : n, (numeric) The confirmations\n"
223  " \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
224  "}\n"
225 
226  "\nExamples:\n" +
227  HelpExampleCli("getrawtransaction", "\"mytxid\"") + HelpExampleCli("getrawtransaction", "\"mytxid\" 1") + HelpExampleRpc("getrawtransaction", "\"mytxid\", 1"));
228 
229  int nHeight = params[0].get_int();
230  if (nHeight > chainActive.Height()) {
231  throw JSONRPCError(RPC_INVALID_BLOCK_HEIGHT, "Block height is too high");
232  }
233  CBlock block;
234  if (!ReadBlockFromDisk(block, chainActive[nHeight])) {
235  throw JSONRPCError(RPC_INVALID_BLOCK_HEIGHT, "Block cannot be read from disk");
236  }
237 
238  UniValue result(UniValue::VOBJ);
239  UniValue hexs(UniValue::VARR);
240  for (size_t i = 0; i < block.vtx.size(); i++) {
241  CTransaction& tx = block.vtx[i];
242  std::string strHex = EncodeHexTx(tx);
243  hexs.push_back(strHex);
244  }
245  result.push_back(Pair("hexs", hexs));
246  result.push_back(Pair("blockhash", block.GetHash().GetHex()));
247  result.push_back(Pair("confirmations", chainActive.Height() - nHeight + 1));
248  result.push_back(Pair("blocktime", block.GetBlockTime()));
249  return result;
250 }
251 
252 UniValue getrawtransaction(const UniValue& params, bool fHelp)
253 {
254  if (fHelp || params.size() < 1 || params.size() > 3)
255  throw std::runtime_error(
256  "getrawtransaction \"txid\" ( verbose \"blockhash\" )\n"
257 
258  "\nNOTE: By default this function only works sometimes. This is when the tx is in the mempool\n"
259  "or there is an unspent output in the utxo for this transaction. To make it always work,\n"
260  "you need to maintain a transaction index, using the -txindex command line option.\n"
261 
262  "\nReturn the raw transaction data.\n"
263  "\nIf verbose is 'true', returns an Object with information about 'txid'.\n"
264  "If verbose is 'false' or omitted, returns a string that is serialized, hex-encoded data for 'txid'.\n"
265 
266  "\nArguments:\n"
267  "1. \"txid\" (string, required) The transaction id\n"
268  "2. verbose (bool, optional, default=false) If false, return a string, otherwise return a json object\n"
269  "3. \"blockhash\" (string, optional) The block in which to look for the transaction\n"
270 
271  "\nResult (if verbose is not set or set to false):\n"
272  "\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
273 
274  "\nResult (if verbose is set to true):\n"
275  "{\n"
276  " \"in_active_chain\": b, (bool) Whether specified block is in the active chain or not (only present with explicit \"blockhash\" argument)\n"
277  " \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
278  " \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
279  " \"size\" : n, (numeric) The serialized transaction size\n"
280  " \"version\" : n, (numeric) The version\n"
281  " \"locktime\" : ttt, (numeric) The lock time\n"
282  " \"vin\" : [ (array of json objects)\n"
283  " {\n"
284  " \"txid\": \"id\", (string) The transaction id\n"
285  " \"vout\": n, (numeric) \n"
286  " \"scriptSig\": { (json object) The script\n"
287  " \"asm\": \"asm\", (string) asm\n"
288  " \"hex\": \"hex\" (string) hex\n"
289  " },\n"
290  " \"sequence\": n (numeric) The script sequence number\n"
291  " }\n"
292  " ,...\n"
293  " ],\n"
294  " \"vout\" : [ (array of json objects)\n"
295  " {\n"
296  " \"value\" : x.xxx, (numeric) The value in PRCY\n"
297  " \"n\" : n, (numeric) index\n"
298  " \"scriptPubKey\" : { (json object)\n"
299  " \"asm\" : \"asm\", (string) the asm\n"
300  " \"hex\" : \"hex\", (string) the hex\n"
301  " \"reqSigs\" : n, (numeric) The required sigs\n"
302  " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
303  " \"addresses\" : [ (json array of string)\n"
304  " \"prcycoinaddress\" (string) prcycoin address\n"
305  " ,...\n"
306  " ]\n"
307  " }\n"
308  " }\n"
309  " ,...\n"
310  " ],\n"
311  " \"blockhash\" : \"hash\", (string) the block hash\n"
312  " \"confirmations\" : n, (numeric) The confirmations\n"
313  " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
314  " \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
315  "}\n"
316 
317  "\nExamples:\n"
318  + HelpExampleCli("getrawtransaction", "\"mytxid\"")
319  + HelpExampleCli("getrawtransaction", "\"mytxid\" true")
320  + HelpExampleRpc("getrawtransaction", "\"mytxid\", true")
321  + HelpExampleCli("getrawtransaction", "\"mytxid\" false \"myblockhash\"")
322  + HelpExampleCli("getrawtransaction", "\"mytxid\" true \"myblockhash\"")
323  );
324 
325  LOCK(cs_main);
326 
327  bool in_active_chain = true;
328  uint256 hash = ParseHashV(params[0], "parameter 1");
329  CBlockIndex* blockindex = nullptr;
330 
331  bool fVerbose = false;
332  if (!params[1].isNull()) {
333  fVerbose = params[1].isNum() ? (params[1].get_int() != 0) : params[1].get_bool();
334  }
335 
336  if (!params[2].isNull()) {
337  uint256 blockhash = ParseHashV(params[2], "parameter 3");
338  BlockMap::iterator it = mapBlockIndex.find(blockhash);
339  if (it == mapBlockIndex.end()) {
340  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block hash not found");
341  }
342  blockindex = it->second;
343  in_active_chain = chainActive.Contains(blockindex);
344  }
345 
346  CTransaction tx;
347  uint256 hash_block;
348  if (!GetTransaction(hash, tx, hash_block, true, blockindex)) {
349  std::string errmsg;
350  if (blockindex) {
351  if (!(blockindex->nStatus & BLOCK_HAVE_DATA)) {
352  throw JSONRPCError(RPC_MISC_ERROR, "Block not available");
353  }
354  errmsg = "No such transaction found in the provided block";
355  } else {
356  errmsg = fTxIndex
357  ? "No such mempool or blockchain transaction"
358  : "No such mempool transaction. Use -txindex to enable blockchain transaction queries";
359  }
360  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, errmsg + ". Use gettransaction for wallet transactions.");
361  }
362 
363  if (!fVerbose) {
364  return EncodeHexTx(tx);
365  }
366 
367  UniValue result(UniValue::VOBJ);
368  if (blockindex) result.push_back(Pair("in_active_chain", in_active_chain));
369  TxToJSON(tx, hash_block, result);
370  return result;
371 }
372 
373 #ifdef ENABLE_WALLET
374 UniValue listunspent(const UniValue& params, bool fHelp)
375 {
376  if (fHelp || params.size() > 3)
377  throw std::runtime_error(
378  "listunspent ( minconf maxconf [\"address\",...] )\n"
379  "\nReturns array of unspent transaction outputs\n"
380  "with between minconf and maxconf (inclusive) confirmations.\n"
381  "Optionally filter to only include txouts paid to specified addresses.\n"
382  "Results are an array of Objects, each of which has:\n"
383  "{txid, vout, scriptPubKey, amount, confirmations, spendable}\n"
384  "\nArguments:\n"
385  "1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n"
386  "2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n"
387  "3. \"addresses\" (string) A json array of prcycoin addresses to filter\n"
388  " [\n"
389  " \"address\" (string) prcycoin address\n"
390  " ,...\n"
391  " ]\n"
392  "\nResult\n"
393  "[ (array of json object)\n"
394  " {\n"
395  " \"txid\" : \"txid\", (string) the transaction id\n"
396  " \"vout\" : n, (numeric) the vout value\n"
397  " \"address\" : \"address\", (string) the prcycoin address\n"
398  " \"account\" : \"account\", (string) The associated account, or \"\" for the default account\n"
399  " \"scriptPubKey\" : \"key\", (string) the script key\n"
400  " \"amount\" : x.xxx, (numeric) the transaction amount in PRCY\n"
401  " \"confirmations\" : n, (numeric) The number of confirmations\n"
402  " \"spendable\" : true|false (boolean) Whether we have the private keys to spend this output\n"
403  " }\n"
404  " ,...\n"
405  "]\n"
406 
407  "\nExamples\n" +
408  HelpExampleCli("listunspent", "") + HelpExampleCli("listunspent", "6 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"") + HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\""));
409 
410  RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM)(UniValue::VNUM)(UniValue::VARR));
411 
412  int nMinDepth = 1;
413  if (params.size() > 0)
414  nMinDepth = params[0].get_int();
415 
416  int nMaxDepth = 9999999;
417  if (params.size() > 1)
418  nMaxDepth = params[1].get_int();
419 
420  std::set<CBitcoinAddress> setAddress;
421  if (params.size() > 2) {
422  UniValue inputs = params[2].get_array();
423  for (unsigned int inx = 0; inx < inputs.size(); inx++) {
424  const UniValue& input = inputs[inx];
425  CBitcoinAddress address(input.get_str());
426  if (!address.IsValid())
427  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid PRCY address: ") + input.get_str());
428  if (setAddress.count(address))
429  throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + input.get_str());
430  setAddress.insert(address);
431  }
432  }
433 
434  UniValue results(UniValue::VARR);
435  std::vector<COutput> vecOutputs;
436  assert(pwalletMain != NULL);
438  pwalletMain->AvailableCoins(vecOutputs, false);
439  for (const COutput& out : vecOutputs) {
440  if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
441  continue;
442 
443  if (setAddress.size()) {
444  CTxDestination address;
445  if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
446  continue;
447 
448  if (!setAddress.count(address))
449  continue;
450  }
451 
452  CAmount nValue = pwalletMain->getCTxOutValue(*out.tx, out.tx->vout[out.i]);
453  const CScript& pk = out.tx->vout[out.i].scriptPubKey;
454  UniValue entry(UniValue::VOBJ);
455  entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
456  entry.push_back(Pair("vout", out.i));
457  CTxDestination address;
458  if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) {
459  entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
460  if (pwalletMain->mapAddressBook.count(address))
461  entry.push_back(Pair("account", pwalletMain->mapAddressBook[address].name));
462  }
463  entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
464  if (pk.IsPayToScriptHash()) {
465  CTxDestination address;
466  if (ExtractDestination(pk, address)) {
467  const CScriptID& hash = boost::get<CScriptID>(address);
468  CScript redeemScript;
469  if (pwalletMain->GetCScript(hash, redeemScript))
470  entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end())));
471  }
472  }
473  entry.push_back(Pair("amount", ValueFromAmount(nValue)));
474  entry.push_back(Pair("confirmations", out.nDepth));
475  entry.push_back(Pair("spendable", out.fSpendable));
476  results.push_back(entry);
477  }
478 
479  return results;
480 }
481 
482 UniValue getunspentcount(const UniValue& params, bool fHelp)
483 {
484  if (fHelp || params.size() > 3)
485  throw std::runtime_error(
486  "getunspentcount ( minconf maxconf [\"address\",...] )\n"
487  "\nReturns the number of unspent transactions\n"
488  "Optionally filter to only include txouts paid to specified addresses.\n"
489  "\nArguments:\n"
490  "1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n"
491  "2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n"
492  "3. \"addresses\" (string) A json array of prcycoin addresses to filter\n"
493  " [\n"
494  " \"address\" (string) prcycoin address\n"
495  " ,...\n"
496  " ]\n"
497  "\nResult\n"
498  "[ (array of json object)\n"
499  " {\n"
500  " \"unspentcount\" : x.xxx, (numeric) the number of unspent transactions\n"
501  " }\n"
502  " ,...\n"
503  "]\n"
504 
505  "\nExamples\n" +
506  HelpExampleCli("getunspentcount", "") + HelpExampleCli("getunspentcount", "6 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"") + HelpExampleRpc("getunspentcount", "6, 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\""));
507 
508  RPCTypeCheck(params, boost::assign::list_of(UniValue::VNUM)(UniValue::VNUM)(UniValue::VARR));
509 
510  int nMinDepth = 1;
511  if (params.size() > 0)
512  nMinDepth = params[0].get_int();
513 
514  int nMaxDepth = 9999999;
515  if (params.size() > 1)
516  nMaxDepth = params[1].get_int();
517 
518  std::set<CBitcoinAddress> setAddress;
519  if (params.size() > 2) {
520  UniValue inputs = params[2].get_array();
521  for (unsigned int inx = 0; inx < inputs.size(); inx++) {
522  const UniValue& input = inputs[inx];
523  CBitcoinAddress address(input.get_str());
524  if (!address.IsValid())
525  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid PRCY address: ") + input.get_str());
526  if (setAddress.count(address))
527  throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + input.get_str());
528  setAddress.insert(address);
529  }
530  }
531 
532  int count = 0;
533  std::vector<COutput> vecOutputs;
534  assert(pwalletMain != NULL);
536  pwalletMain->AvailableCoins(vecOutputs, false);
537  for (const COutput& out : vecOutputs) {
538  if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
539  continue;
540 
541  if (setAddress.size()) {
542  CTxDestination address;
543  if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
544  continue;
545 
546  if (!setAddress.count(address))
547  continue;
548  }
549  ++count;
550  }
552  obj.push_back(Pair("unspentcount", count));
553  return obj;
554 }
555 #endif
556 
557 UniValue createrawtransaction(const UniValue& params, bool fHelp)
558 {
559  if (fHelp || params.size() < 2 || params.size() > 3)
560  throw std::runtime_error(
561  "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,...} ( locktime )\n"
562  "\nCreate a transaction spending the given inputs and sending to the given addresses.\n"
563  "Returns hex-encoded raw transaction.\n"
564  "Note that the transaction's inputs are not signed, and\n"
565  "it is not stored in the wallet or transmitted to the network.\n"
566 
567  "\nArguments:\n"
568  "1. \"transactions\" (string, required) A json array of json objects\n"
569  " [\n"
570  " {\n"
571  " \"txid\":\"id\", (string, required) The transaction id\n"
572  " \"vout\":n, (numeric, required) The output number\n"
573  " \"sequence\":n (numeric, optional) The sequence number\n"
574  " }\n"
575  " ,...\n"
576  " ]\n"
577  "2. \"addresses\" (string, required) a json object with addresses as keys and amounts as values\n"
578  " {\n"
579  " \"address\": x.xxx (numeric, required) The key is the prcycoin address, the value is the PRCY amount\n"
580  " ,...\n"
581  " }\n"
582  "3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n"
583 
584  "\nResult:\n"
585  "\"transaction\" (string) hex string of the transaction\n"
586 
587  "\nExamples\n" +
588  HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"") + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\""));
589 
590  LOCK(cs_main);
591  RPCTypeCheck(params, boost::assign::list_of(UniValue::VARR)(UniValue::VOBJ)(UniValue::VNUM));
592  if (params[0].isNull() || params[1].isNull())
593  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null");
594 
595  UniValue inputs = params[0].get_array();
596  UniValue sendTo = params[1].get_obj();
597 
598  CMutableTransaction rawTx;
599 
600  if (params.size() > 2 && !params[2].isNull()) {
601  int64_t nLockTime = params[2].get_int64();
602  if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max())
603  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");
604  rawTx.nLockTime = nLockTime;
605  }
606 
607  for (unsigned int idx = 0; idx < inputs.size(); idx++) {
608  const UniValue& input = inputs[idx];
609  const UniValue& o = input.get_obj();
610 
611  uint256 txid = ParseHashO(o, "txid");
612 
613  const UniValue& vout_v = find_value(o, "vout");
614  if (!vout_v.isNum())
615  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
616  int nOutput = vout_v.get_int();
617  if (nOutput < 0)
618  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
619 
620  uint32_t nSequence = (rawTx.nLockTime ? std::numeric_limits<uint32_t>::max() - 1 : std::numeric_limits<uint32_t>::max());
621 
622  // set the sequence number if passed in the parameters object
623  const UniValue& sequenceObj = find_value(o, "sequence");
624  if (sequenceObj.isNum()) {
625  int64_t seqNr64 = sequenceObj.get_int64();
626  if (seqNr64 < 0 || seqNr64 > std::numeric_limits<uint32_t>::max())
627  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range");
628  else
629  nSequence = (uint32_t)seqNr64;
630  }
631 
632  CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
633 
634  rawTx.vin.push_back(in);
635  }
636 
637  std::set<CBitcoinAddress> setAddress;
638  std::vector<std::string> addrList = sendTo.getKeys();
639  for (const std::string& name_ : addrList) {
640  CBitcoinAddress address(name_);
641  if (!address.IsValid())
642  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid PRCY address: ")+name_);
643 
644  if (setAddress.count(address))
645  throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+name_);
646  setAddress.insert(address);
647 
648  CScript scriptPubKey = GetScriptForDestination(address.Get());
649  CAmount nAmount = AmountFromValue(sendTo[name_]);
650 
651  CTxOut out(nAmount, scriptPubKey);
652  rawTx.vout.push_back(out);
653  }
654 
655  return EncodeHexTx(rawTx);
656 }
657 
658 UniValue decoderawtransaction(const UniValue& params, bool fHelp)
659 {
660  if (fHelp || params.size() != 1)
661  throw std::runtime_error(
662  "decoderawtransaction \"hexstring\"\n"
663  "\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
664 
665  "\nArguments:\n"
666  "1. \"hex\" (string, required) The transaction hex string\n"
667 
668  "\nResult:\n"
669  "{\n"
670  " \"txid\" : \"id\", (string) The transaction id\n"
671  " \"size\" : n, (numeric) The transaction size\n"
672  " \"version\" : n, (numeric) The version\n"
673  " \"locktime\" : ttt, (numeric) The lock time\n"
674  " \"vin\" : [ (array of json objects)\n"
675  " {\n"
676  " \"txid\": \"id\", (string) The transaction id\n"
677  " \"vout\": n, (numeric) The output number\n"
678  " \"scriptSig\": { (json object) The script\n"
679  " \"asm\": \"asm\", (string) asm\n"
680  " \"hex\": \"hex\" (string) hex\n"
681  " },\n"
682  " \"sequence\": n (numeric) The script sequence number\n"
683  " }\n"
684  " ,...\n"
685  " ],\n"
686  " \"vout\" : [ (array of json objects)\n"
687  " {\n"
688  " \"value\" : x.xxx, (numeric) The value in PRCY\n"
689  " \"n\" : n, (numeric) index\n"
690  " \"scriptPubKey\" : { (json object)\n"
691  " \"asm\" : \"asm\", (string) the asm\n"
692  " \"hex\" : \"hex\", (string) the hex\n"
693  " \"reqSigs\" : n, (numeric) The required sigs\n"
694  " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
695  " \"addresses\" : [ (json array of string)\n"
696  " \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) prcycoin address\n"
697  " ,...\n"
698  " ]\n"
699  " }\n"
700  " }\n"
701  " ,...\n"
702  " ],\n"
703  "}\n"
704 
705  "\nExamples:\n" +
706  HelpExampleCli("decoderawtransaction", "\"hexstring\"") + HelpExampleRpc("decoderawtransaction", "\"hexstring\""));
707 
708  LOCK(cs_main);
709  RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR));
710 
711  CTransaction tx;
712 
713  if (!DecodeHexTx(tx, params[0].get_str()))
714  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
715 
716  UniValue result(UniValue::VOBJ);
717  TxToJSON(tx, UINT256_ZERO, result);
718 
719  return result;
720 }
721 
722 UniValue decodescript(const UniValue& params, bool fHelp)
723 {
724  if (fHelp || params.size() != 1)
725  throw std::runtime_error(
726  "decodescript \"hex\"\n"
727  "\nDecode a hex-encoded script.\n"
728  "\nArguments:\n"
729  "1. \"hex\" (string) the hex encoded script\n"
730  "\nResult:\n"
731  "{\n"
732  " \"asm\":\"asm\", (string) Script public key\n"
733  " \"hex\":\"hex\", (string) hex encoded public key\n"
734  " \"type\":\"type\", (string) The output type\n"
735  " \"reqSigs\": n, (numeric) The required signatures\n"
736  " \"addresses\": [ (json array of string)\n"
737  " \"address\" (string) prcycoin address\n"
738  " ,...\n"
739  " ],\n"
740  " \"p2sh\",\"address\" (string) script address\n"
741  "}\n"
742  "\nExamples:\n" +
743  HelpExampleCli("decodescript", "\"hexstring\"") + HelpExampleRpc("decodescript", "\"hexstring\""));
744 
745  LOCK(cs_main);
746  RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR));
747 
749  CScript script;
750  if (params[0].get_str().size() > 0) {
751  std::vector<unsigned char> scriptData(ParseHexV(params[0], "argument"));
752  script = CScript(scriptData.begin(), scriptData.end());
753  } else {
754  // Empty scripts are valid
755  }
756  ScriptPubKeyToJSON(script, r, false);
757 
758  r.push_back(Pair("p2sh", CBitcoinAddress(CScriptID(script)).ToString()));
759  return r;
760 }
761 
763 static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)
764 {
765  UniValue entry(UniValue::VOBJ);
766  entry.push_back(Pair("txid", txin.prevout.hash.ToString()));
767  entry.push_back(Pair("vout", (uint64_t)txin.prevout.n));
768  entry.push_back(Pair("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
769  entry.push_back(Pair("sequence", (uint64_t)txin.nSequence));
770  entry.push_back(Pair("error", strMessage));
771  vErrorsRet.push_back(entry);
772 }
773 
774 UniValue signrawtransaction(const UniValue& params, bool fHelp)
775 {
776  if (fHelp || params.size() < 1 || params.size() > 4)
777  throw std::runtime_error(
778  "signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
779  "\nSign inputs for raw transaction (serialized, hex-encoded).\n"
780  "The second optional argument (may be null) is an array of previous transaction outputs that\n"
781  "this transaction depends on but may not yet be in the block chain.\n"
782  "The third optional argument (may be null) is an array of base58-encoded private\n"
783  "keys that, if given, will be the only keys used to sign the transaction.\n"
784 #ifdef ENABLE_WALLET
785  + HelpRequiringPassphrase() + "\n"
786 #endif
787 
788  "\nArguments:\n"
789  "1. \"hexstring\" (string, required) The transaction hex string\n"
790  "2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
791  " [ (json array of json objects, or 'null' if none provided)\n"
792  " {\n"
793  " \"txid\":\"id\", (string, required) The transaction id\n"
794  " \"vout\":n, (numeric, required) The output number\n"
795  " \"scriptPubKey\": \"hex\", (string, required) script key\n"
796  " \"redeemScript\": \"hex\" (string, required for P2SH) redeem script\n"
797  " }\n"
798  " ,...\n"
799  " ]\n"
800  "3. \"privatekeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
801  " [ (json array of strings, or 'null' if none provided)\n"
802  " \"privatekey\" (string) private key in base58-encoding\n"
803  " ,...\n"
804  " ]\n"
805  "4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
806  " \"ALL\"\n"
807  " \"NONE\"\n"
808  " \"SINGLE\"\n"
809  " \"ALL|ANYONECANPAY\"\n"
810  " \"NONE|ANYONECANPAY\"\n"
811  " \"SINGLE|ANYONECANPAY\"\n"
812 
813  "\nResult:\n"
814  "{\n"
815  " \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"
816  " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
817  " \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n"
818  " {\n"
819  " \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n"
820  " \"vout\" : n, (numeric) The index of the output to spent and used as input\n"
821  " \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n"
822  " \"sequence\" : n, (numeric) Script sequence number\n"
823  " \"error\" : \"text\" (string) Verification or signing error related to the input\n"
824  " }\n"
825  " ,...\n"
826  " ]\n"
827  "}\n"
828 
829  "\nExamples:\n" +
830  HelpExampleCli("signrawtransaction", "\"myhex\"") + HelpExampleRpc("signrawtransaction", "\"myhex\""));
831 
832 #ifdef ENABLE_WALLET
834 #else
835  LOCK(cs_main);
836 #endif
837 
838  RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VARR)(UniValue::VARR)(UniValue::VSTR), true);
839 
840  std::vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
841  CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
842  std::vector<CMutableTransaction> txVariants;
843  while (!ssData.empty()) {
844  try {
846  ssData >> tx;
847  txVariants.push_back(tx);
848  } catch (const std::exception&) {
849  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
850  }
851  }
852 
853  if (txVariants.empty())
854  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
855 
856  // mergedTx will end up with all the signatures; it
857  // starts as a clone of the rawtx:
858  CMutableTransaction mergedTx(txVariants[0]);
859 
860  // Fetch previous transactions (inputs):
861  std::map<COutPoint, CScript> mapPrevOut;
862  if (Params().IsRegTestNet()) {
863  for (const CTxIn &txbase : mergedTx.vin)
864  {
865  CTransaction tempTx;
866  uint256 hashBlock;
867  if (GetTransaction(txbase.prevout.hash, tempTx, hashBlock, true)) {
868  // Copy results into mapPrevOut:
869  mapPrevOut[txbase.prevout] = tempTx.vout[txbase.prevout.n].scriptPubKey;
870  }
871  }
872  }
873  CCoinsView viewDummy;
874  CCoinsViewCache view(&viewDummy);
875  {
876  LOCK(mempool.cs);
877  CCoinsViewCache& viewChain = *pcoinsTip;
878  CCoinsViewMemPool viewMempool(&viewChain, mempool);
879  view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
880 
881  for (const CTxIn& txin : mergedTx.vin) {
882  const uint256& prevHash = txin.prevout.hash;
883  CCoins coins;
884  view.AccessCoins(prevHash); // this is certainly allowed to fail
885  }
886 
887  view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
888  }
889 
890  bool fGivenKeys = false;
891  CBasicKeyStore tempKeystore;
892  if (params.size() > 2 && !params[2].isNull()) {
893  fGivenKeys = true;
894  UniValue keys = params[2].get_array();
895  for (unsigned int idx = 0; idx < keys.size(); idx++) {
896  UniValue k = keys[idx];
897  CBitcoinSecret vchSecret;
898  bool fGood = vchSecret.SetString(k.get_str());
899  if (!fGood)
900  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
901  CKey key = vchSecret.GetKey();
902  if (!key.IsValid())
903  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
904  tempKeystore.AddKey(key);
905  }
906  }
907 #ifdef ENABLE_WALLET
908  else if (pwalletMain)
910 #endif
911 
912  // Add previous txouts given in the RPC call:
913  if (params.size() > 1 && !params[1].isNull()) {
914  UniValue prevTxs = params[1].get_array();
915  for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {
916  const UniValue& p = prevTxs[idx];
917  if (!p.isObject())
918  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
919 
920  UniValue prevOut = p.get_obj();
921 
922  RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR));
923 
924  uint256 txid = ParseHashO(prevOut, "txid");
925 
926  int nOut = find_value(prevOut, "vout").get_int();
927  if (nOut < 0)
928  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
929 
930  std::vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
931  CScript scriptPubKey(pkData.begin(), pkData.end());
932 
933  {
934  CCoinsModifier coins = view.ModifyCoins(txid);
935  if (coins->IsAvailable(nOut) && coins->vout[nOut].scriptPubKey != scriptPubKey) {
936  std::string err("Previous output scriptPubKey mismatch:\n");
937  err = err + coins->vout[nOut].scriptPubKey.ToString() + "\nvs:\n" +
938  scriptPubKey.ToString();
940  }
941  if ((unsigned int)nOut >= coins->vout.size())
942  coins->vout.resize(nOut + 1);
943  coins->vout[nOut].scriptPubKey = scriptPubKey;
944  coins->vout[nOut].nValue = 0; // we don't know the actual output value
945  }
946 
947  // if redeemScript given and not using the local wallet (private keys
948  // given), add redeemScript to the tempKeystore so it can be signed:
949  if (fGivenKeys && scriptPubKey.IsPayToScriptHash()) {
950  RPCTypeCheckObj(prevOut, boost::assign::map_list_of("txid", UniValue::VSTR)("vout", UniValue::VNUM)("scriptPubKey", UniValue::VSTR)("redeemScript",UniValue::VSTR));
951  UniValue v = find_value(prevOut, "redeemScript");
952  if (!v.isNull()) {
953  std::vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
954  CScript redeemScript(rsData.begin(), rsData.end());
955  tempKeystore.AddCScript(redeemScript);
956  }
957  }
958  }
959  }
960 
961 #ifdef ENABLE_WALLET
962  const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);
963 #else
964  const CKeyStore& keystore = tempKeystore;
965 #endif
966 
967  int nHashType = SIGHASH_ALL;
968  if (params.size() > 3 && !params[3].isNull()) {
969  static std::map<std::string, int> mapSigHashValues =
970  boost::assign::map_list_of(std::string("ALL"), int(SIGHASH_ALL))(std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL | SIGHASH_ANYONECANPAY))(std::string("NONE"), int(SIGHASH_NONE))(std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE | SIGHASH_ANYONECANPAY))(std::string("SINGLE"), int(SIGHASH_SINGLE))(std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE | SIGHASH_ANYONECANPAY));
971  std::string strHashType = params[3].get_str();
972  if (mapSigHashValues.count(strHashType))
973  nHashType = mapSigHashValues[strHashType];
974  else
975  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
976  }
977 
978  bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
979 
980  // Script verification errors
981  UniValue vErrors(UniValue::VARR);
982 
983  // Sign what we can:
984  for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
985  CTxIn& txin = mergedTx.vin[i];
986  const CCoins* coins = view.AccessCoins(txin.prevout.hash);
987  if (Params().IsRegTestNet()) {
988  if (mapPrevOut.count(txin.prevout) == 0)
989  {
990  TxInErrorToJSON(txin, vErrors, "Input not found");
991  continue;
992  }
993  } else {
994  if (coins == NULL || !coins->IsAvailable(txin.prevout.n)) {
995  TxInErrorToJSON(txin, vErrors, "Input not found or already spent");
996  continue;
997  }
998  }
999  const CScript& prevPubKey = (Params().IsRegTestNet() ? mapPrevOut[txin.prevout] : coins->vout[txin.prevout.n].scriptPubKey);
1000 
1001  txin.scriptSig.clear();
1002  // Only sign SIGHASH_SINGLE if there's a corresponding output:
1003  if (!fHashSingle || (i < mergedTx.vout.size()))
1004  SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
1005 
1006  // ... and merge in other signatures:
1007  for (const CMutableTransaction& txv : txVariants) {
1008  txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
1009  }
1010  ScriptError serror = SCRIPT_ERR_OK;
1011  if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&mergedTx, i), &serror)) {
1012  TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));
1013  }
1014  }
1015  bool fComplete = vErrors.empty();
1016 
1017  UniValue result(UniValue::VOBJ);
1018  result.push_back(Pair("hex", EncodeHexTx(mergedTx)));
1019  result.push_back(Pair("complete", fComplete));
1020  if (!vErrors.empty()) {
1021  result.push_back(Pair("errors", vErrors));
1022  }
1023 
1024  return result;
1025 }
1026 
1027 UniValue sendrawtransaction(const UniValue& params, bool fHelp)
1028 {
1029  if (fHelp || params.size() < 1 || params.size() > 2)
1030  throw std::runtime_error(
1031  "sendrawtransaction \"hexstring\" ( allowhighfees )\n"
1032  "\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
1033  "\nAlso see createrawtransaction and signrawtransaction calls.\n"
1034  "\nArguments:\n"
1035  "1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
1036  "2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
1037  "\nResult:\n"
1038  "\"hex\" (string) The transaction hash in hex\n"
1039  "\nExamples:\n"
1040  "\nCreate a transaction\n" +
1041  HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
1042  "Sign the transaction, and get back the hex\n" + HelpExampleCli("signrawtransaction", "\"myhex\"") +
1043  "\nSend the transaction (signed hex)\n" + HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
1044  "\nAs a json rpc call\n" + HelpExampleRpc("sendrawtransaction", "\"signedhex\""));
1045 
1046  RPCTypeCheck(params, boost::assign::list_of(UniValue::VSTR)(UniValue::VBOOL));
1047 
1048  // parse hex string from parameter
1049  CTransaction tx;
1050  if (!DecodeHexTx(tx, params[0].get_str()))
1051  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
1052  uint256 hashTx = tx.GetHash();
1053 
1054  bool fOverrideFees = false;
1055  if (params.size() > 1)
1056  fOverrideFees = params[1].get_bool();
1057 
1059  CCoinsViewCache& view = *pcoinsTip;
1060  const CCoins* existingCoins = view.AccessCoins(hashTx);
1061  bool fHaveMempool = mempool.exists(hashTx);
1062  bool fHaveChain = existingCoins && existingCoins->nHeight < 1000000000;
1063  if (!fHaveMempool && !fHaveChain) {
1064  // push to local node and sync with wallets
1065  CValidationState state;
1066  if (!AcceptToMemoryPool(mempool, state, tx, false, NULL, !fOverrideFees)) {
1067  if (state.IsInvalid())
1068  throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
1069  else
1071  }
1072  } else if (fHaveChain) {
1073  throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
1074  }
1075  RelayTransaction(tx);
1076 
1077  return hashTx.GetHex();
1078 }
1079 
CBlockIndex::GetBlockTime
int64_t GetBlockTime() const
Definition: chain.h:364
CCoinsViewBacked::SetBackend
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:77
CTxIn
An input of a transaction.
Definition: transaction.h:83
CKeyStore
A virtual base class for key stores.
Definition: keystore.h:21
RPC_MISC_ERROR
@ RPC_MISC_ERROR
General application defined errors.
Definition: protocol.h:40
LOCK2
#define LOCK2(cs1, cs2)
Definition: sync.h:183
SIGHASH_ANYONECANPAY
@ SIGHASH_ANYONECANPAY
Definition: interpreter.h:27
CMutableTransaction::vin
std::vector< CTxIn > vin
Definition: transaction.h:387
UINT256_ZERO
const uint256 UINT256_ZERO
constant uint256 instances
Definition: uint256.h:129
createrawtransaction
UniValue createrawtransaction(const UniValue &params, bool fHelp)
Definition: rawtransaction.cpp:557
UniValue::VOBJ
@ VOBJ
Definition: univalue.h:21
CBitcoinSecret::GetKey
CKey GetKey()
Definition: base58.cpp:304
UniValue::get_bool
bool get_bool() const
Definition: univalue.cpp:302
getrawtransaction
UniValue getrawtransaction(const UniValue &params, bool fHelp)
Definition: rawtransaction.cpp:252
CWallet::mapWallet
std::map< uint256, CWalletTx > mapWallet
Definition: wallet.h:344
transaction.h
CCoinsViewCache::ModifyCoins
CCoinsModifier ModifyCoins(const uint256 &txid)
Return a modifiable reference to a CCoins.
Definition: coins.cpp:123
BLOCK_HAVE_DATA
@ BLOCK_HAVE_DATA
Definition: chain.h:148
CWallet::RevealTxOutAmount
bool RevealTxOutAmount(const CTransaction &tx, const CTxOut &out, CAmount &amount, CKey &) const
Definition: wallet.cpp:7047
CWallet::IsMine
isminetype IsMine(const CTxIn &txin) const
Definition: wallet.cpp:1333
base_uint::GetHex
std::string GetHex() const
Definition: arith_uint256.cpp:155
SCRIPT_ERR_OK
@ SCRIPT_ERR_OK
Definition: script_error.h:11
RPC_TRANSACTION_REJECTED
@ RPC_TRANSACTION_REJECTED
Definition: protocol.h:56
ValueFromAmount
UniValue ValueFromAmount(const CAmount &amount)
Definition: server.cpp:118
chainActive
CChain chainActive
The currently-connected chain of blocks.
Definition: main.cpp:70
COutPoint::hash
uint256 hash
Definition: transaction.h:39
GetScriptForDestination
CScript GetScriptForDestination(const CTxDestination &dest)
Definition: standard.cpp:285
CBitcoinAddress
base58-encoded PRCY addresses.
Definition: base58.h:109
RPC_INVALID_PARAMETER
@ RPC_INVALID_PARAMETER
Ran out of memory during operation.
Definition: protocol.h:45
uint256.h
CTxMemPool::exists
bool exists(uint256 hash)
Definition: txmempool.h:179
sendrawtransaction
UniValue sendrawtransaction(const UniValue &params, bool fHelp)
Definition: rawtransaction.cpp:1027
signrawtransaction
UniValue signrawtransaction(const UniValue &params, bool fHelp)
Definition: rawtransaction.cpp:774
ScriptErrorString
const char * ScriptErrorString(const ScriptError serror)
Definition: script_error.cpp:8
CCoins::IsAvailable
bool IsAvailable(unsigned int nPos) const
check whether a particular output is still available
Definition: coins.h:275
CBlockIndex::nHeight
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:181
CTransaction::nLockTime
const uint32_t nLockTime
Definition: transaction.h:287
wallet.h
GetSerializeSize
unsigned int GetSerializeSize(char a, int, int=0)
Definition: serialize.h:194
UniValue::isNull
bool isNull() const
Definition: univalue.h:77
CCoins::nHeight
int nHeight
at which height this transaction was included in the active block chain
Definition: coins.h:88
CBlockIndex::nStatus
unsigned int nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:205
RPCTypeCheck
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:70
CScript::IsPayToScriptHash
bool IsPayToScriptHash() const
Definition: script.cpp:235
CValidationState::GetRejectReason
std::string GetRejectReason() const
Definition: validation.h:87
UniValue::isNum
bool isNum() const
Definition: univalue.h:82
SER_NETWORK
@ SER_NETWORK
Definition: serialize.h:159
CScript::clear
void clear()
Definition: script.h:634
CChainParams::IsRegTestNet
bool IsRegTestNet() const
Definition: chainparams.h:104
core_io.h
CBlockHeader::GetHash
uint256 GetHash() const
Definition: block.cpp:80
RPC_TRANSACTION_ALREADY_IN_CHAIN
@ RPC_TRANSACTION_ALREADY_IN_CHAIN
Definition: protocol.h:57
MutableTransactionSignatureChecker
Definition: interpreter.h:119
UniValue
Definition: univalue.h:19
CPubKey::GetHex
std::string GetHex() const
Definition: pubkey.h:193
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:269
ScriptError
enum ScriptError_t ScriptError
CBitcoinSecret
A base58-encoded secret key.
Definition: base58.h:131
CTransaction::txType
uint32_t txType
Definition: transaction.h:294
MaskValue::mask
uint256 mask
Definition: transaction.h:151
CValidationState::IsInvalid
bool IsInvalid() const
Definition: validation.h:66
HelpRequiringPassphrase
std::string HelpRequiringPassphrase()
Definition: rpcwallet.cpp:32
ENABLE_WALLET
#define ENABLE_WALLET
Definition: prcycoin-config.h:39
CCoinsView
Abstract view on the open txout dataset.
Definition: coins.h:346
r
void const uint64_t uint64_t * r
Definition: field_5x52_asm_impl.h:10
AcceptToMemoryPool
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransaction &tx, bool fLimitFree, bool *pfMissingInputs, bool fRejectInsaneFee, bool ignoreFees)
(try to) add transaction to memory pool
Definition: main.cpp:1579
CTxIn::nSequence
uint32_t nSequence
Definition: transaction.h:88
CTxOut::nValue
CAmount nValue
Definition: transaction.h:167
UniValue::get_str
const std::string & get_str() const
Definition: univalue.cpp:309
cs_main
RecursiveMutex cs_main
Global state.
Definition: main.cpp:65
CKey::begin
const unsigned char * begin() const
Definition: key.h:100
RPC_DESERIALIZATION_ERROR
@ RPC_DESERIALIZATION_ERROR
Database error.
Definition: protocol.h:47
prevector::end
iterator end()
Definition: prevector.h:292
CTransaction::IsCoinBase
bool IsCoinBase() const
Definition: transaction.h:359
CCoins::vout
std::vector< CTxOut > vout
unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are d...
Definition: coins.h:85
GetTxnOutputType
const char * GetTxnOutputType(txnouttype t)
Definition: standard.cpp:20
prevector::push_back
void push_back(const T &value)
Definition: prevector.h:411
CMutableTransaction::nLockTime
uint32_t nLockTime
Definition: transaction.h:389
UniValue::get_int64
int64_t get_int64() const
Definition: univalue.cpp:326
UniValue::get_obj
const UniValue & get_obj() const
Definition: univalue.cpp:346
CTxMemPool::cs
RecursiveMutex cs
sum of all mempool tx' byte sizes
Definition: txmempool.h:135
AssertLockNotHeld
#define AssertLockNotHeld(cs)
Definition: sync.h:72
RPCTypeCheckObj
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValue::VType > &typesExpected, bool fAllowNull)
Check for expected keys/value types in an Object.
Definition: server.cpp:86
CTxOut
An output of a transaction.
Definition: transaction.h:164
CBlockHeader::GetBlockTime
int64_t GetBlockTime() const
Definition: block.h:135
ParseHexV
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string strName)
Definition: server.cpp:144
GetTransaction
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow, CBlockIndex *blockIndex)
Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock.
Definition: main.cpp:2010
init.h
CTransaction::vout
std::vector< CTxOut > vout
Definition: transaction.h:286
decoderawtransaction
UniValue decoderawtransaction(const UniValue &params, bool fHelp)
Definition: rawtransaction.cpp:658
CTxOut::scriptPubKey
CScript scriptPubKey
Definition: transaction.h:168
UniValue::VBOOL
@ VBOOL
Definition: univalue.h:21
univalue.h
HexStr
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
Definition: utilstrencodings.h:85
CKey::IsValid
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:104
sign.h
DecodeHexTx
bool DecodeHexTx(CTransaction &tx, const std::string &strHexTx)
Definition: core_read.cpp:63
CValidationState::GetRejectCode
unsigned char GetRejectCode() const
Definition: validation.h:86
CCoinsModifier
A reference to a mutable cache entry.
Definition: coins.h:398
CWallet::outpointToKeyImages
std::map< std::string, CKeyImage > outpointToKeyImages
Definition: wallet.h:368
JSONRPCError
UniValue JSONRPCError(int code, const std::string &message)
Definition: protocol.cpp:60
CAmount
int64_t CAmount
Amount in PRCY (Can be negative)
Definition: amount.h:17
standard.h
pcoinsTip
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: main.cpp:1130
CTransaction::nTxFee
CAmount nTxFee
Definition: transaction.h:298
RPC_INVALID_BLOCK_HEIGHT
@ RPC_INVALID_BLOCK_HEIGHT
Client still warming up.
Definition: protocol.h:52
mempool
CTxMemPool mempool(::minRelayTxFee)
CBitcoinSecret::SetString
bool SetString(const char *pszSecret)
Definition: base58.cpp:319
CBasicKeyStore::AddCScript
virtual bool AddCScript(const CScript &redeemScript)
Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki.
Definition: keystore.cpp:34
CTxIn::decoys
std::vector< COutPoint > decoys
Definition: transaction.h:98
UniValue::getKeys
const std::vector< std::string > & getKeys() const
Definition: univalue.cpp:288
keystore.h
HelpExampleRpc
std::string HelpExampleRpc(std::string methodname, std::string args)
Definition: server.cpp:607
UniValue::VNUM
@ VNUM
Definition: univalue.h:21
uint256
256-bit unsigned big integer.
Definition: uint256.h:38
AmountFromValue
CAmount AmountFromValue(const UniValue &value)
Definition: server.cpp:107
MaskValue::amount
uint256 amount
Definition: transaction.h:150
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:363
base_uint::IsNull
bool IsNull() const
Definition: arith_uint256.h:312
SIGHASH_NONE
@ SIGHASH_NONE
Definition: interpreter.h:25
CBasicKeyStore::GetCScript
virtual bool GetCScript(const CScriptID &hash, CScript &redeemScriptOut) const
Definition: keystore.cpp:50
ExtractDestination
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Definition: standard.cpp:199
ParseHashV
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: server.cpp:127
CCoinsViewCache::AccessCoins
const CCoins * AccessCoins(const uint256 &txid) const
Return a pointer to CCoins in the cache, or NULL if not found.
Definition: coins.cpp:145
CTxDestination
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:81
CChain::Height
int Height() const
Return the maximal height in the chain.
Definition: chain.h:641
HelpExampleCli
std::string HelpExampleCli(std::string methodname, std::string args)
Definition: server.cpp:603
RPC_INVALID_ADDRESS_OR_KEY
@ RPC_INVALID_ADDRESS_OR_KEY
Unexpected type was passed as parameter.
Definition: protocol.h:43
RelayTransaction
void RelayTransaction(const CTransaction &tx)
Definition: net.cpp:2028
CBlock::vtx
std::vector< CTransaction > vtx
Definition: block.h:146
VerifyScript
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, unsigned int flags, const BaseSignatureChecker &checker, ScriptError *serror)
Definition: interpreter.cpp:1163
fTxIndex
bool fTxIndex
Definition: main.cpp:82
CBlock
Definition: block.h:142
CMutableTransaction::vout
std::vector< CTxOut > vout
Definition: transaction.h:388
strprintf
#define strprintf
Definition: tinyformat.h:1056
TxToJSON
void TxToJSON(const CTransaction &tx, const uint256 hashBlock, UniValue &entry)
Definition: rawtransaction.cpp:66
CPubKey
An encapsulated public key.
Definition: pubkey.h:37
CWallet::AvailableCoins
bool AvailableCoins(std::vector< COutput > &vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl=NULL, bool fIncludeZeroValue=false, AvailableCoinsType nCoinType=ALL_COINS, bool fUseIX=false)
populate vCoins with vector of available COutputs.
Definition: wallet.cpp:2490
CWallet::GetTransactionType
std::string GetTransactionType(const CTransaction &tx)
Definition: wallet.cpp:910
UniValue::get_int
int get_int() const
Definition: univalue.cpp:316
CKey
An encapsulated private key.
Definition: key.h:39
CTxOut::maskValue
MaskValue maskValue
Definition: transaction.h:176
CCoinsViewCache
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:414
CKeyStore::AddKey
virtual bool AddKey(const CKey &key)
Definition: keystore.cpp:22
utilmoneystr.h
PoSBlockInfoToJSON
void PoSBlockInfoToJSON(const uint256 hashBlock, int64_t nTime, int height, UniValue &entry)
Definition: rawtransaction.cpp:59
main.h
COutPoint::n
uint32_t n
Definition: transaction.h:40
CTransaction::vin
std::vector< CTxIn > vin
Definition: transaction.h:285
EnsureWalletIsUnlocked
void EnsureWalletIsUnlocked(bool fAllowAnonOnly=false)
Definition: rpcwallet.cpp:45
LOCK
#define LOCK(cs)
Definition: sync.h:182
script_error.h
key
CKey key
Definition: bip38tooldialog.cpp:173
CScript::ToString
std::string ToString() const
Definition: script.cpp:266
CWalletTx
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:792
listunspent
UniValue listunspent(const UniValue &params, bool fHelp)
ReadBlockFromDisk
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos)
Definition: main.cpp:2101
CTxIn::prevout
COutPoint prevout
Definition: transaction.h:86
CTransaction::paymentID
uint64_t paymentID
Definition: transaction.h:292
SignSignature
bool SignSignature(const CKeyStore &keystore, const CScript &fromPubKey, CMutableTransaction &txTo, unsigned int nIn, int nHashType)
Definition: sign.cpp:96
CCoinsViewMemPool
CCoinsView that brings transactions from a memorypool into view.
Definition: txmempool.h:202
CTxIn::scriptSig
CScript scriptSig
Definition: transaction.h:87
prevector::begin
iterator begin()
Definition: prevector.h:290
UniValue::push_back
bool push_back(const UniValue &val)
Definition: univalue.cpp:173
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:463
CChain::Contains
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:626
UniValue::empty
bool empty() const
Definition: univalue.h:67
CWallet::cs_wallet
RecursiveMutex cs_wallet
Definition: wallet.h:301
SIGHASH_SINGLE
@ SIGHASH_SINGLE
Definition: interpreter.h:26
CDataStream
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:34
ParseHexO
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string strKey)
Definition: server.cpp:153
base58.h
CCoins
Definition: coins.h:77
UniValue::size
size_t size() const
Definition: univalue.h:69
CBasicKeyStore
Basic key store, that keeps keys in an address->secret map.
Definition: keystore.h:57
script.h
CTxOut::commitment
std::vector< unsigned char > commitment
Definition: transaction.h:178
CTransaction::GetHash
const uint256 & GetHash() const
Definition: transaction.h:342
EncodeHexTx
std::string EncodeHexTx(const CTransaction &tx)
Definition: core_write.cpp:55
COutPoint
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:36
find_value
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:279
txnouttype
txnouttype
Definition: standard.h:57
CDataStream::empty
bool empty() const
Definition: streams.h:121
CTransaction::nVersion
const int32_t nVersion
Definition: transaction.h:284
SIGHASH_ALL
@ SIGHASH_ALL
Definition: interpreter.h:24
CTransaction::hasPaymentID
char hasPaymentID
Definition: transaction.h:291
CMutableTransaction
A mutable version of CTransaction.
Definition: transaction.h:384
UniValue::get_array
const UniValue & get_array() const
Definition: univalue.cpp:353
UniValue::VARR
@ VARR
Definition: univalue.h:21
getunspentcount
UniValue getunspentcount(const UniValue &params, bool fHelp)
CBitcoinAddress::IsValid
bool IsValid() const
Definition: base58.cpp:254
CombineSignatures
CScript CombineSignatures(const CScript &scriptPubKey, const CTransaction &txTo, unsigned int nIn, const CScript &scriptSig1, const CScript &scriptSig2)
Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders, combine them intellig...
Definition: sign.cpp:249
CTxIn::keyImage
CKeyImage keyImage
Definition: transaction.h:97
server.h
net.h
ExtractDestinations
bool ExtractDestinations(const CScript &scriptPubKey, txnouttype &typeRet, std::vector< CTxDestination > &addressRet, int &nRequiredRet)
Definition: standard.cpp:223
CBlockIndex
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:162
CScriptID
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:20
CBitcoinAddress::Get
CTxDestination Get() const
Definition: base58.cpp:267
pwalletMain
CWallet * pwalletMain
Definition: wallet.cpp:49
COutput
Definition: wallet.h:922
UniValue::VSTR
@ VSTR
Definition: univalue.h:21
CValidationState
Capture information about block/transaction validation.
Definition: validation.h:23
ScriptPubKeyToJSON
void ScriptPubKeyToJSON(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
Definition: rawtransaction.cpp:34
CWallet::getCTxOutValue
CAmount getCTxOutValue(const CTransaction &tx, const CTxOut &out) const
Definition: wallet.cpp:7202
getrawtransactionbyblockheight
UniValue getrawtransactionbyblockheight(const UniValue &params, bool fHelp)
Definition: rawtransaction.cpp:200
CTransaction::hash
const uint256 hash
Memory only.
Definition: transaction.h:273
CWallet::mapAddressBook
std::map< CTxDestination, CAddressBookData > mapAddressBook
Definition: wallet.h:354
CCryptoKeyStore::IsLocked
bool IsLocked() const
Definition: crypter.h:159
RPC_TRANSACTION_ERROR
@ RPC_TRANSACTION_ERROR
Invalid block height.
Definition: protocol.h:55
mapBlockIndex
BlockMap mapBlockIndex
Definition: main.cpp:67
CTxOut::txPub
std::vector< unsigned char > txPub
Definition: transaction.h:173
UniValue::isObject
bool isObject() const
Definition: univalue.h:84
decodescript
UniValue decodescript(const UniValue &params, bool fHelp)
Definition: rawtransaction.cpp:722
ParseHashO
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: server.cpp:140
base_uint::ToString
std::string ToString() const
Definition: arith_uint256.cpp:199