BSHA3  0.17.99
P2P Blockchain, based on Bitcoin
rawtransaction.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 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 <chain.h>
7 #include <coins.h>
8 #include <compat/byteswap.h>
9 #include <consensus/validation.h>
10 #include <core_io.h>
11 #include <index/txindex.h>
12 #include <keystore.h>
13 #include <validation.h>
14 #include <validationinterface.h>
15 #include <key_io.h>
16 #include <merkleblock.h>
17 #include <net.h>
18 #include <policy/policy.h>
19 #include <policy/rbf.h>
20 #include <primitives/transaction.h>
21 #include <rpc/rawtransaction.h>
22 #include <rpc/server.h>
23 #include <script/script.h>
24 #include <script/script_error.h>
25 #include <script/sign.h>
26 #include <script/standard.h>
27 #include <txmempool.h>
28 #include <uint256.h>
29 #include <utilstrencodings.h>
30 
31 #include <future>
32 #include <stdint.h>
33 
34 #include <univalue.h>
35 
36 
37 static void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry)
38 {
39  // Call into TxToUniv() in bitcoin-common to decode the transaction hex.
40  //
41  // Blockchain contextual information (confirmations and blocktime) is not
42  // available to code in bitcoin-common, so we query them here and push the
43  // data into the returned UniValue.
44  TxToUniv(tx, uint256(), entry, true, RPCSerializationFlags());
45 
46  if (!hashBlock.IsNull()) {
47  LOCK(cs_main);
48 
49  entry.pushKV("blockhash", hashBlock.GetHex());
50  CBlockIndex* pindex = LookupBlockIndex(hashBlock);
51  if (pindex) {
52  if (chainActive.Contains(pindex)) {
53  entry.pushKV("confirmations", 1 + chainActive.Height() - pindex->nHeight);
54  entry.pushKV("time", pindex->GetBlockTime());
55  entry.pushKV("blocktime", pindex->GetBlockTime());
56  }
57  else
58  entry.pushKV("confirmations", 0);
59  }
60  }
61 }
62 
63 static UniValue getrawtransaction(const JSONRPCRequest& request)
64 {
65  if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)
66  throw std::runtime_error(
67  "getrawtransaction \"txid\" ( verbose \"blockhash\" )\n"
68 
69  "\nNOTE: By default this function only works for mempool transactions. If the -txindex option is\n"
70  "enabled, it also works for blockchain transactions. If the block which contains the transaction\n"
71  "is known, its hash can be provided even for nodes without -txindex. Note that if a blockhash is\n"
72  "provided, only that block will be searched and if the transaction is in the mempool or other\n"
73  "blocks, or if this node does not have the given block available, the transaction will not be found.\n"
74  "DEPRECATED: for now, it also works for transactions with unspent outputs.\n"
75 
76  "\nReturn the raw transaction data.\n"
77  "\nIf verbose is 'true', returns an Object with information about 'txid'.\n"
78  "If verbose is 'false' or omitted, returns a string that is serialized, hex-encoded data for 'txid'.\n"
79 
80  "\nArguments:\n"
81  "1. \"txid\" (string, required) The transaction id\n"
82  "2. verbose (bool, optional, default=false) If false, return a string, otherwise return a json object\n"
83  "3. \"blockhash\" (string, optional) The block in which to look for the transaction\n"
84 
85  "\nResult (if verbose is not set or set to false):\n"
86  "\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
87 
88  "\nResult (if verbose is set to true):\n"
89  "{\n"
90  " \"in_active_chain\": b, (bool) Whether specified block is in the active chain or not (only present with explicit \"blockhash\" argument)\n"
91  " \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
92  " \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
93  " \"hash\" : \"id\", (string) The transaction hash (differs from txid for witness transactions)\n"
94  " \"size\" : n, (numeric) The serialized transaction size\n"
95  " \"vsize\" : n, (numeric) The virtual transaction size (differs from size for witness transactions)\n"
96  " \"weight\" : n, (numeric) The transaction's weight (between vsize*4-3 and vsize*4)\n"
97  " \"version\" : n, (numeric) The version\n"
98  " \"locktime\" : ttt, (numeric) The lock time\n"
99  " \"vin\" : [ (array of json objects)\n"
100  " {\n"
101  " \"txid\": \"id\", (string) The transaction id\n"
102  " \"vout\": n, (numeric) \n"
103  " \"scriptSig\": { (json object) The script\n"
104  " \"asm\": \"asm\", (string) asm\n"
105  " \"hex\": \"hex\" (string) hex\n"
106  " },\n"
107  " \"sequence\": n (numeric) The script sequence number\n"
108  " \"txinwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n"
109  " }\n"
110  " ,...\n"
111  " ],\n"
112  " \"vout\" : [ (array of json objects)\n"
113  " {\n"
114  " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
115  " \"n\" : n, (numeric) index\n"
116  " \"scriptPubKey\" : { (json object)\n"
117  " \"asm\" : \"asm\", (string) the asm\n"
118  " \"hex\" : \"hex\", (string) the hex\n"
119  " \"reqSigs\" : n, (numeric) The required sigs\n"
120  " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
121  " \"addresses\" : [ (json array of string)\n"
122  " \"address\" (string) bitcoin address\n"
123  " ,...\n"
124  " ]\n"
125  " }\n"
126  " }\n"
127  " ,...\n"
128  " ],\n"
129  " \"blockhash\" : \"hash\", (string) the block hash\n"
130  " \"confirmations\" : n, (numeric) The confirmations\n"
131  " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
132  " \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
133  "}\n"
134 
135  "\nExamples:\n"
136  + HelpExampleCli("getrawtransaction", "\"mytxid\"")
137  + HelpExampleCli("getrawtransaction", "\"mytxid\" true")
138  + HelpExampleRpc("getrawtransaction", "\"mytxid\", true")
139  + HelpExampleCli("getrawtransaction", "\"mytxid\" false \"myblockhash\"")
140  + HelpExampleCli("getrawtransaction", "\"mytxid\" true \"myblockhash\"")
141  );
142 
143  bool in_active_chain = true;
144  uint256 hash = ParseHashV(request.params[0], "parameter 1");
145  CBlockIndex* blockindex = nullptr;
146 
147  if (hash == Params().GenesisBlock().hashMerkleRoot) {
148  // Special exception for the genesis block coinbase transaction
149  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "The genesis block coinbase is not considered an ordinary transaction and cannot be retrieved");
150  }
151 
152  // Accept either a bool (true) or a num (>=1) to indicate verbose output.
153  bool fVerbose = false;
154  if (!request.params[1].isNull()) {
155  fVerbose = request.params[1].isNum() ? (request.params[1].get_int() != 0) : request.params[1].get_bool();
156  }
157 
158  if (!request.params[2].isNull()) {
159  LOCK(cs_main);
160 
161  uint256 blockhash = ParseHashV(request.params[2], "parameter 3");
162  blockindex = LookupBlockIndex(blockhash);
163  if (!blockindex) {
164  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block hash not found");
165  }
166  in_active_chain = chainActive.Contains(blockindex);
167  }
168 
169  bool f_txindex_ready = false;
170  if (g_txindex && !blockindex) {
171  f_txindex_ready = g_txindex->BlockUntilSyncedToCurrentChain();
172  }
173 
174  CTransactionRef tx;
175  uint256 hash_block;
176  if (!GetTransaction(hash, tx, Params().GetConsensus(), hash_block, true, blockindex)) {
177  std::string errmsg;
178  if (blockindex) {
179  if (!(blockindex->nStatus & BLOCK_HAVE_DATA)) {
180  throw JSONRPCError(RPC_MISC_ERROR, "Block not available");
181  }
182  errmsg = "No such transaction found in the provided block";
183  } else if (!g_txindex) {
184  errmsg = "No such mempool transaction. Use -txindex to enable blockchain transaction queries";
185  } else if (!f_txindex_ready) {
186  errmsg = "No such mempool transaction. Blockchain transactions are still in the process of being indexed";
187  } else {
188  errmsg = "No such mempool or blockchain transaction";
189  }
190  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, errmsg + ". Use gettransaction for wallet transactions.");
191  }
192 
193  if (!fVerbose) {
194  return EncodeHexTx(*tx, RPCSerializationFlags());
195  }
196 
197  UniValue result(UniValue::VOBJ);
198  if (blockindex) result.pushKV("in_active_chain", in_active_chain);
199  TxToJSON(*tx, hash_block, result);
200  return result;
201 }
202 
203 static UniValue gettxoutproof(const JSONRPCRequest& request)
204 {
205  if (request.fHelp || (request.params.size() != 1 && request.params.size() != 2))
206  throw std::runtime_error(
207  "gettxoutproof [\"txid\",...] ( blockhash )\n"
208  "\nReturns a hex-encoded proof that \"txid\" was included in a block.\n"
209  "\nNOTE: By default this function only works sometimes. This is when there is an\n"
210  "unspent output in the utxo for this transaction. To make it always work,\n"
211  "you need to maintain a transaction index, using the -txindex command line option or\n"
212  "specify the block in which the transaction is included manually (by blockhash).\n"
213  "\nArguments:\n"
214  "1. \"txids\" (string) A json array of txids to filter\n"
215  " [\n"
216  " \"txid\" (string) A transaction hash\n"
217  " ,...\n"
218  " ]\n"
219  "2. \"blockhash\" (string, optional) If specified, looks for txid in the block with this hash\n"
220  "\nResult:\n"
221  "\"data\" (string) A string that is a serialized, hex-encoded data for the proof.\n"
222  );
223 
224  std::set<uint256> setTxids;
225  uint256 oneTxid;
226  UniValue txids = request.params[0].get_array();
227  for (unsigned int idx = 0; idx < txids.size(); idx++) {
228  const UniValue& txid = txids[idx];
229  uint256 hash(ParseHashV(txid, "txid"));
230  if (setTxids.count(hash))
231  throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated txid: ")+txid.get_str());
232  setTxids.insert(hash);
233  oneTxid = hash;
234  }
235 
236  CBlockIndex* pblockindex = nullptr;
237  uint256 hashBlock;
238  if (!request.params[1].isNull()) {
239  LOCK(cs_main);
240  hashBlock = ParseHashV(request.params[1], "blockhash");
241  pblockindex = LookupBlockIndex(hashBlock);
242  if (!pblockindex) {
243  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
244  }
245  } else {
246  LOCK(cs_main);
247 
248  // Loop through txids and try to find which block they're in. Exit loop once a block is found.
249  for (const auto& tx : setTxids) {
250  const Coin& coin = AccessByTxid(*pcoinsTip, tx);
251  if (!coin.IsSpent()) {
252  pblockindex = chainActive[coin.nHeight];
253  break;
254  }
255  }
256  }
257 
258 
259  // Allow txindex to catch up if we need to query it and before we acquire cs_main.
260  if (g_txindex && !pblockindex) {
261  g_txindex->BlockUntilSyncedToCurrentChain();
262  }
263 
264  LOCK(cs_main);
265 
266  if (pblockindex == nullptr)
267  {
268  CTransactionRef tx;
269  if (!GetTransaction(oneTxid, tx, Params().GetConsensus(), hashBlock, false) || hashBlock.IsNull())
270  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block");
271  pblockindex = LookupBlockIndex(hashBlock);
272  if (!pblockindex) {
273  throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt");
274  }
275  }
276 
277  CBlock block;
278  if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
279  throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
280 
281  unsigned int ntxFound = 0;
282  for (const auto& tx : block.vtx)
283  if (setTxids.count(tx->GetHash()))
284  ntxFound++;
285  if (ntxFound != setTxids.size())
286  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Not all transactions found in specified or retrieved block");
287 
288  CDataStream ssMB(SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
289  CMerkleBlock mb(block, setTxids);
290  ssMB << mb;
291  std::string strHex = HexStr(ssMB.begin(), ssMB.end());
292  return strHex;
293 }
294 
295 static UniValue verifytxoutproof(const JSONRPCRequest& request)
296 {
297  if (request.fHelp || request.params.size() != 1)
298  throw std::runtime_error(
299  "verifytxoutproof \"proof\"\n"
300  "\nVerifies that a proof points to a transaction in a block, returning the transaction it commits to\n"
301  "and throwing an RPC error if the block is not in our best chain\n"
302  "\nArguments:\n"
303  "1. \"proof\" (string, required) The hex-encoded proof generated by gettxoutproof\n"
304  "\nResult:\n"
305  "[\"txid\"] (array, strings) The txid(s) which the proof commits to, or empty array if the proof can not be validated.\n"
306  );
307 
308  CDataStream ssMB(ParseHexV(request.params[0], "proof"), SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
309  CMerkleBlock merkleBlock;
310  ssMB >> merkleBlock;
311 
313 
314  std::vector<uint256> vMatch;
315  std::vector<unsigned int> vIndex;
316  if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot)
317  return res;
318 
319  LOCK(cs_main);
320 
321  const CBlockIndex* pindex = LookupBlockIndex(merkleBlock.header.GetHash());
322  if (!pindex || !chainActive.Contains(pindex) || pindex->nTx == 0) {
323  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
324  }
325 
326  // Check if proof is valid, only add results if so
327  if (pindex->nTx == merkleBlock.txn.GetNumTransactions()) {
328  for (const uint256& hash : vMatch) {
329  res.push_back(hash.GetHex());
330  }
331  }
332 
333  return res;
334 }
335 
336 CMutableTransaction ConstructTransaction(const UniValue& inputs_in, const UniValue& outputs_in, const UniValue& locktime, const UniValue& rbf)
337 {
338  if (inputs_in.isNull() || outputs_in.isNull())
339  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, arguments 1 and 2 must be non-null");
340 
341  UniValue inputs = inputs_in.get_array();
342  const bool outputs_is_obj = outputs_in.isObject();
343  UniValue outputs = outputs_is_obj ? outputs_in.get_obj() : outputs_in.get_array();
344 
345  CMutableTransaction rawTx;
346 
347  if (!locktime.isNull()) {
348  int64_t nLockTime = locktime.get_int64();
349  if (nLockTime < 0 || nLockTime > std::numeric_limits<uint32_t>::max())
350  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");
351  rawTx.nLockTime = nLockTime;
352  }
353 
354  bool rbfOptIn = rbf.isTrue();
355 
356  for (unsigned int idx = 0; idx < inputs.size(); idx++) {
357  const UniValue& input = inputs[idx];
358  const UniValue& o = input.get_obj();
359 
360  uint256 txid = ParseHashO(o, "txid");
361 
362  const UniValue& vout_v = find_value(o, "vout");
363  if (!vout_v.isNum())
364  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
365  int nOutput = vout_v.get_int();
366  if (nOutput < 0)
367  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
368 
369  uint32_t nSequence;
370  if (rbfOptIn) {
371  nSequence = MAX_BIP125_RBF_SEQUENCE;
372  } else if (rawTx.nLockTime) {
373  nSequence = std::numeric_limits<uint32_t>::max() - 1;
374  } else {
375  nSequence = std::numeric_limits<uint32_t>::max();
376  }
377 
378  // set the sequence number if passed in the parameters object
379  const UniValue& sequenceObj = find_value(o, "sequence");
380  if (sequenceObj.isNum()) {
381  int64_t seqNr64 = sequenceObj.get_int64();
382  if (seqNr64 < 0 || seqNr64 > std::numeric_limits<uint32_t>::max()) {
383  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range");
384  } else {
385  nSequence = (uint32_t)seqNr64;
386  }
387  }
388 
389  CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
390 
391  rawTx.vin.push_back(in);
392  }
393 
394  std::set<CTxDestination> destinations;
395  if (!outputs_is_obj) {
396  // Translate array of key-value pairs into dict
397  UniValue outputs_dict = UniValue(UniValue::VOBJ);
398  for (size_t i = 0; i < outputs.size(); ++i) {
399  const UniValue& output = outputs[i];
400  if (!output.isObject()) {
401  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, key-value pair not an object as expected");
402  }
403  if (output.size() != 1) {
404  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, key-value pair must contain exactly one key");
405  }
406  outputs_dict.pushKVs(output);
407  }
408  outputs = std::move(outputs_dict);
409  }
410  for (const std::string& name_ : outputs.getKeys()) {
411  if (name_ == "data") {
412  std::vector<unsigned char> data = ParseHexV(outputs[name_].getValStr(), "Data");
413 
414  CTxOut out(0, CScript() << OP_RETURN << data);
415  rawTx.vout.push_back(out);
416  } else {
417  CTxDestination destination = DecodeDestination(name_);
418  if (!IsValidDestination(destination)) {
419  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid BSHA3 address: ") + name_);
420  }
421 
422  if (!destinations.insert(destination).second) {
423  throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + name_);
424  }
425 
426  CScript scriptPubKey = GetScriptForDestination(destination);
427  CAmount nAmount = AmountFromValue(outputs[name_]);
428 
429  CTxOut out(nAmount, scriptPubKey);
430  rawTx.vout.push_back(out);
431  }
432  }
433 
434  if (!rbf.isNull() && rawTx.vin.size() > 0 && rbfOptIn != SignalsOptInRBF(rawTx)) {
435  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter combination: Sequence number(s) contradict replaceable option");
436  }
437 
438  return rawTx;
439 }
440 
441 static UniValue createrawtransaction(const JSONRPCRequest& request)
442 {
443  if (request.fHelp || request.params.size() < 2 || request.params.size() > 4) {
444  throw std::runtime_error(
445  // clang-format off
446  "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] [{\"address\":amount},{\"data\":\"hex\"},...] ( locktime ) ( replaceable )\n"
447  "\nCreate a transaction spending the given inputs and creating new outputs.\n"
448  "Outputs can be addresses or data.\n"
449  "Returns hex-encoded raw transaction.\n"
450  "Note that the transaction's inputs are not signed, and\n"
451  "it is not stored in the wallet or transmitted to the network.\n"
452 
453  "\nArguments:\n"
454  "1. \"inputs\" (array, required) A json array of json objects\n"
455  " [\n"
456  " {\n"
457  " \"txid\":\"id\", (string, required) The transaction id\n"
458  " \"vout\":n, (numeric, required) The output number\n"
459  " \"sequence\":n (numeric, optional) The sequence number\n"
460  " } \n"
461  " ,...\n"
462  " ]\n"
463  "2. \"outputs\" (array, required) a json array with outputs (key-value pairs)\n"
464  " [\n"
465  " {\n"
466  " \"address\": x.xxx, (obj, optional) A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT + "\n"
467  " },\n"
468  " {\n"
469  " \"data\": \"hex\" (obj, optional) A key-value pair. The key must be \"data\", the value is hex-encoded data\n"
470  " }\n"
471  " ,... More key-value pairs of the above form. For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n"
472  " accepted as second parameter.\n"
473  " ]\n"
474  "3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n"
475  "4. replaceable (boolean, optional, default=false) Marks this transaction as BIP125-replaceable.\n"
476  " 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"
477  "\nResult:\n"
478  "\"transaction\" (string) hex string of the transaction\n"
479 
480  "\nExamples:\n"
481  + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"address\\\":0.01}]\"")
482  + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"")
483  + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"[{\\\"address\\\":0.01}]\"")
484  + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"[{\\\"data\\\":\\\"00010203\\\"}]\"")
485  // clang-format on
486  );
487  }
488 
489  RPCTypeCheck(request.params, {
490  UniValue::VARR,
491  UniValueType(), // ARR or OBJ, checked later
492  UniValue::VNUM,
493  UniValue::VBOOL
494  }, true
495  );
496 
497  CMutableTransaction rawTx = ConstructTransaction(request.params[0], request.params[1], request.params[2], request.params[3]);
498 
499  return EncodeHexTx(rawTx);
500 }
501 
502 static UniValue decoderawtransaction(const JSONRPCRequest& request)
503 {
504  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
505  throw std::runtime_error(
506  "decoderawtransaction \"hexstring\" ( iswitness )\n"
507  "\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
508 
509  "\nArguments:\n"
510  "1. \"hexstring\" (string, required) The transaction hex string\n"
511  "2. iswitness (boolean, optional) Whether the transaction hex is a serialized witness transaction\n"
512  " If iswitness is not present, heuristic tests will be used in decoding\n"
513 
514  "\nResult:\n"
515  "{\n"
516  " \"txid\" : \"id\", (string) The transaction id\n"
517  " \"hash\" : \"id\", (string) The transaction hash (differs from txid for witness transactions)\n"
518  " \"size\" : n, (numeric) The transaction size\n"
519  " \"vsize\" : n, (numeric) The virtual transaction size (differs from size for witness transactions)\n"
520  " \"weight\" : n, (numeric) The transaction's weight (between vsize*4 - 3 and vsize*4)\n"
521  " \"version\" : n, (numeric) The version\n"
522  " \"locktime\" : ttt, (numeric) The lock time\n"
523  " \"vin\" : [ (array of json objects)\n"
524  " {\n"
525  " \"txid\": \"id\", (string) The transaction id\n"
526  " \"vout\": n, (numeric) The output number\n"
527  " \"scriptSig\": { (json object) The script\n"
528  " \"asm\": \"asm\", (string) asm\n"
529  " \"hex\": \"hex\" (string) hex\n"
530  " },\n"
531  " \"txinwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n"
532  " \"sequence\": n (numeric) The script sequence number\n"
533  " }\n"
534  " ,...\n"
535  " ],\n"
536  " \"vout\" : [ (array of json objects)\n"
537  " {\n"
538  " \"value\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
539  " \"n\" : n, (numeric) index\n"
540  " \"scriptPubKey\" : { (json object)\n"
541  " \"asm\" : \"asm\", (string) the asm\n"
542  " \"hex\" : \"hex\", (string) the hex\n"
543  " \"reqSigs\" : n, (numeric) The required sigs\n"
544  " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
545  " \"addresses\" : [ (json array of string)\n"
546  " \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) bitcoin address\n"
547  " ,...\n"
548  " ]\n"
549  " }\n"
550  " }\n"
551  " ,...\n"
552  " ],\n"
553  "}\n"
554 
555  "\nExamples:\n"
556  + HelpExampleCli("decoderawtransaction", "\"hexstring\"")
557  + HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
558  );
559 
560  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL});
561 
563 
564  bool try_witness = request.params[1].isNull() ? true : request.params[1].get_bool();
565  bool try_no_witness = request.params[1].isNull() ? true : !request.params[1].get_bool();
566 
567  if (!DecodeHexTx(mtx, request.params[0].get_str(), try_no_witness, try_witness)) {
568  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
569  }
570 
571  UniValue result(UniValue::VOBJ);
572  TxToUniv(CTransaction(std::move(mtx)), uint256(), result, false);
573 
574  return result;
575 }
576 
577 static UniValue decodescript(const JSONRPCRequest& request)
578 {
579  if (request.fHelp || request.params.size() != 1)
580  throw std::runtime_error(
581  "decodescript \"hexstring\"\n"
582  "\nDecode a hex-encoded script.\n"
583  "\nArguments:\n"
584  "1. \"hexstring\" (string) the hex-encoded script\n"
585  "\nResult:\n"
586  "{\n"
587  " \"asm\":\"asm\", (string) Script public key\n"
588  " \"hex\":\"hex\", (string) hex-encoded public key\n"
589  " \"type\":\"type\", (string) The output type\n"
590  " \"reqSigs\": n, (numeric) The required signatures\n"
591  " \"addresses\": [ (json array of string)\n"
592  " \"address\" (string) bitcoin address\n"
593  " ,...\n"
594  " ],\n"
595  " \"p2sh\",\"address\" (string) address of P2SH script wrapping this redeem script (not returned if the script is already a P2SH).\n"
596  "}\n"
597  "\nExamples:\n"
598  + HelpExampleCli("decodescript", "\"hexstring\"")
599  + HelpExampleRpc("decodescript", "\"hexstring\"")
600  );
601 
602  RPCTypeCheck(request.params, {UniValue::VSTR});
603 
605  CScript script;
606  if (request.params[0].get_str().size() > 0){
607  std::vector<unsigned char> scriptData(ParseHexV(request.params[0], "argument"));
608  script = CScript(scriptData.begin(), scriptData.end());
609  } else {
610  // Empty scripts are valid
611  }
612  ScriptPubKeyToUniv(script, r, false);
613 
614  UniValue type;
615  type = find_value(r, "type");
616 
617  if (type.isStr() && type.get_str() != "scripthash") {
618  // P2SH cannot be wrapped in a P2SH. If this script is already a P2SH,
619  // don't return the address for a P2SH of the P2SH.
620  r.pushKV("p2sh", EncodeDestination(CScriptID(script)));
621  // P2SH and witness programs cannot be wrapped in P2WSH, if this script
622  // is a witness program, don't return addresses for a segwit programs.
623  if (type.get_str() == "pubkey" || type.get_str() == "pubkeyhash" || type.get_str() == "multisig" || type.get_str() == "nonstandard") {
624  std::vector<std::vector<unsigned char>> solutions_data;
625  txnouttype which_type = Solver(script, solutions_data);
626  // Uncompressed pubkeys cannot be used with segwit checksigs.
627  // If the script contains an uncompressed pubkey, skip encoding of a segwit program.
628  if ((which_type == TX_PUBKEY) || (which_type == TX_MULTISIG)) {
629  for (const auto& solution : solutions_data) {
630  if ((solution.size() != 1) && !CPubKey(solution).IsCompressed()) {
631  return r;
632  }
633  }
634  }
636  CScript segwitScr;
637  if (which_type == TX_PUBKEY) {
638  segwitScr = GetScriptForDestination(WitnessV0KeyHash(Hash360(solutions_data[0].begin(), solutions_data[0].end())));
639  } else if (which_type == TX_PUBKEYHASH) {
640  segwitScr = GetScriptForDestination(WitnessV0KeyHash(solutions_data[0]));
641  } else {
642  // Scripts that are not fit for P2WPKH are encoded as P2WSH.
643  // Newer segwit program versions should be considered when then become available.
644  segwitScr = GetScriptForDestination(WitnessV0ScriptHash(script));
645  }
646  ScriptPubKeyToUniv(segwitScr, sr, true);
647  sr.pushKV("p2sh-segwit", EncodeDestination(CScriptID(segwitScr)));
648  r.pushKV("segwit", sr);
649  }
650  }
651 
652  return r;
653 }
654 
656 static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)
657 {
658  UniValue entry(UniValue::VOBJ);
659  entry.pushKV("txid", txin.prevout.hash.ToString());
660  entry.pushKV("vout", (uint64_t)txin.prevout.n);
661  UniValue witness(UniValue::VARR);
662  for (unsigned int i = 0; i < txin.scriptWitness.stack.size(); i++) {
663  witness.push_back(HexStr(txin.scriptWitness.stack[i].begin(), txin.scriptWitness.stack[i].end()));
664  }
665  entry.pushKV("witness", witness);
666  entry.pushKV("scriptSig", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()));
667  entry.pushKV("sequence", (uint64_t)txin.nSequence);
668  entry.pushKV("error", strMessage);
669  vErrorsRet.push_back(entry);
670 }
671 
672 static UniValue combinerawtransaction(const JSONRPCRequest& request)
673 {
674 
675  if (request.fHelp || request.params.size() != 1)
676  throw std::runtime_error(
677  "combinerawtransaction [\"hexstring\",...]\n"
678  "\nCombine multiple partially signed transactions into one transaction.\n"
679  "The combined transaction may be another partially signed transaction or a \n"
680  "fully signed transaction."
681 
682  "\nArguments:\n"
683  "1. \"txs\" (string) A json array of hex strings of partially signed transactions\n"
684  " [\n"
685  " \"hexstring\" (string) A transaction hash\n"
686  " ,...\n"
687  " ]\n"
688 
689  "\nResult:\n"
690  "\"hex\" (string) The hex-encoded raw transaction with signature(s)\n"
691 
692  "\nExamples:\n"
693  + HelpExampleCli("combinerawtransaction", "[\"myhex1\", \"myhex2\", \"myhex3\"]")
694  );
695 
696 
697  UniValue txs = request.params[0].get_array();
698  std::vector<CMutableTransaction> txVariants(txs.size());
699 
700  for (unsigned int idx = 0; idx < txs.size(); idx++) {
701  if (!DecodeHexTx(txVariants[idx], txs[idx].get_str(), true)) {
702  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed for tx %d", idx));
703  }
704  }
705 
706  if (txVariants.empty()) {
707  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transactions");
708  }
709 
710  // mergedTx will end up with all the signatures; it
711  // starts as a clone of the rawtx:
712  CMutableTransaction mergedTx(txVariants[0]);
713 
714  // Fetch previous transactions (inputs):
715  CCoinsView viewDummy;
716  CCoinsViewCache view(&viewDummy);
717  {
718  LOCK(cs_main);
719  LOCK(mempool.cs);
720  CCoinsViewCache &viewChain = *pcoinsTip;
721  CCoinsViewMemPool viewMempool(&viewChain, mempool);
722  view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
723 
724  for (const CTxIn& txin : mergedTx.vin) {
725  view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
726  }
727 
728  view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
729  }
730 
731  // Use CTransaction for the constant parts of the
732  // transaction to avoid rehashing.
733  const CTransaction txConst(mergedTx);
734  // Sign what we can:
735  for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
736  CTxIn& txin = mergedTx.vin[i];
737  const Coin& coin = view.AccessCoin(txin.prevout);
738  if (coin.IsSpent()) {
739  throw JSONRPCError(RPC_VERIFY_ERROR, "Input not found or already spent");
740  }
741  SignatureData sigdata;
742 
743  // ... and merge in other signatures:
744  for (const CMutableTransaction& txv : txVariants) {
745  if (txv.vin.size() > i) {
746  sigdata.MergeSignatureData(DataFromTransaction(txv, i, coin.out));
747  }
748  }
750 
751  UpdateInput(txin, sigdata);
752  }
753 
754  return EncodeHexTx(mergedTx);
755 }
756 
757 UniValue SignTransaction(CMutableTransaction& mtx, const UniValue& prevTxsUnival, CBasicKeyStore *keystore, bool is_temp_keystore, const UniValue& hashType)
758 {
759  // Fetch previous transactions (inputs):
760  CCoinsView viewDummy;
761  CCoinsViewCache view(&viewDummy);
762  {
764  CCoinsViewCache &viewChain = *pcoinsTip;
765  CCoinsViewMemPool viewMempool(&viewChain, mempool);
766  view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
767 
768  for (const CTxIn& txin : mtx.vin) {
769  view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
770  }
771 
772  view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
773  }
774 
775  // Add previous txouts given in the RPC call:
776  if (!prevTxsUnival.isNull()) {
777  UniValue prevTxs = prevTxsUnival.get_array();
778  for (unsigned int idx = 0; idx < prevTxs.size(); ++idx) {
779  const UniValue& p = prevTxs[idx];
780  if (!p.isObject()) {
781  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
782  }
783 
784  UniValue prevOut = p.get_obj();
785 
786  RPCTypeCheckObj(prevOut,
787  {
788  {"txid", UniValueType(UniValue::VSTR)},
789  {"vout", UniValueType(UniValue::VNUM)},
790  {"scriptPubKey", UniValueType(UniValue::VSTR)},
791  });
792 
793  uint256 txid = ParseHashO(prevOut, "txid");
794 
795  int nOut = find_value(prevOut, "vout").get_int();
796  if (nOut < 0) {
797  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
798  }
799 
800  COutPoint out(txid, nOut);
801  std::vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
802  CScript scriptPubKey(pkData.begin(), pkData.end());
803 
804  {
805  const Coin& coin = view.AccessCoin(out);
806  if (!coin.IsSpent() && coin.out.scriptPubKey != scriptPubKey) {
807  std::string err("Previous output scriptPubKey mismatch:\n");
808  err = err + ScriptToAsmStr(coin.out.scriptPubKey) + "\nvs:\n"+
809  ScriptToAsmStr(scriptPubKey);
811  }
812  Coin newcoin;
813  newcoin.out.scriptPubKey = scriptPubKey;
814  newcoin.out.nValue = MAX_MONEY;
815  if (prevOut.exists("amount")) {
816  newcoin.out.nValue = AmountFromValue(find_value(prevOut, "amount"));
817  }
818  newcoin.nHeight = 1;
819  view.AddCoin(out, std::move(newcoin), true);
820  }
821 
822  // if redeemScript and private keys were given, add redeemScript to the keystore so it can be signed
823  if (is_temp_keystore && (scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash())) {
824  RPCTypeCheckObj(prevOut,
825  {
826  {"redeemScript", UniValueType(UniValue::VSTR)},
827  });
828  UniValue v = find_value(prevOut, "redeemScript");
829  if (!v.isNull()) {
830  std::vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
831  CScript redeemScript(rsData.begin(), rsData.end());
832  keystore->AddCScript(redeemScript);
833  // Automatically also add the P2WSH wrapped version of the script (to deal with P2SH-P2WSH).
834  keystore->AddCScript(GetScriptForWitness(redeemScript));
835  }
836  }
837  }
838  }
839 
840  int nHashType = ParseSighashString(hashType);
841 
842  bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
843 
844  // Script verification errors
845  UniValue vErrors(UniValue::VARR);
846 
847  // Use CTransaction for the constant parts of the
848  // transaction to avoid rehashing.
849  const CTransaction txConst(mtx);
850  // Sign what we can:
851  for (unsigned int i = 0; i < mtx.vin.size(); i++) {
852  CTxIn& txin = mtx.vin[i];
853  const Coin& coin = view.AccessCoin(txin.prevout);
854  if (coin.IsSpent()) {
855  TxInErrorToJSON(txin, vErrors, "Input not found or already spent");
856  continue;
857  }
858  const CScript& prevPubKey = coin.out.scriptPubKey;
859  const CAmount& amount = coin.out.nValue;
860 
861  SignatureData sigdata = DataFromTransaction(mtx, i, coin.out);
862  // Only sign SIGHASH_SINGLE if there's a corresponding output:
863  if (!fHashSingle || (i < mtx.vout.size())) {
864  ProduceSignature(*keystore, MutableTransactionSignatureCreator(&mtx, i, amount, nHashType), prevPubKey, sigdata);
865  }
866 
867  UpdateInput(txin, sigdata);
868 
869  // amount must be specified for valid segwit signature
870  if (amount == MAX_MONEY && !txin.scriptWitness.IsNull()) {
871  throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing amount for %s", coin.out.ToString()));
872  }
873 
874  ScriptError serror = SCRIPT_ERR_OK;
875  if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount), &serror)) {
876  if (serror == SCRIPT_ERR_INVALID_STACK_OPERATION) {
877  // Unable to sign input and verification failed (possible attempt to partially sign).
878  TxInErrorToJSON(txin, vErrors, "Unable to sign input, invalid stack size (possibly missing key)");
879  } else {
880  TxInErrorToJSON(txin, vErrors, ScriptErrorString(serror));
881  }
882  }
883  }
884  bool fComplete = vErrors.empty();
885 
886  UniValue result(UniValue::VOBJ);
887  result.pushKV("hex", EncodeHexTx(mtx));
888  result.pushKV("complete", fComplete);
889  if (!vErrors.empty()) {
890  result.pushKV("errors", vErrors);
891  }
892 
893  return result;
894 }
895 
896 static UniValue signrawtransactionwithkey(const JSONRPCRequest& request)
897 {
898  if (request.fHelp || request.params.size() < 2 || request.params.size() > 4)
899  throw std::runtime_error(
900  "signrawtransactionwithkey \"hexstring\" [\"privatekey1\",...] ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] sighashtype )\n"
901  "\nSign inputs for raw transaction (serialized, hex-encoded).\n"
902  "The second argument is an array of base58-encoded private\n"
903  "keys that will be the only keys used to sign the transaction.\n"
904  "The third optional argument (may be null) is an array of previous transaction outputs that\n"
905  "this transaction depends on but may not yet be in the block chain.\n"
906 
907  "\nArguments:\n"
908  "1. \"hexstring\" (string, required) The transaction hex string\n"
909  "2. \"privkeys\" (string, required) A json array of base58-encoded private keys for signing\n"
910  " [ (json array of strings)\n"
911  " \"privatekey\" (string) private key in base58-encoding\n"
912  " ,...\n"
913  " ]\n"
914  "3. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
915  " [ (json array of json objects, or 'null' if none provided)\n"
916  " {\n"
917  " \"txid\":\"id\", (string, required) The transaction id\n"
918  " \"vout\":n, (numeric, required) The output number\n"
919  " \"scriptPubKey\": \"hex\", (string, required) script key\n"
920  " \"redeemScript\": \"hex\", (string, required for P2SH or P2WSH) redeem script\n"
921  " \"amount\": value (numeric, required) The amount spent\n"
922  " }\n"
923  " ,...\n"
924  " ]\n"
925  "4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of:\n"
926  " \"ALL\"\n"
927  " \"NONE\"\n"
928  " \"SINGLE\"\n"
929  " \"ALL|ANYONECANPAY\"\n"
930  " \"NONE|ANYONECANPAY\"\n"
931  " \"SINGLE|ANYONECANPAY\"\n"
932 
933  "\nResult:\n"
934  "{\n"
935  " \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"
936  " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
937  " \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n"
938  " {\n"
939  " \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n"
940  " \"vout\" : n, (numeric) The index of the output to spent and used as input\n"
941  " \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n"
942  " \"sequence\" : n, (numeric) Script sequence number\n"
943  " \"error\" : \"text\" (string) Verification or signing error related to the input\n"
944  " }\n"
945  " ,...\n"
946  " ]\n"
947  "}\n"
948 
949  "\nExamples:\n"
950  + HelpExampleCli("signrawtransactionwithkey", "\"myhex\"")
951  + HelpExampleRpc("signrawtransactionwithkey", "\"myhex\"")
952  );
953 
954  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR, UniValue::VARR, UniValue::VSTR}, true);
955 
957  if (!DecodeHexTx(mtx, request.params[0].get_str(), true)) {
958  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
959  }
960 
961  CBasicKeyStore keystore;
962  const UniValue& keys = request.params[1].get_array();
963  for (unsigned int idx = 0; idx < keys.size(); ++idx) {
964  UniValue k = keys[idx];
965  CKey key = DecodeSecret(k.get_str());
966  if (!key.IsValid()) {
967  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
968  }
969  keystore.AddKey(key);
970  }
971 
972  return SignTransaction(mtx, request.params[2], &keystore, true, request.params[3]);
973 }
974 
976 {
977  // This method should be removed entirely in V0.19, along with the entries in the
978  // CRPCCommand table and rpc/client.cpp.
979  throw JSONRPCError(RPC_METHOD_DEPRECATED, "signrawtransaction was removed in v0.18.\n"
980  "Clients should transition to using signrawtransactionwithkey and signrawtransactionwithwallet");
981 }
982 
983 static UniValue sendrawtransaction(const JSONRPCRequest& request)
984 {
985  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
986  throw std::runtime_error(
987  "sendrawtransaction \"hexstring\" ( allowhighfees )\n"
988  "\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
989  "\nAlso see createrawtransaction and signrawtransactionwithkey calls.\n"
990  "\nArguments:\n"
991  "1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
992  "2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
993  "\nResult:\n"
994  "\"hex\" (string) The transaction hash in hex\n"
995  "\nExamples:\n"
996  "\nCreate a transaction\n"
997  + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
998  "Sign the transaction, and get back the hex\n"
999  + HelpExampleCli("signrawtransactionwithwallet", "\"myhex\"") +
1000  "\nSend the transaction (signed hex)\n"
1001  + HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
1002  "\nAs a JSON-RPC call\n"
1003  + HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
1004  );
1005 
1006  std::promise<void> promise;
1007 
1008  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL});
1009 
1010  // parse hex string from parameter
1011  CMutableTransaction mtx;
1012  if (!DecodeHexTx(mtx, request.params[0].get_str()))
1013  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
1014  CTransactionRef tx(MakeTransactionRef(std::move(mtx)));
1015  const uint256& hashTx = tx->GetHash();
1016 
1017  CAmount nMaxRawTxFee = maxTxFee;
1018  if (!request.params[1].isNull() && request.params[1].get_bool())
1019  nMaxRawTxFee = 0;
1020 
1021  { // cs_main scope
1022  LOCK(cs_main);
1023  CCoinsViewCache &view = *pcoinsTip;
1024  bool fHaveChain = false;
1025  for (size_t o = 0; !fHaveChain && o < tx->vout.size(); o++) {
1026  const Coin& existingCoin = view.AccessCoin(COutPoint(hashTx, o));
1027  fHaveChain = !existingCoin.IsSpent();
1028  }
1029  bool fHaveMempool = mempool.exists(hashTx);
1030  if (!fHaveMempool && !fHaveChain) {
1031  // push to local node and sync with wallets
1032  CValidationState state;
1033  bool fMissingInputs;
1034  if (!AcceptToMemoryPool(mempool, state, std::move(tx), &fMissingInputs,
1035  nullptr /* plTxnReplaced */, false /* bypass_limits */, nMaxRawTxFee)) {
1036  if (state.IsInvalid()) {
1038  } else {
1039  if (fMissingInputs) {
1040  throw JSONRPCError(RPC_TRANSACTION_ERROR, "Missing inputs");
1041  }
1043  }
1044  } else {
1045  // If wallet is enabled, ensure that the wallet has been made aware
1046  // of the new transaction prior to returning. This prevents a race
1047  // where a user might call sendrawtransaction with a transaction
1048  // to/from their wallet, immediately call some wallet RPC, and get
1049  // a stale result because callbacks have not yet been processed.
1051  promise.set_value();
1052  });
1053  }
1054  } else if (fHaveChain) {
1055  throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
1056  } else {
1057  // Make sure we don't block forever if re-sending
1058  // a transaction already in mempool.
1059  promise.set_value();
1060  }
1061 
1062  } // cs_main
1063 
1064  promise.get_future().wait();
1065 
1066  if(!g_connman)
1067  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
1068 
1069  CInv inv(MSG_TX, hashTx);
1070  g_connman->ForEachNode([&inv](CNode* pnode)
1071  {
1072  pnode->PushInventory(inv);
1073  });
1074 
1075  return hashTx.GetHex();
1076 }
1077 
1078 static UniValue testmempoolaccept(const JSONRPCRequest& request)
1079 {
1080  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
1081  throw std::runtime_error(
1082  // clang-format off
1083  "testmempoolaccept [\"rawtxs\"] ( allowhighfees )\n"
1084  "\nReturns if raw transaction (serialized, hex-encoded) would be accepted by mempool.\n"
1085  "\nThis checks if the transaction violates the consensus or policy rules.\n"
1086  "\nSee sendrawtransaction call.\n"
1087  "\nArguments:\n"
1088  "1. [\"rawtxs\"] (array, required) An array of hex strings of raw transactions.\n"
1089  " Length must be one for now.\n"
1090  "2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
1091  "\nResult:\n"
1092  "[ (array) The result of the mempool acceptance test for each raw transaction in the input array.\n"
1093  " Length is exactly one for now.\n"
1094  " {\n"
1095  " \"txid\" (string) The transaction hash in hex\n"
1096  " \"allowed\" (boolean) If the mempool allows this tx to be inserted\n"
1097  " \"reject-reason\" (string) Rejection string (only present when 'allowed' is false)\n"
1098  " }\n"
1099  "]\n"
1100  "\nExamples:\n"
1101  "\nCreate a transaction\n"
1102  + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
1103  "Sign the transaction, and get back the hex\n"
1104  + HelpExampleCli("signrawtransactionwithwallet", "\"myhex\"") +
1105  "\nTest acceptance of the transaction (signed hex)\n"
1106  + HelpExampleCli("testmempoolaccept", "\"signedhex\"") +
1107  "\nAs a JSON-RPC call\n"
1108  + HelpExampleRpc("testmempoolaccept", "[\"signedhex\"]")
1109  // clang-format on
1110  );
1111  }
1112 
1113  RPCTypeCheck(request.params, {UniValue::VARR, UniValue::VBOOL});
1114  if (request.params[0].get_array().size() != 1) {
1115  throw JSONRPCError(RPC_INVALID_PARAMETER, "Array must contain exactly one raw transaction for now");
1116  }
1117 
1118  CMutableTransaction mtx;
1119  if (!DecodeHexTx(mtx, request.params[0].get_array()[0].get_str())) {
1120  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
1121  }
1122  CTransactionRef tx(MakeTransactionRef(std::move(mtx)));
1123  const uint256& tx_hash = tx->GetHash();
1124 
1125  CAmount max_raw_tx_fee = ::maxTxFee;
1126  if (!request.params[1].isNull() && request.params[1].get_bool()) {
1127  max_raw_tx_fee = 0;
1128  }
1129 
1130  UniValue result(UniValue::VARR);
1131  UniValue result_0(UniValue::VOBJ);
1132  result_0.pushKV("txid", tx_hash.GetHex());
1133 
1134  CValidationState state;
1135  bool missing_inputs;
1136  bool test_accept_res;
1137  {
1138  LOCK(cs_main);
1139  test_accept_res = AcceptToMemoryPool(mempool, state, std::move(tx), &missing_inputs,
1140  nullptr /* plTxnReplaced */, false /* bypass_limits */, max_raw_tx_fee, /* test_accept */ true);
1141  }
1142  result_0.pushKV("allowed", test_accept_res);
1143  if (!test_accept_res) {
1144  if (state.IsInvalid()) {
1145  result_0.pushKV("reject-reason", strprintf("%i: %s", state.GetRejectCode(), state.GetRejectReason()));
1146  } else if (missing_inputs) {
1147  result_0.pushKV("reject-reason", "missing-inputs");
1148  } else {
1149  result_0.pushKV("reject-reason", state.GetRejectReason());
1150  }
1151  }
1152 
1153  result.push_back(std::move(result_0));
1154  return result;
1155 }
1156 
1157 static std::string WriteHDKeypath(std::vector<uint32_t>& keypath)
1158 {
1159  std::string keypath_str = "m";
1160  for (uint32_t num : keypath) {
1161  keypath_str += "/";
1162  bool hardened = false;
1163  if (num & 0x80000000) {
1164  hardened = true;
1165  num &= ~0x80000000;
1166  }
1167 
1168  keypath_str += std::to_string(num);
1169  if (hardened) {
1170  keypath_str += "'";
1171  }
1172  }
1173  return keypath_str;
1174 }
1175 
1177 {
1178  if (request.fHelp || request.params.size() != 1)
1179  throw std::runtime_error(
1180  "decodepsbt \"psbt\"\n"
1181  "\nReturn a JSON object representing the serialized, base64-encoded partially signed Bitcoin transaction.\n"
1182 
1183  "\nArguments:\n"
1184  "1. \"psbt\" (string, required) The PSBT base64 string\n"
1185 
1186  "\nResult:\n"
1187  "{\n"
1188  " \"tx\" : { (json object) The decoded network-serialized unsigned transaction.\n"
1189  " ... The layout is the same as the output of decoderawtransaction.\n"
1190  " },\n"
1191  " \"unknown\" : { (json object) The unknown global fields\n"
1192  " \"key\" : \"value\" (key-value pair) An unknown key-value pair\n"
1193  " ...\n"
1194  " },\n"
1195  " \"inputs\" : [ (array of json objects)\n"
1196  " {\n"
1197  " \"non_witness_utxo\" : { (json object, optional) Decoded network transaction for non-witness UTXOs\n"
1198  " ...\n"
1199  " },\n"
1200  " \"witness_utxo\" : { (json object, optional) Transaction output for witness UTXOs\n"
1201  " \"amount\" : x.xxx, (numeric) The value in " + CURRENCY_UNIT + "\n"
1202  " \"scriptPubKey\" : { (json object)\n"
1203  " \"asm\" : \"asm\", (string) The asm\n"
1204  " \"hex\" : \"hex\", (string) The hex\n"
1205  " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
1206  " \"address\" : \"address\" (string) BSHA3 address if there is one\n"
1207  " }\n"
1208  " },\n"
1209  " \"partial_signatures\" : { (json object, optional)\n"
1210  " \"pubkey\" : \"signature\", (string) The public key and signature that corresponds to it.\n"
1211  " ,...\n"
1212  " }\n"
1213  " \"sighash\" : \"type\", (string, optional) The sighash type to be used\n"
1214  " \"redeem_script\" : { (json object, optional)\n"
1215  " \"asm\" : \"asm\", (string) The asm\n"
1216  " \"hex\" : \"hex\", (string) The hex\n"
1217  " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
1218  " }\n"
1219  " \"witness_script\" : { (json object, optional)\n"
1220  " \"asm\" : \"asm\", (string) The asm\n"
1221  " \"hex\" : \"hex\", (string) The hex\n"
1222  " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
1223  " }\n"
1224  " \"bip32_derivs\" : { (json object, optional)\n"
1225  " \"pubkey\" : { (json object, optional) The public key with the derivation path as the value.\n"
1226  " \"master_fingerprint\" : \"fingerprint\" (string) The fingerprint of the master key\n"
1227  " \"path\" : \"path\", (string) The path\n"
1228  " }\n"
1229  " ,...\n"
1230  " }\n"
1231  " \"final_scriptsig\" : { (json object, optional)\n"
1232  " \"asm\" : \"asm\", (string) The asm\n"
1233  " \"hex\" : \"hex\", (string) The hex\n"
1234  " }\n"
1235  " \"final_scriptwitness\": [\"hex\", ...] (array of string) hex-encoded witness data (if any)\n"
1236  " \"unknown\" : { (json object) The unknown global fields\n"
1237  " \"key\" : \"value\" (key-value pair) An unknown key-value pair\n"
1238  " ...\n"
1239  " },\n"
1240  " }\n"
1241  " ,...\n"
1242  " ]\n"
1243  " \"outputs\" : [ (array of json objects)\n"
1244  " {\n"
1245  " \"redeem_script\" : { (json object, optional)\n"
1246  " \"asm\" : \"asm\", (string) The asm\n"
1247  " \"hex\" : \"hex\", (string) The hex\n"
1248  " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
1249  " }\n"
1250  " \"witness_script\" : { (json object, optional)\n"
1251  " \"asm\" : \"asm\", (string) The asm\n"
1252  " \"hex\" : \"hex\", (string) The hex\n"
1253  " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
1254  " }\n"
1255  " \"bip32_derivs\" : [ (array of json objects, optional)\n"
1256  " {\n"
1257  " \"pubkey\" : \"pubkey\", (string) The public key this path corresponds to\n"
1258  " \"master_fingerprint\" : \"fingerprint\" (string) The fingerprint of the master key\n"
1259  " \"path\" : \"path\", (string) The path\n"
1260  " }\n"
1261  " }\n"
1262  " ,...\n"
1263  " ],\n"
1264  " \"unknown\" : { (json object) The unknown global fields\n"
1265  " \"key\" : \"value\" (key-value pair) An unknown key-value pair\n"
1266  " ...\n"
1267  " },\n"
1268  " }\n"
1269  " ,...\n"
1270  " ]\n"
1271  " \"fee\" : fee (numeric, optional) The transaction fee paid if all UTXOs slots in the PSBT have been filled.\n"
1272  "}\n"
1273 
1274  "\nExamples:\n"
1275  + HelpExampleCli("decodepsbt", "\"psbt\"")
1276  );
1277 
1278  RPCTypeCheck(request.params, {UniValue::VSTR});
1279 
1280  // Unserialize the transactions
1282  std::string error;
1283  if (!DecodePSBT(psbtx, request.params[0].get_str(), error)) {
1284  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error));
1285  }
1286 
1287  UniValue result(UniValue::VOBJ);
1288 
1289  // Add the decoded tx
1290  UniValue tx_univ(UniValue::VOBJ);
1291  TxToUniv(CTransaction(*psbtx.tx), uint256(), tx_univ, false);
1292  result.pushKV("tx", tx_univ);
1293 
1294  // Unknown data
1295  UniValue unknowns(UniValue::VOBJ);
1296  for (auto entry : psbtx.unknown) {
1297  unknowns.pushKV(HexStr(entry.first), HexStr(entry.second));
1298  }
1299  result.pushKV("unknown", unknowns);
1300 
1301  // inputs
1302  CAmount total_in = 0;
1303  bool have_all_utxos = true;
1304  UniValue inputs(UniValue::VARR);
1305  for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
1306  const PSBTInput& input = psbtx.inputs[i];
1308  // UTXOs
1309  if (!input.witness_utxo.IsNull()) {
1310  const CTxOut& txout = input.witness_utxo;
1311 
1312  UniValue out(UniValue::VOBJ);
1313 
1314  out.pushKV("amount", ValueFromAmount(txout.nValue));
1315  total_in += txout.nValue;
1316 
1318  ScriptToUniv(txout.scriptPubKey, o, true);
1319  out.pushKV("scriptPubKey", o);
1320  in.pushKV("witness_utxo", out);
1321  } else if (input.non_witness_utxo) {
1322  UniValue non_wit(UniValue::VOBJ);
1323  TxToUniv(*input.non_witness_utxo, uint256(), non_wit, false);
1324  in.pushKV("non_witness_utxo", non_wit);
1325  total_in += input.non_witness_utxo->vout[psbtx.tx->vin[i].prevout.n].nValue;
1326  } else {
1327  have_all_utxos = false;
1328  }
1329 
1330  // Partial sigs
1331  if (!input.partial_sigs.empty()) {
1332  UniValue partial_sigs(UniValue::VOBJ);
1333  for (const auto& sig : input.partial_sigs) {
1334  partial_sigs.pushKV(HexStr(sig.second.first), HexStr(sig.second.second));
1335  }
1336  in.pushKV("partial_signatures", partial_sigs);
1337  }
1338 
1339  // Sighash
1340  if (input.sighash_type > 0) {
1341  in.pushKV("sighash", SighashToStr((unsigned char)input.sighash_type));
1342  }
1343 
1344  // Redeem script and witness script
1345  if (!input.redeem_script.empty()) {
1347  ScriptToUniv(input.redeem_script, r, false);
1348  in.pushKV("redeem_script", r);
1349  }
1350  if (!input.witness_script.empty()) {
1352  ScriptToUniv(input.witness_script, r, false);
1353  in.pushKV("witness_script", r);
1354  }
1355 
1356  // keypaths
1357  if (!input.hd_keypaths.empty()) {
1358  UniValue keypaths(UniValue::VARR);
1359  for (auto entry : input.hd_keypaths) {
1360  UniValue keypath(UniValue::VOBJ);
1361  keypath.pushKV("pubkey", HexStr(entry.first));
1362 
1363  keypath.pushKV("master_fingerprint", strprintf("%08x", ReadBE32(entry.second.fingerprint)));
1364  keypath.pushKV("path", WriteHDKeypath(entry.second.path));
1365  keypaths.push_back(keypath);
1366  }
1367  in.pushKV("bip32_derivs", keypaths);
1368  }
1369 
1370  // Final scriptSig and scriptwitness
1371  if (!input.final_script_sig.empty()) {
1372  UniValue scriptsig(UniValue::VOBJ);
1373  scriptsig.pushKV("asm", ScriptToAsmStr(input.final_script_sig, true));
1374  scriptsig.pushKV("hex", HexStr(input.final_script_sig));
1375  in.pushKV("final_scriptSig", scriptsig);
1376  }
1377  if (!input.final_script_witness.IsNull()) {
1378  UniValue txinwitness(UniValue::VARR);
1379  for (const auto& item : input.final_script_witness.stack) {
1380  txinwitness.push_back(HexStr(item.begin(), item.end()));
1381  }
1382  in.pushKV("final_scriptwitness", txinwitness);
1383  }
1384 
1385  // Unknown data
1386  if (input.unknown.size() > 0) {
1387  UniValue unknowns(UniValue::VOBJ);
1388  for (auto entry : input.unknown) {
1389  unknowns.pushKV(HexStr(entry.first), HexStr(entry.second));
1390  }
1391  in.pushKV("unknown", unknowns);
1392  }
1393 
1394  inputs.push_back(in);
1395  }
1396  result.pushKV("inputs", inputs);
1397 
1398  // outputs
1399  CAmount output_value = 0;
1400  UniValue outputs(UniValue::VARR);
1401  for (unsigned int i = 0; i < psbtx.outputs.size(); ++i) {
1402  const PSBTOutput& output = psbtx.outputs[i];
1403  UniValue out(UniValue::VOBJ);
1404  // Redeem script and witness script
1405  if (!output.redeem_script.empty()) {
1407  ScriptToUniv(output.redeem_script, r, false);
1408  out.pushKV("redeem_script", r);
1409  }
1410  if (!output.witness_script.empty()) {
1412  ScriptToUniv(output.witness_script, r, false);
1413  out.pushKV("witness_script", r);
1414  }
1415 
1416  // keypaths
1417  if (!output.hd_keypaths.empty()) {
1418  UniValue keypaths(UniValue::VARR);
1419  for (auto entry : output.hd_keypaths) {
1420  UniValue keypath(UniValue::VOBJ);
1421  keypath.pushKV("pubkey", HexStr(entry.first));
1422  keypath.pushKV("master_fingerprint", strprintf("%08x", ReadBE32(entry.second.fingerprint)));
1423  keypath.pushKV("path", WriteHDKeypath(entry.second.path));
1424  keypaths.push_back(keypath);
1425  }
1426  out.pushKV("bip32_derivs", keypaths);
1427  }
1428 
1429  // Unknown data
1430  if (output.unknown.size() > 0) {
1431  UniValue unknowns(UniValue::VOBJ);
1432  for (auto entry : output.unknown) {
1433  unknowns.pushKV(HexStr(entry.first), HexStr(entry.second));
1434  }
1435  out.pushKV("unknown", unknowns);
1436  }
1437 
1438  outputs.push_back(out);
1439 
1440  // Fee calculation
1441  output_value += psbtx.tx->vout[i].nValue;
1442  }
1443  result.pushKV("outputs", outputs);
1444  if (have_all_utxos) {
1445  result.pushKV("fee", ValueFromAmount(total_in - output_value));
1446  }
1447 
1448  return result;
1449 }
1450 
1452 {
1453  if (request.fHelp || request.params.size() != 1)
1454  throw std::runtime_error(
1455  "combinepsbt [\"psbt\",...]\n"
1456  "\nCombine multiple partially signed Bitcoin transactions into one transaction.\n"
1457  "Implements the Combiner role.\n"
1458  "\nArguments:\n"
1459  "1. \"txs\" (string) A json array of base64 strings of partially signed transactions\n"
1460  " [\n"
1461  " \"psbt\" (string) A base64 string of a PSBT\n"
1462  " ,...\n"
1463  " ]\n"
1464 
1465  "\nResult:\n"
1466  " \"psbt\" (string) The base64-encoded partially signed transaction\n"
1467  "\nExamples:\n"
1468  + HelpExampleCli("combinepsbt", "[\"mybase64_1\", \"mybase64_2\", \"mybase64_3\"]")
1469  );
1470 
1471  RPCTypeCheck(request.params, {UniValue::VARR}, true);
1472 
1473  // Unserialize the transactions
1474  std::vector<PartiallySignedTransaction> psbtxs;
1475  UniValue txs = request.params[0].get_array();
1476  for (unsigned int i = 0; i < txs.size(); ++i) {
1478  std::string error;
1479  if (!DecodePSBT(psbtx, txs[i].get_str(), error)) {
1480  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error));
1481  }
1482  psbtxs.push_back(psbtx);
1483  }
1484 
1485  PartiallySignedTransaction merged_psbt(psbtxs[0]); // Copy the first one
1486 
1487  // Merge
1488  for (auto it = std::next(psbtxs.begin()); it != psbtxs.end(); ++it) {
1489  if (*it != merged_psbt) {
1490  throw JSONRPCError(RPC_INVALID_PARAMETER, "PSBTs do not refer to the same transactions.");
1491  }
1492  merged_psbt.Merge(*it);
1493  }
1494  if (!merged_psbt.IsSane()) {
1495  throw JSONRPCError(RPC_INVALID_PARAMETER, "Merged PSBT is inconsistent");
1496  }
1497 
1498  UniValue result(UniValue::VOBJ);
1499  CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
1500  ssTx << merged_psbt;
1501  return EncodeBase64((unsigned char*)ssTx.data(), ssTx.size());
1502 }
1503 
1505 {
1506  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
1507  throw std::runtime_error(
1508  "finalizepsbt \"psbt\" ( extract )\n"
1509  "Finalize the inputs of a PSBT. If the transaction is fully signed, it will produce a\n"
1510  "network serialized transaction which can be broadcast with sendrawtransaction. Otherwise a PSBT will be\n"
1511  "created which has the final_scriptSig and final_scriptWitness fields filled for inputs that are complete.\n"
1512  "Implements the Finalizer and Extractor roles.\n"
1513  "\nArguments:\n"
1514  "1. \"psbt\" (string) A base64 string of a PSBT\n"
1515  "2. \"extract\" (boolean, optional, default=true) If true and the transaction is complete, \n"
1516  " extract and return the complete transaction in normal network serialization instead of the PSBT.\n"
1517 
1518  "\nResult:\n"
1519  "{\n"
1520  " \"psbt\" : \"value\", (string) The base64-encoded partially signed transaction if not extracted\n"
1521  " \"hex\" : \"value\", (string) The hex-encoded network transaction if extracted\n"
1522  " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
1523  " ]\n"
1524  "}\n"
1525 
1526  "\nExamples:\n"
1527  + HelpExampleCli("finalizepsbt", "\"psbt\"")
1528  );
1529 
1530  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL}, true);
1531 
1532  // Unserialize the transactions
1534  std::string error;
1535  if (!DecodePSBT(psbtx, request.params[0].get_str(), error)) {
1536  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error));
1537  }
1538 
1539  // Get all of the previous transactions
1540  bool complete = true;
1541  for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
1542  PSBTInput& input = psbtx.inputs.at(i);
1543 
1544  complete &= SignPSBTInput(DUMMY_SIGNING_PROVIDER, *psbtx.tx, input, i, 1);
1545  }
1546 
1547  UniValue result(UniValue::VOBJ);
1548  CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
1549  bool extract = request.params[1].isNull() || (!request.params[1].isNull() && request.params[1].get_bool());
1550  if (complete && extract) {
1551  CMutableTransaction mtx(*psbtx.tx);
1552  for (unsigned int i = 0; i < mtx.vin.size(); ++i) {
1553  mtx.vin[i].scriptSig = psbtx.inputs[i].final_script_sig;
1554  mtx.vin[i].scriptWitness = psbtx.inputs[i].final_script_witness;
1555  }
1556  ssTx << mtx;
1557  result.pushKV("hex", HexStr(ssTx.begin(), ssTx.end()));
1558  } else {
1559  ssTx << psbtx;
1560  result.pushKV("psbt", EncodeBase64((unsigned char*)ssTx.data(), ssTx.size()));
1561  }
1562  result.pushKV("complete", complete);
1563 
1564  return result;
1565 }
1566 
1568 {
1569  if (request.fHelp || request.params.size() < 2 || request.params.size() > 4)
1570  throw std::runtime_error(
1571  "createpsbt [{\"txid\":\"id\",\"vout\":n},...] [{\"address\":amount},{\"data\":\"hex\"},...] ( locktime ) ( replaceable )\n"
1572  "\nCreates a transaction in the Partially Signed Transaction format.\n"
1573  "Implements the Creator role.\n"
1574  "\nArguments:\n"
1575  "1. \"inputs\" (array, required) A json array of json objects\n"
1576  " [\n"
1577  " {\n"
1578  " \"txid\":\"id\", (string, required) The transaction id\n"
1579  " \"vout\":n, (numeric, required) The output number\n"
1580  " \"sequence\":n (numeric, optional) The sequence number\n"
1581  " } \n"
1582  " ,...\n"
1583  " ]\n"
1584  "2. \"outputs\" (array, required) a json array with outputs (key-value pairs)\n"
1585  " [\n"
1586  " {\n"
1587  " \"address\": x.xxx, (obj, optional) A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT + "\n"
1588  " },\n"
1589  " {\n"
1590  " \"data\": \"hex\" (obj, optional) A key-value pair. The key must be \"data\", the value is hex-encoded data\n"
1591  " }\n"
1592  " ,... More key-value pairs of the above form. For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n"
1593  " accepted as second parameter.\n"
1594  " ]\n"
1595  "3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n"
1596  "4. replaceable (boolean, optional, default=false) Marks this transaction as BIP125 replaceable.\n"
1597  " 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"
1598  "\nResult:\n"
1599  " \"psbt\" (string) The resulting raw transaction (base64-encoded string)\n"
1600  "\nExamples:\n"
1601  + HelpExampleCli("createpsbt", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"")
1602  );
1603 
1604 
1605  RPCTypeCheck(request.params, {
1606  UniValue::VARR,
1607  UniValueType(), // ARR or OBJ, checked later
1608  UniValue::VNUM,
1609  UniValue::VBOOL,
1610  }, true
1611  );
1612 
1613  CMutableTransaction rawTx = ConstructTransaction(request.params[0], request.params[1], request.params[2], request.params[3]);
1614 
1615  // Make a blank psbt
1617  psbtx.tx = rawTx;
1618  for (unsigned int i = 0; i < rawTx.vin.size(); ++i) {
1619  psbtx.inputs.push_back(PSBTInput());
1620  }
1621  for (unsigned int i = 0; i < rawTx.vout.size(); ++i) {
1622  psbtx.outputs.push_back(PSBTOutput());
1623  }
1624 
1625  // Serialize the PSBT
1626  CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
1627  ssTx << psbtx;
1628 
1629  return EncodeBase64((unsigned char*)ssTx.data(), ssTx.size());
1630 }
1631 
1633 {
1634  if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)
1635  throw std::runtime_error(
1636  "converttopsbt \"hexstring\" ( permitsigdata iswitness )\n"
1637  "\nConverts a network serialized transaction to a PSBT. This should be used only with createrawtransaction and fundrawtransaction\n"
1638  "createpsbt and walletcreatefundedpsbt should be used for new applications.\n"
1639  "\nArguments:\n"
1640  "1. \"hexstring\" (string, required) The hex string of a raw transaction\n"
1641  "2. permitsigdata (boolean, optional, default=false) If true, any signatures in the input will be discarded and conversion.\n"
1642  " will continue. If false, RPC will fail if any signatures are present.\n"
1643  "3. iswitness (boolean, optional) Whether the transaction hex is a serialized witness transaction.\n"
1644  " If iswitness is not present, heuristic tests will be used in decoding. If true, only witness deserializaion\n"
1645  " will be tried. If false, only non-witness deserialization will be tried. Only has an effect if\n"
1646  " permitsigdata is true.\n"
1647  "\nResult:\n"
1648  " \"psbt\" (string) The resulting raw transaction (base64-encoded string)\n"
1649  "\nExamples:\n"
1650  "\nCreate a transaction\n"
1651  + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") +
1652  "\nConvert the transaction to a PSBT\n"
1653  + HelpExampleCli("converttopsbt", "\"rawtransaction\"")
1654  );
1655 
1656 
1657  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL, UniValue::VBOOL}, true);
1658 
1659  // parse hex string from parameter
1661  bool permitsigdata = request.params[1].isNull() ? false : request.params[1].get_bool();
1662  bool witness_specified = !request.params[2].isNull();
1663  bool iswitness = witness_specified ? request.params[2].get_bool() : false;
1664  bool try_witness = permitsigdata ? (witness_specified ? iswitness : true) : false;
1665  bool try_no_witness = permitsigdata ? (witness_specified ? !iswitness : true) : true;
1666  if (!DecodeHexTx(tx, request.params[0].get_str(), try_no_witness, try_witness)) {
1667  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
1668  }
1669 
1670  // Remove all scriptSigs and scriptWitnesses from inputs
1671  for (CTxIn& input : tx.vin) {
1672  if ((!input.scriptSig.empty() || !input.scriptWitness.IsNull()) && (request.params[1].isNull() || (!request.params[1].isNull() && request.params[1].get_bool()))) {
1673  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Inputs must not have scriptSigs and scriptWitnesses");
1674  }
1675  input.scriptSig.clear();
1676  input.scriptWitness.SetNull();
1677  }
1678 
1679  // Make a blank psbt
1681  psbtx.tx = tx;
1682  for (unsigned int i = 0; i < tx.vin.size(); ++i) {
1683  psbtx.inputs.push_back(PSBTInput());
1684  }
1685  for (unsigned int i = 0; i < tx.vout.size(); ++i) {
1686  psbtx.outputs.push_back(PSBTOutput());
1687  }
1688 
1689  // Serialize the PSBT
1690  CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
1691  ssTx << psbtx;
1692 
1693  return EncodeBase64((unsigned char*)ssTx.data(), ssTx.size());
1694 }
1695 
1696 // clang-format off
1697 static const CRPCCommand commands[] =
1698 { // category name actor (function) argNames
1699  // --------------------- ------------------------ ----------------------- ----------
1700  { "rawtransactions", "getrawtransaction", &getrawtransaction, {"txid","verbose","blockhash"} },
1701  { "rawtransactions", "createrawtransaction", &createrawtransaction, {"inputs","outputs","locktime","replaceable"} },
1702  { "rawtransactions", "decoderawtransaction", &decoderawtransaction, {"hexstring","iswitness"} },
1703  { "rawtransactions", "decodescript", &decodescript, {"hexstring"} },
1704  { "rawtransactions", "sendrawtransaction", &sendrawtransaction, {"hexstring","allowhighfees"} },
1705  { "rawtransactions", "combinerawtransaction", &combinerawtransaction, {"txs"} },
1706  { "hidden", "signrawtransaction", &signrawtransaction, {"hexstring","prevtxs","privkeys","sighashtype"} },
1707  { "rawtransactions", "signrawtransactionwithkey", &signrawtransactionwithkey, {"hexstring","privkeys","prevtxs","sighashtype"} },
1708  { "rawtransactions", "testmempoolaccept", &testmempoolaccept, {"rawtxs","allowhighfees"} },
1709  { "rawtransactions", "decodepsbt", &decodepsbt, {"psbt"} },
1710  { "rawtransactions", "combinepsbt", &combinepsbt, {"txs"} },
1711  { "rawtransactions", "finalizepsbt", &finalizepsbt, {"psbt", "extract"} },
1712  { "rawtransactions", "createpsbt", &createpsbt, {"inputs","outputs","locktime","replaceable"} },
1713  { "rawtransactions", "converttopsbt", &converttopsbt, {"hexstring","permitsigdata","iswitness"} },
1714 
1715  { "blockchain", "gettxoutproof", &gettxoutproof, {"txids", "blockhash"} },
1716  { "blockchain", "verifytxoutproof", &verifytxoutproof, {"proof"} },
1717 };
1718 // clang-format on
1719 
1721 {
1722  for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
1723  t.appendCommand(commands[vcidx].name, &commands[vcidx]);
1724 }
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:250
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull, bool fStrict)
Definition: server.cpp:75
Aliases for backward compatibility.
Definition: protocol.h:62
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: server.cpp:126
CTxMemPool mempool
std::vector< unsigned char > ParseHexO(const UniValue &o, std::string strKey)
Definition: server.cpp:139
bool IsSpent() const
Definition: coins.h:75
bool isObject() const
Definition: univalue.h:85
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool potential_overwrite)
Add a coin.
Definition: coins.cpp:66
bool GetTransaction(const uint256 &hash, CTransactionRef &txOut, const Consensus::Params &consensusParams, uint256 &hashBlock, bool fAllowSlow, CBlockIndex *blockIndex)
Return transaction in txOut, and if it was found inside a block, its hash is placed in hashBlock...
Definition: validation.cpp:998
Bitcoin RPC command dispatcher.
Definition: server.h:143
int64_t GetBlockTime() const
Definition: chain.h:297
enum ScriptError_t ScriptError
CScript scriptPubKey
Definition: transaction.h:135
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:207
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or a pruned one if not found.
Definition: coins.cpp:116
bool get_bool() const
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:27
boost::optional< CMutableTransaction > tx
Definition: sign.h:559
A UTXO entry.
Definition: coins.h:29
Definition: block.h:74
#define strprintf
Definition: tinyformat.h:1066
CAmount maxTxFee
Absolute maximum transaction fee (in satoshis) used by wallet and mempool (rejects high fee in sendra...
Definition: validation.cpp:242
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:385
std::vector< CTxIn > vin
Definition: transaction.h:362
CScriptWitness scriptWitness
Only serialized through CTransaction.
Definition: transaction.h:67
void ScriptToUniv(const CScript &script, UniValue &out, bool include_address)
Definition: core_write.cpp:138
int Height() const
Return the maximal height in the chain.
Definition: chain.h:476
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:324
CTxOut out
unspent transaction output
Definition: coins.h:33
UniValue converttopsbt(const JSONRPCRequest &request)
UniValue ValueFromAmount(const CAmount &amount)
Definition: core_write.cpp:19
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
bool IsSane() const
Definition: sign.cpp:532
bool AddCScript(const CScript &redeemScript) override
Support for BIP 0013 : see https://github.com/bitcoin/bips/blob/master/bip-0013.mediawiki.
Definition: keystore.cpp:86
value_type * data()
Definition: streams.h:321
std::vector< std::vector< unsigned char > > stack
Definition: script.h:566
const std::string & get_str() const
bool isNum() const
Definition: univalue.h:83
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: server.cpp:516
const UniValue & get_array() const
const std::string CURRENCY_UNIT
Definition: feerate.cpp:10
txnouttype Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char >> &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:90
bool isStr() const
Definition: univalue.h:82
A version of CTransaction with the PSBT format.
Definition: sign.h:557
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:221
int64_t get_int64() const
std::string ToString() const
Definition: transaction.cpp:52
CTxOut witness_utxo
Definition: sign.h:222
A signature creator for transactions.
Definition: sign.h:83
bool pushKVs(const UniValue &obj)
Definition: univalue.cpp:146
const std::vector< std::string > & getKeys() const
bool IsNull() const
Definition: script.h:571
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:402
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:285
UniValue finalizepsbt(const JSONRPCRequest &request)
CScript redeem_script
Definition: sign.h:223
bool IsNull() const
Definition: uint256.h:32
void PushInventory(const CInv &inv)
Definition: net.h:847
Invalid, missing or duplicate parameter.
Definition: protocol.h:52
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: server.cpp:117
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:234
UniValue decodepsbt(const JSONRPCRequest &request)
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransactionRef &tx, bool *pfMissingInputs, std::list< CTransactionRef > *plTxnReplaced, bool bypass_limits, const CAmount nAbsurdFee, bool test_accept)
(try to) add transaction to memory pool plTxnReplaced will be appended to with all transactions repla...
Definition: validation.cpp:986
bool DecodePSBT(PartiallySignedTransaction &psbt, const std::string &base64_tx, std::string &error)
Definition: core_read.cpp:179
bool IsNull() const
Definition: transaction.h:158
const char * ScriptErrorString(const ScriptError serror)
Definition: script_error.cpp:8
std::unique_ptr< CCoinsViewCache > pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: validation.cpp:298
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
A structure for PSBTs which contains per output information.
Definition: sign.h:444
General error during transaction or block submission.
Definition: protocol.h:55
uint32_t nHeight
at which height this containing transaction was included in the active block chain ...
Definition: coins.h:39
std::vector< PSBTOutput > outputs
Definition: sign.h:561
iterator end()
Definition: prevector.h:303
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: sign.h:448
#define LOCK2(cs1, cs2)
Definition: sync.h:182
std::string name
Definition: server.h:135
Used to relay blocks as header + vector<merkle branch> to filtered nodes.
Definition: merkleblock.h:133
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
CCriticalSection cs_main
Definition: validation.cpp:216
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode=false)
Create the assembly string representation of a CScript object.
Definition: core_write.cpp:87
size_type size() const
Definition: streams.h:312
bool IsInvalid() const
Definition: validation.h:68
Abstract view on the open txout dataset.
Definition: coins.h:145
UniValue params
Definition: server.h:44
bool exists(const uint256 &hash) const
Definition: txmempool.h:650
int ParseSighashString(const UniValue &sighash)
Definition: core_read.cpp:215
An input of a transaction.
Definition: transaction.h:61
boost::variant< CNoDestination, CKeyID, CScriptID, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:123
std::map< std::vector< unsigned char >, std::vector< unsigned char > > unknown
Definition: sign.h:229
#define LOCK(cs)
Definition: sync.h:181
std::unique_ptr< TxIndex > g_txindex
The global transaction index, used in GetTransaction. May be null.
Definition: txindex.cpp:17
bool exists(const std::string &key) const
Definition: univalue.h:76
bool AddKey(const CKey &key)
Definition: keystore.h:61
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:463
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: sign.h:227
std::map< CKeyID, SigPair > partial_sigs
Definition: sign.h:228
An encapsulated public key.
Definition: pubkey.h:30
std::string GetRejectReason() const
Definition: validation.h:88
uint32_t n
Definition: transaction.h:22
Unexpected type was passed as parameter.
Definition: protocol.h:49
CScriptWitness final_script_witness
Definition: sign.h:226
std::map< std::vector< unsigned char >, std::vector< unsigned char > > unknown
Definition: sign.h:449
bool empty() const
Definition: univalue.h:67
auto end
Definition: rpcwallet.cpp:1068
std::string SighashToStr(unsigned char sighash_type)
Definition: core_write.cpp:73
General application defined errors.
Definition: protocol.h:48
A structure for PSBTs which contain per-input information.
Definition: sign.h:219
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
void RPCTypeCheck(const UniValue &params, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: server.cpp:51
void CallFunctionInValidationInterfaceQueue(std::function< void()> func)
Pushes a function to callback onto the notification queue, guaranteeing any callbacks generated prior...
An output of a transaction.
Definition: transaction.h:131
int get_int() const
void MergeSignatureData(SignatureData sigdata)
Definition: sign.cpp:408
std::string ToString() const
Definition: uint256.cpp:62
Invalid address or key.
Definition: protocol.h:50
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:288
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: server.cpp:511
CAmount AmountFromValue(const UniValue &value)
Definition: server.cpp:105
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:18
void SetNull()
Definition: script.h:573
std::vector< CTxOut > vout
Definition: transaction.h:363
bool isNull() const
Definition: univalue.h:78
std::vector< PSBTInput > inputs
Definition: sign.h:560
bool isTrue() const
Definition: univalue.h:79
void RegisterRawTransactionRPCCommands(CRPCTable &t)
Register raw transaction RPC commands.
CCriticalSection cs
Definition: txmempool.h:487
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string strName)
Definition: server.cpp:130
RPC method is deprecated.
Definition: protocol.h:59
int sighash_type
Definition: sign.h:230
CScript scriptSig
Definition: transaction.h:65
bool fHelp
Definition: server.h:45
txnouttype
Definition: standard.h:56
Capture information about block/transaction validation.
Definition: validation.h:26
#define extract(n)
Extract the lowest 64 bits of (c0,c1,c2) into n, and left shift the number 64 bits.
256-bit opaque blob.
Definition: uint256.h:122
CTxDestination DecodeDestination(const std::string &str)
Definition: key_io.cpp:214
std::vector< CTransactionRef > vtx
Definition: block.h:78
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
Definition: validation.cpp:453
const_iterator end() const
Definition: streams.h:310
#define ARRAYLEN(array)
UniValue combinepsbt(const JSONRPCRequest &request)
const_iterator begin() const
Definition: streams.h:308
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn, const CTxOut &txout)
Extract signature data from a transaction input, and insert it.
Definition: sign.cpp:337
CScript witness_script
Definition: sign.h:447
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:170
const CChainParams & Params()
Return the currently selected parameters.
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:384
int RPCSerializationFlags()
Definition: server.cpp:548
uint32_t nSequence
Definition: transaction.h:66
bool SignalsOptInRBF(const CTransaction &tx)
Definition: rbf.cpp:7
const UniValue & get_obj() const
CScript redeem_script
Definition: sign.h:446
bool empty() const
Definition: prevector.h:297
CTransactionRef non_witness_utxo
Definition: sign.h:221
void UpdateInput(CTxIn &input, const SignatureData &data)
Definition: sign.cpp:402
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness=false, bool try_witness=true)
Definition: core_read.cpp:113
std::string GetHex() const
Definition: uint256.cpp:21
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Definition: core_write.cpp:131
UniValue SignTransaction(CMutableTransaction &mtx, const UniValue &prevTxsUnival, CBasicKeyStore *keystore, bool is_temp_keystore, const UniValue &hashType)
Sign a transaction with the given keystore and previous transactions.
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:74
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
Definition: sign.cpp:186
bool error(const char *fmt, const Args &... args)
Definition: util.h:59
iterator begin()
Definition: prevector.h:301
unsigned int GetRejectCode() const
Definition: validation.h:87
void ScriptPubKeyToUniv(const CScript &scriptPubKey, UniValue &out, bool fIncludeHex)
Definition: core_write.cpp:153
A reference to a CScript: the Hash360 of its serialization (see script.h)
Definition: standard.h:22
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:209
CMutableTransaction ConstructTransaction(const UniValue &inputs_in, const UniValue &outputs_in, const UniValue &locktime, const UniValue &rbf)
Create a transaction from univalue parameters.
A mutable version of CTransaction.
Definition: transaction.h:360
void TxToUniv(const CTransaction &tx, const uint256 &hashBlock, UniValue &entry, bool include_hex=true, int serialize_flags=0)
Definition: core_write.cpp:179
UniValue signrawtransaction(const JSONRPCRequest &request)
UniValue JSONRPCError(int code, const std::string &message)
Definition: protocol.cpp:51
No valid connection manager instance found.
Definition: protocol.h:73
size_t size() const
Definition: univalue.h:69
An encapsulated private key.
Definition: key.h:27
CScript final_script_sig
Definition: sign.h:225
const SigningProvider & DUMMY_SIGNING_PROVIDER
Definition: sign.cpp:495
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:264
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:183
Information about a peer.
Definition: net.h:626
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
CKey DecodeSecret(const std::string &str)
Definition: key_io.cpp:133
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:201
void Merge(const PartiallySignedTransaction &psbt)
Definition: sign.cpp:521
full block available in blk*.dat
Definition: chain.h:154
bool SignPSBTInput(const SigningProvider &provider, const CMutableTransaction &tx, PSBTInput &input, int index, int sighash)
Signs a PSBTInput, verifying that all provided data matches what is being signed. ...
Definition: sign.cpp:242
CChain & chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:219
CScript witness_script
Definition: sign.h:224
uint160 Hash360(const T1 pbegin, const T1 pend)
Compute the 160-bit hash an object.
Definition: hash.h:142
COutPoint prevout
Definition: transaction.h:64
void clear()
Definition: script.h:554
UniValue createpsbt(const JSONRPCRequest &request)
CCoinsView that brings transactions from a mempool into view.
Definition: txmempool.h:715
CScript GetScriptForWitness(const CScript &redeemscript)
Generate a pay-to-witness script for the given redeem script.
Definition: standard.cpp:312
Basic key store, that keeps keys in an address->secret map.
Definition: keystore.h:42
std::map< std::vector< unsigned char >, std::vector< unsigned char > > unknown
Definition: sign.h:562
Wrapper for UniValue::VType, which includes typeAny: Used to denote don&#39;t care type.
Definition: server.h:32
unsigned int nTx
Number of transactions in this block.
Definition: chain.h:199
Error parsing or validating structure in raw format.
Definition: protocol.h:54
std::string EncodeBase64(const unsigned char *pch, size_t len)
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:93
uint256 hash
Definition: transaction.h:21
bool IsCompressed() const
Check whether this is a compressed public key.
Definition: pubkey.h:180
CBlockIndex * LookupBlockIndex(const uint256 &hash)
Definition: validation.h:431