Fabcoin Core  0.16.2
P2P Digital Currency
rawtransaction.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2017 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <base58.h>
7 #include <chain.h>
8 #include <coins.h>
9 #include <consensus/validation.h>
10 #include <core_io.h>
11 #include <init.h>
12 #include <keystore.h>
13 #include <validation.h>
14 #include <merkleblock.h>
15 #include <net.h>
16 #include <policy/policy.h>
17 #include <policy/rbf.h>
18 #include <primitives/transaction.h>
19 #include <rpc/server.h>
20 #include <script/script.h>
21 #include <script/script_error.h>
22 #include <script/sign.h>
23 #include <script/standard.h>
24 #include <txmempool.h>
25 #include <uint256.h>
26 #include <utilstrencodings.h>
27 #include <utilmoneystr.h>
28 #ifdef ENABLE_WALLET
29 #include <wallet/rpcwallet.h>
30 #include <wallet/wallet.h>
31 #endif
32 
33 #include <stdint.h>
34 
35 #include <univalue.h>
36 
37 
38 void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry)
39 {
40  // Call into TxToUniv() in fabcoin-common to decode the transaction hex.
41  //
42  // Blockchain contextual information (confirmations and blocktime) is not
43  // available to code in fabcoin-common, so we query them here and push the
44  // data into the returned UniValue.
45  TxToUniv(tx, uint256(), entry, true, RPCSerializationFlags());
46 
47  if (!hashBlock.IsNull()) {
48  entry.push_back(Pair("blockhash", hashBlock.GetHex()));
49  BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
50  if (mi != mapBlockIndex.end() && (*mi).second) {
51  CBlockIndex* pindex = (*mi).second;
52  if (chainActive.Contains(pindex)) {
53  entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
54  entry.push_back(Pair("time", pindex->GetBlockTime()));
55  entry.push_back(Pair("blocktime", pindex->GetBlockTime()));
56  }
57  else
58  entry.push_back(Pair("confirmations", 0));
59  }
60  }
61 }
62 
64  if (request.fHelp || request.params.size() < 1 || request.params.size() > 1)
65  throw std::runtime_error(
66  "gethexaddress \"address\"\n"
67 
68  "\nConverts a base58 pubkeyhash address to a hex address for use in smart contracts.\n"
69 
70  "\nArguments:\n"
71  "1. \"address\" (string, required) The base58 address\n"
72 
73  "\nResult:\n"
74  "\"hexaddress\" (string) The raw hex pubkeyhash address for use in smart contracts\n"
75 
76  "\nExamples:\n"
77  + HelpExampleCli("gethexaddress", "\"address\"")
78  + HelpExampleRpc("gethexaddress", "\"address\"")
79  );
80 
81  CFabcoinAddress address(request.params[0].get_str());
82  if (!address.IsValid())
83  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Fabcoin address");
84 
85  if(!address.IsPubKeyHash())
86  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Only pubkeyhash addresses are supported");
87 
88  return boost::get<CKeyID>(address.Get()).GetReverseHex();
89 }
90 
92  if (request.fHelp || request.params.size() < 1 || request.params.size() > 1)
93  throw std::runtime_error(
94  "fromhexaddress \"hexaddress\"\n"
95 
96  "\nConverts a raw hex address to a base58 pubkeyhash address\n"
97 
98  "\nArguments:\n"
99  "1. \"hexaddress\" (string, required) The raw hex address\n"
100 
101  "\nResult:\n"
102  "\"address\" (string) The base58 pubkeyhash address\n"
103 
104  "\nExamples:\n"
105  + HelpExampleCli("fromhexaddress", "\"hexaddress\"")
106  + HelpExampleRpc("fromhexaddress", "\"hexaddress\"")
107  );
108  if (request.params[0].get_str().size() != 40)
109  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid pubkeyhash hex size (should be 40 hex characters)");
110  CKeyID raw;
111  raw.SetReverseHex(request.params[0].get_str());
113 
114  return address.ToString();
115 }
116 
118 {
119  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
120  throw std::runtime_error(
121  "getrawtransaction \"txid\" ( verbose )\n"
122 
123  "\nNOTE: By default this function only works for mempool transactions. If the -txindex option is\n"
124  "enabled, it also works for blockchain transactions.\n"
125  "DEPRECATED: for now, it also works for transactions with unspent outputs.\n"
126 
127  "\nReturn the raw transaction data.\n"
128  "\nIf verbose is 'true', returns an Object with information about 'txid'.\n"
129  "If verbose is 'false' or omitted, returns a string that is serialized, hex-encoded data for 'txid'.\n"
130 
131  "\nArguments:\n"
132  "1. \"txid\" (string, required) The transaction id\n"
133  "2. verbose (bool, optional, default=false) If false, return a string, otherwise return a json object\n"
134 
135  "\nResult (if verbose is not set or set to false):\n"
136  "\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
137 
138  "\nResult (if verbose is set to true):\n"
139  "{\n"
140  " \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
141  " \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
142  " \"hash\" : \"id\", (string) The transaction hash (differs from txid for witness transactions)\n"
143  " \"size\" : n, (numeric) The serialized transaction size\n"
144  " \"vsize\" : n, (numeric) The virtual transaction size (differs from size for witness transactions)\n"
145  " \"version\" : n, (numeric) The version\n"
146  " \"locktime\" : ttt, (numeric) The lock time\n"
147  " \"vin\" : [ (array of json objects)\n"
148  " {\n"
149  " \"txid\": \"id\", (string) The transaction id\n"
150  " \"vout\": n, (numeric) \n"
151  " \"scriptSig\": { (json object) The script\n"
152  " \"asm\": \"asm\", (string) asm\n"
153  " \"hex\": \"hex\" (string) hex\n"
154  " },\n"
155  " \"sequence\": n (numeric) The script sequence number\n"
156  " \"txinwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n"
157  " }\n"
158  " ,...\n"
159  " ],\n"
160  " \"vout\" : [ (array of json objects)\n"
161  " {\n"
162  " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
163  " \"n\" : n, (numeric) index\n"
164  " \"scriptPubKey\" : { (json object)\n"
165  " \"asm\" : \"asm\", (string) the asm\n"
166  " \"hex\" : \"hex\", (string) the hex\n"
167  " \"reqSigs\" : n, (numeric) The required sigs\n"
168  " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
169  " \"addresses\" : [ (json array of string)\n"
170  " \"address\" (string) fabcoin address\n"
171  " ,...\n"
172  " ]\n"
173  " }\n"
174  " }\n"
175  " ,...\n"
176  " ],\n"
177  " \"blockhash\" : \"hash\", (string) the block hash\n"
178  " \"confirmations\" : n, (numeric) The confirmations\n"
179  " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
180  " \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
181  "}\n"
182 
183  "\nExamples:\n"
184  + HelpExampleCli("getrawtransaction", "\"mytxid\"")
185  + HelpExampleCli("getrawtransaction", "\"mytxid\" true")
186  + HelpExampleRpc("getrawtransaction", "\"mytxid\", true")
187  );
188 
189  LOCK(cs_main);
190 
191  uint256 hash = ParseHashV(request.params[0], "parameter 1");
192 
193  // Accept either a bool (true) or a num (>=1) to indicate verbose output.
194  bool fVerbose = false;
195  if (!request.params[1].isNull()) {
196  if (request.params[1].isNum()) {
197  if (request.params[1].get_int() != 0) {
198  fVerbose = true;
199  }
200  }
201  else if(request.params[1].isBool()) {
202  if(request.params[1].isTrue()) {
203  fVerbose = true;
204  }
205  }
206  else {
207  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid type provided. Verbose parameter must be a boolean.");
208  }
209  }
210 
211  CTransactionRef tx;
212  uint256 hashBlock;
213  if (!GetTransaction(hash, tx, Params().GetConsensus(), hashBlock, true))
214  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string(fTxIndex ? "No such mempool or blockchain transaction"
215  : "No such mempool transaction. Use -txindex to enable blockchain transaction queries") +
216  ". Use gettransaction for wallet transactions.");
217 
218  if (!fVerbose)
219  return EncodeHexTx(*tx, RPCSerializationFlags());
220 
221  UniValue result(UniValue::VOBJ);
222  TxToJSON(*tx, hashBlock, result);
223  return result;
224 }
225 
227 {
228  if (request.fHelp || (request.params.size() != 1 && request.params.size() != 2))
229  throw std::runtime_error(
230  "gettxoutproof [\"txid\",...] ( blockhash )\n"
231  "\nReturns a hex-encoded proof that \"txid\" was included in a block.\n"
232  "\nNOTE: By default this function only works sometimes. This is when there is an\n"
233  "unspent output in the utxo for this transaction. To make it always work,\n"
234  "you need to maintain a transaction index, using the -txindex command line option or\n"
235  "specify the block in which the transaction is included manually (by blockhash).\n"
236  "\nArguments:\n"
237  "1. \"txids\" (string) A json array of txids to filter\n"
238  " [\n"
239  " \"txid\" (string) A transaction hash\n"
240  " ,...\n"
241  " ]\n"
242  "2. \"blockhash\" (string, optional) If specified, looks for txid in the block with this hash\n"
243  "\nResult:\n"
244  "\"data\" (string) A string that is a serialized, hex-encoded data for the proof.\n"
245  );
246 
247  std::set<uint256> setTxids;
248  uint256 oneTxid;
249  UniValue txids = request.params[0].get_array();
250  for (unsigned int idx = 0; idx < txids.size(); idx++) {
251  const UniValue& txid = txids[idx];
252  if (txid.get_str().length() != 64 || !IsHex(txid.get_str()))
253  throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid txid ")+txid.get_str());
254  uint256 hash(uint256S(txid.get_str()));
255  if (setTxids.count(hash))
256  throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated txid: ")+txid.get_str());
257  setTxids.insert(hash);
258  oneTxid = hash;
259  }
260 
261  LOCK(cs_main);
262 
263  CBlockIndex* pblockindex = nullptr;
264 
265  uint256 hashBlock;
266  if (!request.params[1].isNull())
267  {
268  hashBlock = uint256S(request.params[1].get_str());
269  if (!mapBlockIndex.count(hashBlock))
270  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
271  pblockindex = mapBlockIndex[hashBlock];
272  } else {
273  // Loop through txids and try to find which block they're in. Exit loop once a block is found.
274  for (const auto& tx : setTxids) {
275  const Coin& coin = AccessByTxid(*pcoinsTip, tx);
276  if (!coin.IsSpent()) {
277  pblockindex = chainActive[coin.nHeight];
278  break;
279  }
280  }
281  }
282 
283  if (pblockindex == nullptr)
284  {
285  CTransactionRef tx;
286  if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, false) || hashBlock.IsNull())
287  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block");
288  if (!mapBlockIndex.count(hashBlock))
289  throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt");
290  pblockindex = mapBlockIndex[hashBlock];
291  }
292 
293  CBlock block;
294  if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
295  throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
296 
297  unsigned int ntxFound = 0;
298  for (const auto& tx : block.vtx)
299  if (setTxids.count(tx->GetHash()))
300  ntxFound++;
301  if (ntxFound != setTxids.size())
302  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Not all transactions found in specified or retrieved block");
303 
304  CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
305  CMerkleBlock mb(block, setTxids);
306  ssMB << mb;
307  std::string strHex = HexStr(ssMB.begin(), ssMB.end());
308  return strHex;
309 }
310 
312 {
313  if (request.fHelp || request.params.size() != 1)
314  throw std::runtime_error(
315  "verifytxoutproof \"proof\"\n"
316  "\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n"
317  "and throwing an RPC error if the block is not in our best chain\n"
318  "\nArguments:\n"
319  "1. \"proof\" (string, required) The hex-encoded proof generated by gettxoutproof\n"
320  "\nResult:\n"
321  "[\"txid\"] (array, strings) The txid(s) which the proof commits to, or empty array if the proof is invalid\n"
322  );
323 
324  CDataStream ssMB(ParseHexV(request.params[0], "proof"), SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
325  CMerkleBlock merkleBlock;
326  ssMB >> merkleBlock;
327 
329 
330  std::vector<uint256> vMatch;
331  std::vector<unsigned int> vIndex;
332  if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot)
333  return res;
334 
335  LOCK(cs_main);
336 
337  if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
338  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
339 
340  for (const uint256& hash : vMatch)
341  res.push_back(hash.GetHex());
342  return res;
343 }
344 
346 {
347  if (request.fHelp || request.params.size() < 2 || request.params.size() > 4)
348  throw std::runtime_error(
349  "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,\"data\":\"hex\",...} ( locktime ) ( replaceable )\n"
350  "\nCreate a transaction spending the given inputs and creating new outputs.\n"
351  "Outputs can be addresses or data.\n"
352  "Returns hex-encoded raw transaction.\n"
353  "Note that the transaction's inputs are not signed, and\n"
354  "it is not stored in the wallet or transmitted to the network.\n"
355 
356  "\nArguments:\n"
357  "1. \"inputs\" (array, required) A json array of json objects\n"
358  " [\n"
359  " {\n"
360  " \"txid\":\"id\", (string, required) The transaction id\n"
361  " \"vout\":n, (numeric, required) The output number\n"
362  " \"sequence\":n (numeric, optional) The sequence number\n"
363  " } \n"
364  " ,...\n"
365  " ]\n"
366  "2. \"outputs\" (object, required) a json object with outputs\n"
367  " {\n"
368  " \"address\": x.xxx, (numeric or string, required) The key is the fabcoin address, the numeric value (can be string) is the " + CURRENCY_UNIT + " amount\n"
369  " \"data\": \"hex\" (string, required) The key is \"data\", the value is hex encoded data\n"
370  " \"contract\":{\n"
371  " \"contractAddress\":\"address\", (string, required) Valid contract address (valid hash160 hex data)\n"
372  " \"data\":\"hex\", (string, required) Hex data to add in the call output\n"
373  " \"amount\":x.xxx, (numeric, optional) Value in fasc to send with the call, should be a valid amount, default 0\n"
374  " \"gasLimit\":x, (numeric, optional) The gas limit for the transaction\n"
375  " \"gasPrice\":x.xxx (numeric, optional) The gas price for the transaction\n"
376  " } \n"
377  " ,...\n"
378  " }\n"
379  "3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n"
380  "4. replaceable (boolean, optional, default=false) Marks this transaction as BIP125 replaceable.\n"
381  " Allows this transaction to be replaced by a transaction with higher fees. If provided, it is an error if explicit sequence numbers are incompatible.\n"
382  "\nResult:\n"
383  "\"transaction\" (string) hex string of the transaction\n"
384 
385  "\nExamples:\n"
386  + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"")
387  + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"data\\\":\\\"00010203\\\"}\"")
388  + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"contract\\\":{\\\"contractAddress\\\":\\\"mycontract\\\","
389  "\\\"data\\\":\\\"00\\\", \\\"gasLimit\\\":250000, \\\"gasPrice\\\":0.00000040, \\\"amount\\\":0}}\"")
390  + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")
391  + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"data\\\":\\\"00010203\\\"}\"")
392  + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"contract\\\":{\\\"contractAddress\\\":\\\"mycontract\\\","
393  "\\\"data\\\":\\\"00\\\", \\\"gasLimit\\\":250000, \\\"gasPrice\\\":0.00000040, \\\"amount\\\":0}}\"")
394 
395  );
396 
397  RPCTypeCheck(request.params, {UniValue::VARR, UniValue::VOBJ, UniValue::VNUM}, true);
398  if (request.params[0].isNull() || request.params[1].isNull())
399  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null");
400 
401  UniValue inputs = request.params[0].get_array();
402  UniValue sendTo = request.params[1].get_obj();
403 
404  CMutableTransaction rawTx;
405 
406  if (request.params.size() > 2 && !request.params[2].isNull()) {
407  int64_t nLockTime = request.params[2].get_int64();
408  if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max())
409  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");
410  rawTx.nLockTime = nLockTime;
411  }
412 
413  bool rbfOptIn = request.params.size() > 3 ? request.params[3].isTrue() : false;
414 
415  for (unsigned int idx = 0; idx < inputs.size(); idx++) {
416  const UniValue& input = inputs[idx];
417  const UniValue& o = input.get_obj();
418 
419  uint256 txid = ParseHashO(o, "txid");
420 
421  const UniValue& vout_v = find_value(o, "vout");
422  if (!vout_v.isNum())
423  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
424  int nOutput = vout_v.get_int();
425  if (nOutput < 0)
426  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
427 
428  uint32_t nSequence;
429  if (rbfOptIn) {
430  nSequence = MAX_BIP125_RBF_SEQUENCE;
431  } else if (rawTx.nLockTime) {
432  nSequence = std::numeric_limits<uint32_t>::max() - 1;
433  } else {
435  }
436 
437  // set the sequence number if passed in the parameters object
438  const UniValue& sequenceObj = find_value(o, "sequence");
439  if (sequenceObj.isNum()) {
440  int64_t seqNr64 = sequenceObj.get_int64();
441  if (seqNr64 < 0 || seqNr64 > std::numeric_limits<uint32_t>::max()) {
442  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range");
443  } else {
444  nSequence = (uint32_t)seqNr64;
445  }
446  }
447 
448  CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
449 
450  rawTx.vin.push_back(in);
451  }
452 
453  std::set<CFabcoinAddress> setAddress;
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 if (name_ == "contract") {
463  if ( (uint32_t) chainActive.Height() < (uint32_t) Params().GetConsensus().ContractHeight )
464  throw JSONRPCError(RPC_METHOD_NOT_FOUND, std::string ("This method can only be used after fasc fork, after block ") + std::to_string(Params().GetConsensus().ContractHeight ));
465 
466  // Get the call object
467  UniValue Contract = sendTo[name_];
468  if(!Contract.isObject())
469  throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, need to be object: ")+name_);
470 
471  // Get dgp gas limit and gas price
472  LOCK(cs_main);
473  FascDGP fascDGP(globalState.get(), fGettingValuesDGP);
474  uint64_t blockGasLimit = fascDGP.getBlockGasLimit(chainActive.Height());
475  uint64_t minGasPrice = CAmount(fascDGP.getMinGasPrice(chainActive.Height()));
476  CAmount nGasPrice = (minGasPrice>DEFAULT_GAS_PRICE)?minGasPrice:DEFAULT_GAS_PRICE;
477 
478  // Get the contract address
479  if(!Contract.exists("contractAddress") || !Contract["contractAddress"].isStr())
480  throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, contract address is mandatory."));
481 
482  std::string contractaddress = Contract["contractAddress"].get_str();
483  if(contractaddress.size() != 40 || !CheckHex(contractaddress))
484  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Incorrect contract address");
485 
486  dev::Address addrAccount(contractaddress);
487  if(!globalState->addressInUse(addrAccount))
488  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "contract address does not exist");
489 
490  // Get the contract data
491  if(!Contract.exists("data") || !Contract["data"].isStr())
492  throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, contract data is mandatory."));
493 
494  std::string datahex = Contract["data"].get_str();
495  if(datahex.size() % 2 != 0 || !CheckHex(datahex))
496  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid data (data not hex)");
497 
498  // Get amount
499  CAmount nAmount = 0;
500  if (Contract.exists("amount")){
501  nAmount = AmountFromValue(Contract["amount"]);
502  if (nAmount < 0)
503  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for call contract");
504  }
505 
506  // Get gas limit
507  uint64_t nGasLimit=DEFAULT_GAS_LIMIT_OP_SEND;
508  if (Contract.exists("gasLimit")){
509  nGasLimit = Contract["gasLimit"].get_int64();
510  if (nGasLimit > blockGasLimit)
511  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid value for gasLimit (Maximum is: "+i64tostr(blockGasLimit)+")");
512  if (nGasLimit < MINIMUM_GAS_LIMIT)
513  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid value for gasLimit (Minimum is: "+i64tostr(MINIMUM_GAS_LIMIT)+")");
514  if (nGasLimit <= 0)
515  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid value for gasLimit");
516  }
517 
518  // Get gas price
519  if (Contract.exists("gasPrice")){
520  UniValue uGasPrice = Contract["gasPrice"];
521  if(!ParseMoney(uGasPrice.getValStr(), nGasPrice))
522  {
523  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid value for gasPrice");
524  }
525  CAmount maxRpcGasPrice = gArgs.GetArg("-rpcmaxgasprice", MAX_RPC_GAS_PRICE);
526  if (nGasPrice > (int64_t)maxRpcGasPrice)
527  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid value for gasPrice, Maximum allowed in RPC calls is: "+FormatMoney(maxRpcGasPrice)+" (use -rpcmaxgasprice to change it)");
528  if (nGasPrice < (int64_t)minGasPrice)
529  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid value for gasPrice (Minimum is: "+FormatMoney(minGasPrice)+")");
530  if (nGasPrice <= 0)
531  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid value for gasPrice");
532  }
533 
534  // Add call contract output
535  CScript scriptPubKey = CScript() << CScriptNum(VersionVM::GetEVMDefault().toRaw()) << CScriptNum(nGasLimit) << CScriptNum(nGasPrice) << ParseHex(datahex) << ParseHex(contractaddress) << OP_CALL;
536  CTxOut out(nAmount, scriptPubKey);
537  rawTx.vout.push_back(out);
538  } else {
539  CFabcoinAddress address(name_);
540  if (!address.IsValid())
541  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Fabcoin address: ")+name_);
542 
543  if (setAddress.count(address))
544  throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+name_);
545  setAddress.insert(address);
546 
547  CScript scriptPubKey = GetScriptForDestination(address.Get());
548  CAmount nAmount = AmountFromValue(sendTo[name_]);
549 
550  CTxOut out(nAmount, scriptPubKey);
551  rawTx.vout.push_back(out);
552  }
553  }
554 
555  if (!request.params[3].isNull() && rbfOptIn != SignalsOptInRBF(rawTx)) {
556  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter combination: Sequence number(s) contradict replaceable option");
557  }
558 
559  return EncodeHexTx(rawTx);
560 }
561 
563 {
564  if (request.fHelp || request.params.size() != 1)
565  throw std::runtime_error(
566  "decoderawtransaction \"hexstring\"\n"
567  "\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
568 
569  "\nArguments:\n"
570  "1. \"hexstring\" (string, required) The transaction hex string\n"
571 
572  "\nResult:\n"
573  "{\n"
574  " \"txid\" : \"id\", (string) The transaction id\n"
575  " \"hash\" : \"id\", (string) The transaction hash (differs from txid for witness transactions)\n"
576  " \"size\" : n, (numeric) The transaction size\n"
577  " \"vsize\" : n, (numeric) The virtual transaction size (differs from size for witness transactions)\n"
578  " \"version\" : n, (numeric) The version\n"
579  " \"locktime\" : ttt, (numeric) The lock time\n"
580  " \"vin\" : [ (array of json objects)\n"
581  " {\n"
582  " \"txid\": \"id\", (string) The transaction id\n"
583  " \"vout\": n, (numeric) The output number\n"
584  " \"scriptSig\": { (json object) The script\n"
585  " \"asm\": \"asm\", (string) asm\n"
586  " \"hex\": \"hex\" (string) hex\n"
587  " },\n"
588  " \"txinwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n"
589  " \"sequence\": n (numeric) The script sequence number\n"
590  " }\n"
591  " ,...\n"
592  " ],\n"
593  " \"vout\" : [ (array of json objects)\n"
594  " {\n"
595  " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
596  " \"n\" : n, (numeric) index\n"
597  " \"scriptPubKey\" : { (json object)\n"
598  " \"asm\" : \"asm\", (string) the asm\n"
599  " \"hex\" : \"hex\", (string) the hex\n"
600  " \"reqSigs\" : n, (numeric) The required sigs\n"
601  " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
602  " \"addresses\" : [ (json array of string)\n"
603  " \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) fabcoin address\n"
604  " ,...\n"
605  " ]\n"
606  " }\n"
607  " }\n"
608  " ,...\n"
609  " ],\n"
610  "}\n"
611 
612  "\nExamples:\n"
613  + HelpExampleCli("decoderawtransaction", "\"hexstring\"")
614  + HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
615  );
616 
617  LOCK(cs_main);
618  RPCTypeCheck(request.params, {UniValue::VSTR});
619 
621 
622  if (!DecodeHexTx(mtx, request.params[0].get_str(), true))
623  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
624 
625  UniValue result(UniValue::VOBJ);
626  TxToUniv(CTransaction(std::move(mtx)), uint256(), result, false);
627 
628  return result;
629 }
630 
632 {
633  if (request.fHelp || request.params.size() != 1)
634  throw std::runtime_error(
635  "getcontractaddress \"hexstring\"\n"
636  "\nReturn the expected contract address of a transaction.\n"
637 
638  "\nArguments:\n"
639  "1. \"hexstring\" (string, required) The transaction hex string\n"
640 
641  "\nResult:\n"
642  "\"address\" (string) The fabcoin address of the contract.\n"
643 
644  "\nExamples:\n"
645  + HelpExampleCli("getcontractaddress", "\"hexstring\"")
646  + HelpExampleRpc("getcontractaddress", "\"hexstring\"")
647  );
648 
649  LOCK(cs_main);
650  RPCTypeCheck(request.params, {UniValue::VSTR});
651 
653 
654  if (!DecodeHexTx(mtx, request.params[0].get_str(), true))
655  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
656 
657  std::vector<unsigned char> SHA256TxVout(32);
658  std::vector<unsigned char> contractAddress(20);
659  std::vector<unsigned char> txIdAndVout(mtx.GetHash().begin(), mtx.GetHash().end());
660 
661  /* uint256 GetHash is meant to provide a length 32 array, but reading from GDB
662  * the size and contents of GetHash is nondeterministic; I'm pretty sure it's
663  * picking up garbage from somewhere and throwing it in with the correct
664  * initial 32 chars.
665  * We resize the array after calling constructor to ensure we're getting a hash
666  * of the correct length.
667  */
668  txIdAndVout.resize(32);
669  uint32_t voutNumber = 0;
670  bool txHasOpCreate = false;
671  for (auto txout : mtx.vout) {
672  if (txout.scriptPubKey.HasOpCreate()) {
673  std::vector<unsigned char> voutNumberChrs;
674  if (voutNumberChrs.size() < sizeof(voutNumber))
675  voutNumberChrs.resize(sizeof(voutNumber));
676  std::memcpy(voutNumberChrs.data(), &voutNumber, sizeof(voutNumber));
677  txIdAndVout.insert(txIdAndVout.end(), voutNumberChrs.begin(), voutNumberChrs.end());
678  txHasOpCreate = true;
679  break;
680  }
681  voutNumber++;
682  }
683 
684  if (!txHasOpCreate)
685  throw JSONRPCError(RPC_INVALID_PARAMETER, "Given transaction does not create a contract");
686 
687  CSHA256().Write(txIdAndVout.data(), txIdAndVout.size()).Finalize(SHA256TxVout.data());
688  CRIPEMD160().Write(SHA256TxVout.data(), SHA256TxVout.size()).Finalize(contractAddress.data());
689 
690  UniValue result(UniValue::VOBJ);
691  result.push_back(Pair("address", HexStr(contractAddress)));
692 
693  return result;
694 }
695 
697 {
698  if (request.fHelp || request.params.size() != 1)
699  throw std::runtime_error(
700  "decodescript \"hexstring\"\n"
701  "\nDecode a hex-encoded script.\n"
702  "\nArguments:\n"
703  "1. \"hexstring\" (string) the hex encoded script\n"
704  "\nResult:\n"
705  "{\n"
706  " \"asm\":\"asm\", (string) Script public key\n"
707  " \"hex\":\"hex\", (string) hex encoded public key\n"
708  " \"type\":\"type\", (string) The output type\n"
709  " \"reqSigs\": n, (numeric) The required signatures\n"
710  " \"addresses\": [ (json array of string)\n"
711  " \"address\" (string) fabcoin address\n"
712  " ,...\n"
713  " ],\n"
714  " \"p2sh\",\"address\" (string) address of P2SH script wrapping this redeem script (not returned if the script is already a P2SH).\n"
715  "}\n"
716  "\nExamples:\n"
717  + HelpExampleCli("decodescript", "\"hexstring\"")
718  + HelpExampleRpc("decodescript", "\"hexstring\"")
719  );
720 
721  RPCTypeCheck(request.params, {UniValue::VSTR});
722 
724  CScript script;
725  if (request.params[0].get_str().size() > 0){
726  std::vector<unsigned char> scriptData(ParseHexV(request.params[0], "argument"));
727  script = CScript(scriptData.begin(), scriptData.end());
728  } else {
729  // Empty scripts are valid
730  }
731  ScriptPubKeyToUniv(script, r, false);
732 
733  UniValue type;
734  type = find_value(r, "type");
735 
736  if (type.isStr() && type.get_str() != "scripthash") {
737  // P2SH cannot be wrapped in a P2SH. If this script is already a P2SH,
738  // don't return the address for a P2SH of the P2SH.
739  r.push_back(Pair("p2sh", CFabcoinAddress(CScriptID(script)).ToString()));
740  }
741 
742  return r;
743 }
744 
746 static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)
747 {
748  UniValue entry(UniValue::VOBJ);
749  entry.push_back(Pair("txid", txin.prevout.hash.ToString()));
750  entry.push_back(Pair("vout", (uint64_t)txin.prevout.n));
751  UniValue witness(UniValue::VARR);
752  for (unsigned int i = 0; i < txin.scriptWitness.stack.size(); i++) {
753  witness.push_back(HexStr(txin.scriptWitness.stack[i].begin(), txin.scriptWitness.stack[i].end()));
754  }
755  entry.push_back(Pair("witness", witness));
756  entry.push_back(Pair("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
757  entry.push_back(Pair("sequence", (uint64_t)txin.nSequence));
758  entry.push_back(Pair("error", strMessage));
759  vErrorsRet.push_back(entry);
760 }
761 
763 {
764 
765  if (request.fHelp || request.params.size() != 1)
766  throw std::runtime_error(
767  "combinerawtransaction [\"hexstring\",...]\n"
768  "\nCombine multiple partially signed transactions into one transaction.\n"
769  "The combined transaction may be another partially signed transaction or a \n"
770  "fully signed transaction."
771 
772  "\nArguments:\n"
773  "1. \"txs\" (string) A json array of hex strings of partially signed transactions\n"
774  " [\n"
775  " \"hexstring\" (string) A transaction hash\n"
776  " ,...\n"
777  " ]\n"
778 
779  "\nResult:\n"
780  "\"hex\" (string) The hex-encoded raw transaction with signature(s)\n"
781 
782  "\nExamples:\n"
783  + HelpExampleCli("combinerawtransaction", "[\"myhex1\", \"myhex2\", \"myhex3\"]")
784  );
785 
786 
787  UniValue txs = request.params[0].get_array();
788  std::vector<CMutableTransaction> txVariants(txs.size());
789 
790  for (unsigned int idx = 0; idx < txs.size(); idx++) {
791  if (!DecodeHexTx(txVariants[idx], txs[idx].get_str(), true)) {
792  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed for tx %d", idx));
793  }
794  }
795 
796  if (txVariants.empty()) {
797  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transactions");
798  }
799 
800  // mergedTx will end up with all the signatures; it
801  // starts as a clone of the rawtx:
802  CMutableTransaction mergedTx(txVariants[0]);
803 
804  // Fetch previous transactions (inputs):
805  CCoinsView viewDummy;
806  CCoinsViewCache view(&viewDummy);
807  {
808  LOCK(cs_main);
809  LOCK(mempool.cs);
810  CCoinsViewCache &viewChain = *pcoinsTip;
811  CCoinsViewMemPool viewMempool(&viewChain, mempool);
812  view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
813 
814  for (const CTxIn& txin : mergedTx.vin) {
815  view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
816  }
817 
818  view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
819  }
820 
821  // Use CTransaction for the constant parts of the
822  // transaction to avoid rehashing.
823  const CTransaction txConst(mergedTx);
824  // Sign what we can:
825  for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
826  CTxIn& txin = mergedTx.vin[i];
827  const Coin& coin = view.AccessCoin(txin.prevout);
828  if (coin.IsSpent()) {
829  throw JSONRPCError(RPC_VERIFY_ERROR, "Input not found or already spent");
830  }
831  const CScript& prevPubKey = coin.out.scriptPubKey;
832  const CAmount& amount = coin.out.nValue;
833 
834  SignatureData sigdata;
835 
836  // ... and merge in other signatures:
837  for (const CMutableTransaction& txv : txVariants) {
838  if (txv.vin.size() > i) {
839  sigdata = CombineSignatures(prevPubKey, TransactionSignatureChecker(&txConst, i, amount), sigdata, DataFromTransaction(txv, i));
840  }
841  }
842 
843  UpdateTransaction(mergedTx, i, sigdata);
844  }
845 
846  return EncodeHexTx(mergedTx);
847 }
848 
850 {
851 #ifdef ENABLE_WALLET
852  CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
853 #endif
854 
855  if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
856  throw std::runtime_error(
857  "signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
858  "\nSign inputs for raw transaction (serialized, hex-encoded).\n"
859  "The second optional argument (may be null) is an array of previous transaction outputs that\n"
860  "this transaction depends on but may not yet be in the block chain.\n"
861  "The third optional argument (may be null) is an array of base58-encoded private\n"
862  "keys that, if given, will be the only keys used to sign the transaction.\n"
863 #ifdef ENABLE_WALLET
864  + HelpRequiringPassphrase(pwallet) + "\n"
865 #endif
866 
867  "\nArguments:\n"
868  "1. \"hexstring\" (string, required) The transaction hex string\n"
869  "2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
870  " [ (json array of json objects, or 'null' if none provided)\n"
871  " {\n"
872  " \"txid\":\"id\", (string, required) The transaction id\n"
873  " \"vout\":n, (numeric, required) The output number\n"
874  " \"scriptPubKey\": \"hex\", (string, required) script key\n"
875  " \"redeemScript\": \"hex\", (string, required for P2SH or P2WSH) redeem script\n"
876  " \"amount\": value (numeric, required) The amount spent\n"
877  " }\n"
878  " ,...\n"
879  " ]\n"
880  "3. \"privkeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
881  " [ (json array of strings, or 'null' if none provided)\n"
882  " \"privatekey\" (string) private key in base58-encoding\n"
883  " ,...\n"
884  " ]\n"
885  "4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
886  " \"ALL\"\n"
887  " \"NONE\"\n"
888  " \"SINGLE\"\n"
889  " \"ALL|ANYONECANPAY\"\n"
890  " \"NONE|ANYONECANPAY\"\n"
891  " \"SINGLE|ANYONECANPAY\"\n"
892 
893  "\nResult:\n"
894  "{\n"
895  " \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"
896  " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
897  " \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n"
898  " {\n"
899  " \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n"
900  " \"vout\" : n, (numeric) The index of the output to spent and used as input\n"
901  " \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n"
902  " \"sequence\" : n, (numeric) Script sequence number\n"
903  " \"error\" : \"text\" (string) Verification or signing error related to the input\n"
904  " }\n"
905  " ,...\n"
906  " ]\n"
907  "}\n"
908 
909  "\nExamples:\n"
910  + HelpExampleCli("signrawtransaction", "\"myhex\"")
911  + HelpExampleRpc("signrawtransaction", "\"myhex\"")
912  );
913 
914 #ifdef ENABLE_WALLET
915  LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : nullptr);
916 #else
917  LOCK(cs_main);
918 #endif
919  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR, UniValue::VARR, UniValue::VSTR}, true);
920 
922  if (!DecodeHexTx(mtx, request.params[0].get_str(), true))
923  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
924 
925  // Fetch previous transactions (inputs):
926  CCoinsView viewDummy;
927  CCoinsViewCache view(&viewDummy);
928  {
929  LOCK(mempool.cs);
930  CCoinsViewCache &viewChain = *pcoinsTip;
931  CCoinsViewMemPool viewMempool(&viewChain, mempool);
932  view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
933 
934  for (const CTxIn& txin : mtx.vin) {
935  view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
936  }
937 
938  view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
939  }
940 
941  bool fGivenKeys = false;
942  CBasicKeyStore tempKeystore;
943  if (request.params.size() > 2 && !request.params[2].isNull()) {
944  fGivenKeys = true;
945  UniValue keys = request.params[2].get_array();
946  for (unsigned int idx = 0; idx < keys.size(); idx++) {
947  UniValue k = keys[idx];
948  CFabcoinSecret vchSecret;
949  bool fGood = vchSecret.SetString(k.get_str());
950  if (!fGood)
951  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
952  CKey key = vchSecret.GetKey();
953  if (!key.IsValid())
954  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
955  tempKeystore.AddKey(key);
956  }
957  }
958 #ifdef ENABLE_WALLET
959  else if (pwallet) {
960  EnsureWalletIsUnlocked(pwallet);
961  }
962 #endif
963 
964  // Add previous txouts given in the RPC call:
965  if (request.params.size() > 1 && !request.params[1].isNull()) {
966  UniValue prevTxs = request.params[1].get_array();
967  for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {
968  const UniValue& p = prevTxs[idx];
969  if (!p.isObject())
970  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
971 
972  UniValue prevOut = p.get_obj();
973 
974  RPCTypeCheckObj(prevOut,
975  {
976  {"txid", UniValueType(UniValue::VSTR)},
977  {"vout", UniValueType(UniValue::VNUM)},
978  {"scriptPubKey", UniValueType(UniValue::VSTR)},
979  });
980 
981  uint256 txid = ParseHashO(prevOut, "txid");
982 
983  int nOut = find_value(prevOut, "vout").get_int();
984  if (nOut < 0)
985  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
986 
987  COutPoint out(txid, nOut);
988  std::vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
989  CScript scriptPubKey(pkData.begin(), pkData.end());
990 
991  {
992  const Coin& coin = view.AccessCoin(out);
993  if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
994  std::string err("Previous output scriptPubKey mismatch:\n");
995  err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
996  ScriptToAsmStr(scriptPubKey);
998  }
999  Coin newcoin;
1000  newcoin.out.scriptPubKey = scriptPubKey;
1001  newcoin.out.nValue = 0;
1002  if (prevOut.exists("amount")) {
1003  newcoin.out.nValue = AmountFromValue(find_value(prevOut, "amount"));
1004  }
1005  newcoin.nHeight = 1;
1006  view.AddCoin(out, std::move(newcoin), true);
1007  }
1008 
1009  // if redeemScript given and not using the local wallet (private keys
1010  // given), add redeemScript to the tempKeystore so it can be signed:
1011  if (fGivenKeys && (scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash())) {
1012  RPCTypeCheckObj(prevOut,
1013  {
1014  {"txid", UniValueType(UniValue::VSTR)},
1015  {"vout", UniValueType(UniValue::VNUM)},
1016  {"scriptPubKey", UniValueType(UniValue::VSTR)},
1017  {"redeemScript", UniValueType(UniValue::VSTR)},
1018  });
1019  UniValue v = find_value(prevOut, "redeemScript");
1020  if (!v.isNull()) {
1021  std::vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
1022  CScript redeemScript(rsData.begin(), rsData.end());
1023  tempKeystore.AddCScript(redeemScript);
1024  }
1025  }
1026  }
1027  }
1028 
1029 #ifdef ENABLE_WALLET
1030  const CKeyStore& keystore = ((fGivenKeys || !pwallet) ? tempKeystore : *pwallet);
1031 #else
1032  const CKeyStore& keystore = tempKeystore;
1033 #endif
1034 
1035  int nHashType = SIGHASH_ALL;
1036  if (request.params.size() > 3 && !request.params[3].isNull()) {
1037  static std::map<std::string, int> mapSigHashValues = {
1038  {std::string("ALL"), int(SIGHASH_ALL)},
1039  {std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},
1040  {std::string("NONE"), int(SIGHASH_NONE)},
1041  {std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},
1042  {std::string("SINGLE"), int(SIGHASH_SINGLE)},
1043  {std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},
1044  };
1045  std::string strHashType = request.params[3].get_str();
1046  if (mapSigHashValues.count(strHashType))
1047  nHashType = mapSigHashValues[strHashType];
1048  else
1049  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
1050  }
1051 
1052  bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
1053 
1054  // Script verification errors
1055  UniValue vErrors(UniValue::VARR);
1056 
1057  // Use CTransaction for the constant parts of the
1058  // transaction to avoid rehashing.
1059  const CTransaction txConst(mtx);
1060  // Sign what we can:
1061  for (unsigned int i = 0; i < mtx.vin.size(); i++) {
1062  CTxIn& txin = mtx.vin[i];
1063  const Coin& coin = view.AccessCoin(txin.prevout);
1064  if (coin.IsSpent()) {
1065  TxInErrorToJSON(txin, vErrors, "Input not found or already spent");
1066  continue;
1067  }
1068  const CScript& prevPubKey = coin.out.scriptPubKey;
1069  const CAmount& amount = coin.out.nValue;
1070 
1071  SignatureData sigdata;
1072  // Only sign SIGHASH_SINGLE if there's a corresponding output:
1073  if (!fHashSingle || (i < mtx.vout.size()))
1074  ProduceSignature(MutableTransactionSignatureCreator(&keystore, &mtx, i, amount, nHashType), prevPubKey, sigdata);
1075  sigdata = CombineSignatures(prevPubKey, TransactionSignatureChecker(&txConst, i, amount), sigdata, DataFromTransaction(mtx, i));
1076 
1077  UpdateTransaction(mtx, i, sigdata);
1078 
1079  ScriptError serror = SCRIPT_ERR_OK;
1080  if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount), &serror)) {
1081  TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));
1082  }
1083  }
1084  bool fComplete = vErrors.empty();
1085 
1086  UniValue result(UniValue::VOBJ);
1087  result.push_back(Pair("hex", EncodeHexTx(mtx)));
1088  result.push_back(Pair("complete", fComplete));
1089  if (!vErrors.empty()) {
1090  result.push_back(Pair("errors", vErrors));
1091  }
1092 
1093  return result;
1094 }
1095 
1097 {
1098  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
1099  throw std::runtime_error(
1100  "sendrawtransaction \"hexstring\" ( allowhighfees )\n"
1101  "\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
1102  "\nAlso see createrawtransaction and signrawtransaction calls.\n"
1103  "\nArguments:\n"
1104  "1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
1105  "2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
1106  "\nResult:\n"
1107  "\"hex\" (string) The transaction hash in hex\n"
1108  "\nExamples:\n"
1109  "\nCreate a transaction\n"
1110  + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
1111  "Sign the transaction, and get back the hex\n"
1112  + HelpExampleCli("signrawtransaction", "\"myhex\"") +
1113  "\nSend the transaction (signed hex)\n"
1114  + HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
1115  "\nAs a json rpc call\n"
1116  + HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
1117  );
1118 
1119  LOCK(cs_main);
1120  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL});
1121 
1122  // parse hex string from parameter
1123  CMutableTransaction mtx;
1124  if (!DecodeHexTx(mtx, request.params[0].get_str()))
1125  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
1126  CTransactionRef tx(MakeTransactionRef(std::move(mtx)));
1127  const uint256& hashTx = tx->GetHash();
1128 
1129  CAmount nMaxRawTxFee = maxTxFee;
1130  if (request.params.size() > 1 && request.params[1].get_bool())
1131  nMaxRawTxFee = 0;
1132 
1133  CCoinsViewCache &view = *pcoinsTip;
1134  bool fHaveChain = false;
1135  for (size_t o = 0; !fHaveChain && o < tx->vout.size(); o++) {
1136  const Coin& existingCoin = view.AccessCoin(COutPoint(hashTx, o));
1137  fHaveChain = !existingCoin.IsSpent();
1138  }
1139  bool fHaveMempool = mempool.exists(hashTx);
1140  if (!fHaveMempool && !fHaveChain) {
1141  // push to local node and sync with wallets
1142  CValidationState state;
1143  bool fMissingInputs;
1144  bool fLimitFree = true;
1145  if (!AcceptToMemoryPool(mempool, state, std::move(tx), fLimitFree, &fMissingInputs, nullptr, false, nMaxRawTxFee, true)) {
1146  if (state.IsInvalid()) {
1147  throw JSONRPCError(RPC_TRANSACTION_REJECTED, strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
1148  } else {
1149  if (fMissingInputs) {
1150  throw JSONRPCError(RPC_TRANSACTION_ERROR, "Missing inputs");
1151  }
1153  }
1154  }
1155  } else if (fHaveChain) {
1156  throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
1157  }
1158  if(!g_connman)
1159  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
1160 
1161  CInv inv(MSG_TX, hashTx);
1162  g_connman->ForEachNode([&inv](CNode* pnode)
1163  {
1164  pnode->PushInventory(inv);
1165  });
1166  return hashTx.GetHex();
1167 }
1168 
1169 static const CRPCCommand commands[] =
1170 { // category name actor (function) okSafeMode
1171  // --------------------- ------------------------ ----------------------- ----------
1172  { "rawtransactions", "getrawtransaction", &getrawtransaction, true, {"txid","verbose"} },
1173  { "rawtransactions", "createrawtransaction", &createrawtransaction, true, {"inputs","outputs","locktime","replaceable"} },
1174  { "rawtransactions", "decoderawtransaction", &decoderawtransaction, true, {"hexstring"} },
1175  { "rawtransactions", "getcontractaddress", &getcontractaddress, true, {"hexstring"} },
1176  { "rawtransactions", "decodescript", &decodescript, true, {"hexstring"} },
1177  { "rawtransactions", "sendrawtransaction", &sendrawtransaction, false, {"hexstring","allowhighfees"} },
1178  { "rawtransactions", "combinerawtransaction", &combinerawtransaction, true, {"txs"} },
1179  { "rawtransactions", "signrawtransaction", &signrawtransaction, false, {"hexstring","prevtxs","privkeys","sighashtype"} }, /* uses wallet if enabled */
1180  { "rawtransactions", "gethexaddress", &gethexaddress, true, {"address",} },
1181  { "rawtransactions", "fromhexaddress", &fromhexaddress, true, {"hexaddress",} },
1182 
1183  { "blockchain", "gettxoutproof", &gettxoutproof, true, {"txids", "blockhash"} },
1184  { "blockchain", "verifytxoutproof", &verifytxoutproof, true, {"proof"} },
1185 };
1186 
1188 {
1189  for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
1190  t.appendCommand(commands[vcidx].name, &commands[vcidx]);
1191 }
int get_int() const
A base58-encoded secret key.
Definition: base58.h:126
CAmount nValue
Definition: transaction.h:134
const Coin & AccessByTxid(const CCoinsViewCache &view, const uint256 &txid)
Utility function to find any unspent output with a given txid.
Definition: coins.cpp:252
const std::string CURRENCY_UNIT
Definition: feerate.cpp:10
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull, bool fStrict)
Definition: server.cpp:84
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:201
Aliases for backward compatibility.
Definition: protocol.h:62
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: server.cpp:139
CTxMemPool mempool
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string strKey)
Definition: server.cpp:152
void UpdateTransaction(CMutableTransaction &tx, unsigned int nIn, const SignatureData &data)
Definition: sign.cpp:198
const std::string & get_str() const
size_t size() const
Definition: univalue.h:70
bool SetString(const char *pszSecret)
Definition: base58.cpp:317
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn)
Extract signature data from a transaction, and insert it.
Definition: sign.cpp:189
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool potential_overwrite)
Add a coin.
Definition: coins.cpp:69
UniValue combinerawtransaction(const JSONRPCRequest &request)
Fabcoin RPC command dispatcher.
Definition: server.h:200
enum ScriptError_t ScriptError
const_iterator begin() const
Definition: streams.h:233
CScript scriptPubKey
Definition: transaction.h:135
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:30
UniValue gethexaddress(const JSONRPCRequest &request)
A UTXO entry.
Definition: coins.h:29
Definition: block.h:155
CCriticalSection cs_wallet
Definition: wallet.h:748
#define strprintf
Definition: tinyformat.h:1054
#define ENABLE_WALLET
CAmount maxTxFee
Absolute maximum transaction fee (in liu) used by wallet and mempool (rejects high fee in sendrawtran...
Definition: validation.cpp:104
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, unsigned int flags, const BaseSignatureChecker &checker, ScriptError *serror)
inv message data
Definition: protocol.h:338
std::vector< CTxIn > vin
Definition: transaction.h:392
CScriptWitness scriptWitness
Definition: transaction.h:67
bool empty() const
Definition: univalue.h:68
std::string GetHex() const
Definition: uint256.cpp:21
static VersionVM GetEVMDefault()
const Consensus::Params & GetConsensus() const
Definition: chainparams.h:60
CCriticalSection cs_main
Definition: validation.cpp:77
base58-encoded Fabcoin addresses.
Definition: base58.h:104
CTxOut out
unspent transaction output
Definition: coins.h:33
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
virtual bool AddCScript(const CScript &redeemScript) override
Support for BIP 0013 : see https://github.com/fabcoin/bips/blob/master/bip-0013.mediawiki.
Definition: keystore.cpp:39
std::vector< std::vector< unsigned char > > stack
Definition: script.h:724
bool IsSpent() const
Definition: coins.h:75
UniValue decoderawtransaction(const JSONRPCRequest &request)
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: server.cpp:559
uint32_t toRaw()
bool IsValid() const
Definition: base58.cpp:247
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:146
bool isBool() const
Definition: univalue.h:82
UniValue getcontractaddress(const JSONRPCRequest &request)
void TxToJSON(const CTransaction &tx, const uint256 hashBlock, UniValue &entry)
unsigned char * begin()
Definition: uint256.h:65
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:437
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:298
bool ProduceSignature(const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
Definition: sign.cpp:141
void PushInventory(const CInv &inv)
Definition: net.h:822
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:59
unsigned char * end()
Definition: uint256.h:70
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:126
SignatureData CombineSignatures(const CScript &scriptPubKey, const BaseSignatureChecker &checker, const SignatureData &scriptSig1, const SignatureData &scriptSig2)
Combine two script signatures using a generic signature checker, intelligently, possibly with OP_0 pl...
Definition: sign.cpp:395
std::string ToString() const
Definition: uint256.cpp:95
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:92
const char * ScriptErrorString(const ScriptError serror)
Definition: script_error.cpp:8
int64_t CAmount
Amount in lius (Can be negative)
Definition: amount.h:15
bool ReadBlockFromDisk(Block &block, const CDiskBlockPos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
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:292
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:252
#define LOCK2(cs1, cs2)
Definition: sync.h:176
std::string name
Definition: server.h:191
int Height() const
Return the maximal height in the chain.
Definition: chain.h:543
Used to relay blocks as header + vector<merkle branch> to filtered nodes.
Definition: merkleblock.h:127
int64_t get_int64() const
bool push_back(const UniValue &val)
Definition: univalue.cpp:110
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode=false)
Create the assembly string representation of a CScript object.
Definition: core_write.cpp:80
Abstract view on the open txout dataset.
Definition: coins.h:145
UniValue params
Definition: server.h:59
An input of a transaction.
Definition: transaction.h:61
void SetReverseHex(const char *psz)
Definition: uint256.cpp:74
bool IsNull() const
Definition: uint256.h:38
bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx, bool fTryNoWitness=false)
Definition: core_read.cpp:111
#define LOCK(cs)
Definition: sync.h:175
const Object_type::value_type::Value_type & find_value(const Object_type &obj, const String_type &name)
ExecStats::duration max
Definition: ExecStats.cpp:36
bool isNum() const
Definition: univalue.h:84
uint64_t getBlockGasLimit(unsigned int blockHeight)
Definition: fascDGP.cpp:76
uint256 uint256S(const char *str)
Definition: uint256.h:153
UniValue fromhexaddress(const JSONRPCRequest &request)
uint32_t ContractHeight
Block height at which Fabcoin Smart Contract hard fork becomes active.
Definition: params.h:56
uint32_t n
Definition: transaction.h:22
UniValue decodescript(const JSONRPCRequest &request)
bool IsHex(const std::string &str)
Unexpected type was passed as parameter.
Definition: protocol.h:50
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:119
Fixed-size raw-byte array container type, with an API optimised for storing hashes.
Definition: FixedHash.h:47
std::string ToString() const
Definition: base58.cpp:193
bool ParseMoney(const std::string &str, CAmount &nRet)
An output of a transaction.
Definition: transaction.h:131
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:80
Invalid address or key.
Definition: protocol.h:51
CScript GetScriptForDestination(const CTxDestination &dest)
Definition: standard.cpp:370
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: server.cpp:554
std::string HelpRequiringPassphrase()
CAmount AmountFromValue(const UniValue &value)
Definition: server.cpp:114
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:18
virtual bool AddKey(const CKey &key)
Definition: keystore.cpp:12
std::vector< CTxOut > vout
Definition: transaction.h:393
bool fTxIndex
Definition: validation.cpp:87
CTxDestination Get() const
Definition: base58.cpp:260
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
uint256 GetHash() const
Compute the hash of this CMutableTransaction.
Definition: transaction.cpp:61
void RegisterRawTransactionRPCCommands(CRPCTable &t)
Register raw transaction RPC commands.
CCriticalSection cs
Definition: txmempool.h:523
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool fLimitFree, bool *pfMissingInputs, std::list< CTransactionRef > *plTxnReplaced, bool fOverrideMempoolLimit, const CAmount nAbsurdFee, bool rawTx)
(try to) add transaction to memory pool plTxnReplaced will be appended to with all transactions repla...
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string strName)
Definition: server.cpp:143
CRIPEMD160 & Write(const unsigned char *data, size_t len)
Definition: ripemd160.cpp:247
bool IsInvalid() const
Definition: validation.h:69
bool exists(uint256 hash) const
Definition: txmempool.h:671
bool CheckHex(const std::string &str)
Definition: util.cpp:985
std::string GetRejectReason() const
Definition: validation.h:89
CKey GetKey()
Definition: base58.cpp:302
unsigned int GetRejectCode() const
Definition: validation.h:88
CScript scriptSig
Definition: transaction.h:65
UniValue createrawtransaction(const JSONRPCRequest &request)
bool fHelp
Definition: server.h:60
Capture information about block/transaction validation.
Definition: validation.h:27
256-bit opaque blob.
Definition: uint256.h:132
ArgsManager gArgs
Definition: util.cpp:94
std::vector< CTransactionRef > vtx
Definition: block.h:159
bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params &consensusParams, uint256 &hashBlock, bool fAllowSlow)
Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock...
const std::string & getValStr() const
Definition: univalue.h:67
#define ARRAYLEN(array)
const UniValue & get_array() const
PlatformStyle::TableColorType type
Definition: rpcconsole.cpp:61
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:177
const CChainParams & Params()
Return the currently selected parameters.
std::string GetArg(const std::string &strArg, const std::string &strDefault)
Return string argument or default value.
Definition: util.cpp:504
UniValue sendrawtransaction(const JSONRPCRequest &request)
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:417
int RPCSerializationFlags()
Definition: server.cpp:591
uint32_t nSequence
Definition: transaction.h:66
void * memcpy(void *a, const void *b, size_t c)
bool SignalsOptInRBF(const CTransaction &tx)
Definition: rbf.cpp:7
A virtual base class for key stores.
Definition: keystore.h:18
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:29
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:530
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
Definition: wallet.h:672
UniValue gettxoutproof(const JSONRPCRequest &request)
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Definition: core_write.cpp:124
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:75
CWallet * GetWalletForJSONRPCRequest(const JSONRPCRequest &request)
Figures out what wallet, if any, to use for a JSONRPCRequest.
Definition: rpcwallet.cpp:41
std::string i64tostr(int64_t n)
iterator begin()
Definition: prevector.h:290
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
Definition: core_write.cpp:131
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:28
bool isObject() const
Definition: univalue.h:86
A mutable version of CTransaction.
Definition: transaction.h:390
void TxToUniv(const CTransaction &tx, const uint256 &hashBlock, UniValue &entry, bool include_hex=true, int serialize_flags=0)
Definition: core_write.cpp:156
UniValue signrawtransaction(const JSONRPCRequest &request)
bool get_bool() const
UniValue JSONRPCError(int code, const std::string &message)
Definition: protocol.cpp:54
No valid connection manager instance found.
Definition: protocol.h:73
bool exists(const std::string &key) const
Definition: univalue.h:77
struct evm_uint160be address(struct evm_env *env)
Definition: capi.c:13
An encapsulated private key.
Definition: key.h:35
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:275
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:193
const std::vector< std::string > & getKeys() const
Information about a peer.
Definition: net.h:599
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:201
int64_t GetBlockTime() const
Definition: chain.h:329
A hasher class for SHA-256.
Definition: sha256.h:13
std::string get_str(std::string::const_iterator begin, std::string::const_iterator end)
const UniValue & get_obj() const
bool isNull() const
Definition: univalue.h:79
COutPoint prevout
Definition: transaction.h:64
bool isTrue() const
Definition: univalue.h:80
Config::Pair_type Pair
CCoinsView that brings transactions from a memorypool into view.
Definition: txmempool.h:743
uint8_t const * data
Definition: sha3.h:19
BlockMap mapBlockIndex
Definition: validation.cpp:79
Basic key store, that keeps keys in an address->secret map.
Definition: keystore.h:54
bool isStr() const
Definition: univalue.h:83
Wrapper for UniValue::VType, which includes typeAny: Used to denote don&#39;t care type.
Definition: server.h:47
std::unique_ptr< FascState > globalState
Global state.
Definition: validation.cpp:70
bool fGettingValuesDGP
Definition: validation.cpp:74
Error parsing or validating structure in raw format.
Definition: protocol.h:55
A hasher class for RIPEMD-160.
Definition: ripemd160.h:12
const_iterator end() const
Definition: streams.h:235
void EnsureWalletIsUnlocked()
std::vector< unsigned char > ParseHex(const char *psz)
uint256 hash
Definition: transaction.h:21