Anoncoin  0.9.4
P2P Digital Currency
rpcrawtransaction.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin developers
3 // Copyright (c) 2013-2014 The Anoncoin Core developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 
7 // Many builder specific things set in the config file, ENABLE_WALLET is a good example. Don't forget to include it this way in your source files.
8 #if defined(HAVE_CONFIG_H)
10 #endif
11 
12 #include "base58.h"
13 #include "core.h"
14 #include "init.h"
15 #include "keystore.h"
16 #include "main.h"
17 #include "net.h"
18 #include "rpcserver.h"
19 #include "uint256.h"
20 #ifdef ENABLE_WALLET
21 #include "wallet.h"
22 #endif
23 
24 #include <stdint.h>
25 
26 #include <boost/assign/list_of.hpp>
27 #include "json/json_spirit_utils.h"
28 #include "json/json_spirit_value.h"
29 
30 using namespace std;
31 using namespace boost;
32 using namespace boost::assign;
33 using namespace json_spirit;
34 
35 void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex)
36 {
37  txnouttype type;
38  vector<CTxDestination> addresses;
39  int nRequired;
40 
41  out.push_back(Pair("asm", scriptPubKey.ToString()));
42  if (fIncludeHex)
43  out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
44 
45  if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired))
46  {
47  out.push_back(Pair("type", GetTxnOutputType(type)));
48  return;
49  }
50 
51  out.push_back(Pair("reqSigs", nRequired));
52  out.push_back(Pair("type", GetTxnOutputType(type)));
53 
54  Array a;
55  BOOST_FOREACH(const CTxDestination& addr, addresses)
56  a.push_back(CAnoncoinAddress(addr).ToString());
57  out.push_back(Pair("addresses", a));
58 }
59 
60 void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
61 {
62  entry.push_back(Pair("txid", tx.GetHash().GetHex()));
63  entry.push_back(Pair("version", tx.nVersion));
64  entry.push_back(Pair("locktime", (int64_t)tx.nLockTime));
65  Array vin;
66  BOOST_FOREACH(const CTxIn& txin, tx.vin)
67  {
68  Object in;
69  if (tx.IsCoinBase())
70  in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
71  else
72  {
73  in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
74  in.push_back(Pair("vout", (int64_t)txin.prevout.n));
75  Object o;
76  o.push_back(Pair("asm", txin.scriptSig.ToString()));
77  o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
78  in.push_back(Pair("scriptSig", o));
79  }
80  in.push_back(Pair("sequence", (int64_t)txin.nSequence));
81  vin.push_back(in);
82  }
83  entry.push_back(Pair("vin", vin));
84  Array vout;
85  for (unsigned int i = 0; i < tx.vout.size(); i++)
86  {
87  const CTxOut& txout = tx.vout[i];
88  Object out;
89  out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
90  out.push_back(Pair("n", (int64_t)i));
91  Object o;
92  ScriptPubKeyToJSON(txout.scriptPubKey, o, true);
93  out.push_back(Pair("scriptPubKey", o));
94  vout.push_back(out);
95  }
96  entry.push_back(Pair("vout", vout));
97 
98  if (hashBlock != 0)
99  {
100  entry.push_back(Pair("blockhash", hashBlock.GetHex()));
101  map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
102  if (mi != mapBlockIndex.end() && (*mi).second)
103  {
104  CBlockIndex* pindex = (*mi).second;
105  if (chainActive.Contains(pindex))
106  {
107  entry.push_back(Pair("confirmations", 1 + chainActive.Height() - pindex->nHeight));
108  entry.push_back(Pair("time", (int64_t)pindex->nTime));
109  entry.push_back(Pair("blocktime", (int64_t)pindex->nTime));
110  }
111  else
112  entry.push_back(Pair("confirmations", 0));
113  }
114  }
115 }
116 
117 Value getrawtransaction(const Array& params, bool fHelp)
118 {
119  if (fHelp || params.size() < 1 || params.size() > 2)
120  throw runtime_error(
121  "getrawtransaction \"txid\" ( verbose )\n"
122  "\nReturn the raw transaction data.\n"
123  "\nIf verbose=0, returns a string that is serialized, hex-encoded data for 'txid'.\n"
124  "If verbose is non-zero, returns an Object with information about 'txid'.\n"
125 
126  "\nArguments:\n"
127  "1. \"txid\" (string, required) The transaction id\n"
128  "2. verbose (numeric, optional, default=0) If 0, return a string, other return a json object\n"
129 
130  "\nResult (if verbose is not set or set to 0):\n"
131  "\"data\" (string) The serialized, hex-encoded data for 'txid'\n"
132 
133  "\nResult (if verbose > 0):\n"
134  "{\n"
135  " \"hex\" : \"data\", (string) The serialized, hex-encoded data for 'txid'\n"
136  " \"txid\" : \"id\", (string) The transaction id (same as provided)\n"
137  " \"version\" : n, (numeric) The version\n"
138  " \"locktime\" : ttt, (numeric) The lock time\n"
139  " \"vin\" : [ (array of json objects)\n"
140  " {\n"
141  " \"txid\": \"id\", (string) The transaction id\n"
142  " \"vout\": n, (numeric) \n"
143  " \"scriptSig\": { (json object) The script\n"
144  " \"asm\": \"asm\", (string) asm\n"
145  " \"hex\": \"hex\" (string) hex\n"
146  " },\n"
147  " \"sequence\": n (numeric) The script sequence number\n"
148  " }\n"
149  " ,...\n"
150  " ],\n"
151  " \"vout\" : [ (array of json objects)\n"
152  " {\n"
153  " \"value\" : x.xxx, (numeric) The value in btc\n"
154  " \"n\" : n, (numeric) index\n"
155  " \"scriptPubKey\" : { (json object)\n"
156  " \"asm\" : \"asm\", (string) the asm\n"
157  " \"hex\" : \"hex\", (string) the hex\n"
158  " \"reqSigs\" : n, (numeric) The required sigs\n"
159  " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
160  " \"addresses\" : [ (json array of string)\n"
161  " \"anoncoinaddress\" (string) anoncoin address\n"
162  " ,...\n"
163  " ]\n"
164  " }\n"
165  " }\n"
166  " ,...\n"
167  " ],\n"
168  " \"blockhash\" : \"hash\", (string) the block hash\n"
169  " \"confirmations\" : n, (numeric) The confirmations\n"
170  " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT)\n"
171  " \"blocktime\" : ttt (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
172  "}\n"
173 
174  "\nExamples:\n"
175  + HelpExampleCli("getrawtransaction", "\"mytxid\"")
176  + HelpExampleCli("getrawtransaction", "\"mytxid\" 1")
177  + HelpExampleRpc("getrawtransaction", "\"mytxid\", 1")
178  );
179 
180  uint256 hash = ParseHashV(params[0], "parameter 1");
181 
182  bool fVerbose = false;
183  if (params.size() > 1)
184  fVerbose = (params[1].get_int() != 0);
185 
186  CTransaction tx;
187  uint256 hashBlock = 0;
188  if (!GetTransaction(hash, tx, hashBlock, true))
189  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
190 
191  CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
192  ssTx << tx;
193  string strHex = HexStr(ssTx.begin(), ssTx.end());
194 
195  if (!fVerbose)
196  return strHex;
197 
198  Object result;
199  result.push_back(Pair("hex", strHex));
200  TxToJSON(tx, hashBlock, result);
201  return result;
202 }
203 
204 #ifdef ENABLE_WALLET
205 Value listunspent(const Array& params, bool fHelp)
206 {
207  if (fHelp || params.size() > 3)
208  throw runtime_error(
209  "listunspent ( minconf maxconf [\"address\",...] )\n"
210  "\nReturns array of unspent transaction outputs\n"
211  "with between minconf and maxconf (inclusive) confirmations.\n"
212  "Optionally filter to only include txouts paid to specified addresses.\n"
213  "Results are an array of Objects, each of which has:\n"
214  "{txid, vout, scriptPubKey, amount, confirmations}\n"
215  "\nArguments:\n"
216  "1. minconf (numeric, optional, default=1) The minimum confirmationsi to filter\n"
217  "2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n"
218  "3. \"addresses\" (string) A json array of anoncoin addresses to filter\n"
219  " [\n"
220  " \"address\" (string) anoncoin address\n"
221  " ,...\n"
222  " ]\n"
223  "\nResult\n"
224  "[ (array of json object)\n"
225  " {\n"
226  " \"txid\" : \"txid\", (string) the transaction id \n"
227  " \"vout\" : n, (numeric) the vout value\n"
228  " \"address\" : \"address\", (string) the anoncoin address\n"
229  " \"account\" : \"account\", (string) The associated account, or \"\" for the default account\n"
230  " \"scriptPubKey\" : \"key\", (string) the script key\n"
231  " \"amount\" : x.xxx, (numeric) the transaction amount in btc\n"
232  " \"confirmations\" : n (numeric) The number of confirmations\n"
233  " }\n"
234  " ,...\n"
235  "]\n"
236 
237  "\nExamples\n"
238  + HelpExampleCli("listunspent", "")
239  + HelpExampleCli("listunspent", "6 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"")
240  + HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"")
241  );
242 
243  RPCTypeCheck(params, list_of(int_type)(int_type)(array_type));
244 
245  int nMinDepth = 1;
246  if (params.size() > 0)
247  nMinDepth = params[0].get_int();
248 
249  int nMaxDepth = 9999999;
250  if (params.size() > 1)
251  nMaxDepth = params[1].get_int();
252 
253  set<CAnoncoinAddress> setAddress;
254  if (params.size() > 2)
255  {
256  Array inputs = params[2].get_array();
257  BOOST_FOREACH(Value& input, inputs)
258  {
259  CAnoncoinAddress address(input.get_str());
260  if (!address.IsValid())
261  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Anoncoin address: ")+input.get_str());
262  if (setAddress.count(address))
263  throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str());
264  setAddress.insert(address);
265  }
266  }
267 
268  Array results;
269  vector<COutput> vecOutputs;
270  assert(pwalletMain != NULL);
271  pwalletMain->AvailableCoins(vecOutputs, false);
272  BOOST_FOREACH(const COutput& out, vecOutputs)
273  {
274  if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
275  continue;
276 
277  if (setAddress.size())
278  {
279  CTxDestination address;
280  if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
281  continue;
282 
283  if (!setAddress.count(address))
284  continue;
285  }
286 
287  int64_t nValue = out.tx->vout[out.i].nValue;
288  const CScript& pk = out.tx->vout[out.i].scriptPubKey;
289  Object entry;
290  entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
291  entry.push_back(Pair("vout", out.i));
292  CTxDestination address;
293  if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
294  {
295  entry.push_back(Pair("address", CAnoncoinAddress(address).ToString()));
296  if (pwalletMain->mapAddressBook.count(address))
297  entry.push_back(Pair("account", pwalletMain->mapAddressBook[address].name));
298  }
299  entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
300  if (pk.IsPayToScriptHash())
301  {
302  CTxDestination address;
303  if (ExtractDestination(pk, address))
304  {
305  const CScriptID& hash = boost::get<const CScriptID&>(address);
306  CScript redeemScript;
307  if (pwalletMain->GetCScript(hash, redeemScript))
308  entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end())));
309  }
310  }
311  entry.push_back(Pair("amount",ValueFromAmount(nValue)));
312  entry.push_back(Pair("confirmations",out.nDepth));
313  entry.push_back(Pair("spendable", out.fSpendable));
314  results.push_back(entry);
315  }
316 
317  return results;
318 }
319 #endif
320 
321 Value createrawtransaction(const Array& params, bool fHelp)
322 {
323  if (fHelp || params.size() != 2)
324  throw runtime_error(
325  "createrawtransaction [{\"txid\":\"id\",\"vout\":n},...] {\"address\":amount,...}\n"
326  "\nCreate a transaction spending the given inputs and sending to the given addresses.\n"
327  "Returns hex-encoded raw transaction.\n"
328  "Note that the transaction's inputs are not signed, and\n"
329  "it is not stored in the wallet or transmitted to the network.\n"
330 
331  "\nArguments:\n"
332  "1. \"transactions\" (string, required) A json array of json objects\n"
333  " [\n"
334  " {\n"
335  " \"txid\":\"id\", (string, required) The transaction id\n"
336  " \"vout\":n (numeric, required) The output number\n"
337  " }\n"
338  " ,...\n"
339  " ]\n"
340  "2. \"addresses\" (string, required) a json object with addresses as keys and amounts as values\n"
341  " {\n"
342  " \"address\": x.xxx (numeric, required) The key is the anoncoin address, the value is the anc amount\n"
343  " ,...\n"
344  " }\n"
345 
346  "\nResult:\n"
347  "\"transaction\" (string) hex string of the transaction\n"
348 
349  "\nExamples\n"
350  + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"{\\\"address\\\":0.01}\"")
351  + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"{\\\"address\\\":0.01}\"")
352  );
353 
354  RPCTypeCheck(params, list_of(array_type)(obj_type));
355 
356  Array inputs = params[0].get_array();
357  Object sendTo = params[1].get_obj();
358 
359  CTransaction rawTx;
360 
361  BOOST_FOREACH(const Value& input, inputs)
362  {
363  const Object& o = input.get_obj();
364 
365  uint256 txid = ParseHashO(o, "txid");
366 
367  const Value& vout_v = find_value(o, "vout");
368  if (vout_v.type() != int_type)
369  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
370  int nOutput = vout_v.get_int();
371  if (nOutput < 0)
372  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
373 
374  CTxIn in(COutPoint(txid, nOutput));
375  rawTx.vin.push_back(in);
376  }
377 
378  set<CAnoncoinAddress> setAddress;
379  BOOST_FOREACH(const Pair& s, sendTo)
380  {
381  CAnoncoinAddress address(s.name_);
382  if (!address.IsValid())
383  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid Anoncoin address: ")+s.name_);
384 
385  if (setAddress.count(address))
386  throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
387  setAddress.insert(address);
388 
389  CScript scriptPubKey;
390  scriptPubKey.SetDestination(address.Get());
391  int64_t nAmount = AmountFromValue(s.value_);
392 
393  CTxOut out(nAmount, scriptPubKey);
394  rawTx.vout.push_back(out);
395  }
396 
397  CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
398  ss << rawTx;
399  return HexStr(ss.begin(), ss.end());
400 }
401 
402 Value decoderawtransaction(const Array& params, bool fHelp)
403 {
404  if (fHelp || params.size() != 1)
405  throw runtime_error(
406  "decoderawtransaction \"hexstring\"\n"
407  "\nReturn a JSON object representing the serialized, hex-encoded transaction.\n"
408 
409  "\nArguments:\n"
410  "1. \"hex\" (string, required) The transaction hex string\n"
411 
412  "\nResult:\n"
413  "{\n"
414  " \"txid\" : \"id\", (string) The transaction id\n"
415  " \"version\" : n, (numeric) The version\n"
416  " \"locktime\" : ttt, (numeric) The lock time\n"
417  " \"vin\" : [ (array of json objects)\n"
418  " {\n"
419  " \"txid\": \"id\", (string) The transaction id\n"
420  " \"vout\": n, (numeric) The output number\n"
421  " \"scriptSig\": { (json object) The script\n"
422  " \"asm\": \"asm\", (string) asm\n"
423  " \"hex\": \"hex\" (string) hex\n"
424  " },\n"
425  " \"sequence\": n (numeric) The script sequence number\n"
426  " }\n"
427  " ,...\n"
428  " ],\n"
429  " \"vout\" : [ (array of json objects)\n"
430  " {\n"
431  " \"value\" : x.xxx, (numeric) The value in btc\n"
432  " \"n\" : n, (numeric) index\n"
433  " \"scriptPubKey\" : { (json object)\n"
434  " \"asm\" : \"asm\", (string) the asm\n"
435  " \"hex\" : \"hex\", (string) the hex\n"
436  " \"reqSigs\" : n, (numeric) The required sigs\n"
437  " \"type\" : \"pubkeyhash\", (string) The type, eg 'pubkeyhash'\n"
438  " \"addresses\" : [ (json array of string)\n"
439  " \"12tvKAXCxZjSmdNbao16dKXC8tRWfcF5oc\" (string) anoncoin address\n"
440  " ,...\n"
441  " ]\n"
442  " }\n"
443  " }\n"
444  " ,...\n"
445  " ],\n"
446  "}\n"
447 
448  "\nExamples:\n"
449  + HelpExampleCli("decoderawtransaction", "\"hexstring\"")
450  + HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
451  );
452 
453  vector<unsigned char> txData(ParseHexV(params[0], "argument"));
454  CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
455  CTransaction tx;
456  try {
457  ssData >> tx;
458  }
459  catch (std::exception &e) {
460  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
461  }
462 
463  Object result;
464  TxToJSON(tx, 0, result);
465 
466  return result;
467 }
468 
469 Value decodescript(const Array& params, bool fHelp)
470 {
471  if (fHelp || params.size() != 1)
472  throw runtime_error(
473  "decodescript \"hex\"\n"
474  "\nDecode a hex-encoded script.\n"
475  "\nArguments:\n"
476  "1. \"hex\" (string) the hex encoded script\n"
477  "\nResult:\n"
478  "{\n"
479  " \"asm\":\"asm\", (string) Script public key\n"
480  " \"hex\":\"hex\", (string) hex encoded public key\n"
481  " \"type\":\"type\", (string) The output type\n"
482  " \"reqSigs\": n, (numeric) The required signatures\n"
483  " \"addresses\": [ (json array of string)\n"
484  " \"address\" (string) anoncoin address\n"
485  " ,...\n"
486  " ],\n"
487  " \"p2sh\",\"address\" (string) script address\n"
488  "}\n"
489  "\nExamples:\n"
490  + HelpExampleCli("decodescript", "\"hexstring\"")
491  + HelpExampleRpc("decodescript", "\"hexstring\"")
492  );
493 
494  RPCTypeCheck(params, list_of(str_type));
495 
496  Object r;
497  CScript script;
498  if (params[0].get_str().size() > 0){
499  vector<unsigned char> scriptData(ParseHexV(params[0], "argument"));
500  script = CScript(scriptData.begin(), scriptData.end());
501  } else {
502  // Empty scripts are valid
503  }
504  ScriptPubKeyToJSON(script, r, false);
505 
506  r.push_back(Pair("p2sh", CAnoncoinAddress(script.GetID()).ToString()));
507  return r;
508 }
509 
510 Value signrawtransaction(const Array& params, bool fHelp)
511 {
512  if (fHelp || params.size() < 1 || params.size() > 4)
513  throw runtime_error(
514  "signrawtransaction \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] [\"privatekey1\",...] sighashtype )\n"
515  "\nSign inputs for raw transaction (serialized, hex-encoded).\n"
516  "The second optional argument (may be null) is an array of previous transaction outputs that\n"
517  "this transaction depends on but may not yet be in the block chain.\n"
518  "The third optional argument (may be null) is an array of base58-encoded private\n"
519  "keys that, if given, will be the only keys used to sign the transaction.\n"
520 #ifdef ENABLE_WALLET
521  + HelpRequiringPassphrase() + "\n"
522 #endif
523 
524  "\nArguments:\n"
525  "1. \"hexstring\" (string, required) The transaction hex string\n"
526  "2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
527  " [ (json array of json objects, or 'null' if none provided)\n"
528  " {\n"
529  " \"txid\":\"id\", (string, required) The transaction id\n"
530  " \"vout\":n, (numeric, required) The output number\n"
531  " \"scriptPubKey\": \"hex\", (string, required) script key\n"
532  " \"redeemScript\": \"hex\" (string, required for P2SH) redeem script\n"
533  " }\n"
534  " ,...\n"
535  " ]\n"
536  "3. \"privatekeys\" (string, optional) A json array of base58-encoded private keys for signing\n"
537  " [ (json array of strings, or 'null' if none provided)\n"
538  " \"privatekey\" (string) private key in base58-encoding\n"
539  " ,...\n"
540  " ]\n"
541  "4. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
542  " \"ALL\"\n"
543  " \"NONE\"\n"
544  " \"SINGLE\"\n"
545  " \"ALL|ANYONECANPAY\"\n"
546  " \"NONE|ANYONECANPAY\"\n"
547  " \"SINGLE|ANYONECANPAY\"\n"
548 
549  "\nResult:\n"
550  "{\n"
551  " \"hex\": \"value\", (string) The raw transaction with signature(s) (hex-encoded string)\n"
552  " \"complete\": n (numeric) if transaction has a complete set of signature (0 if not)\n"
553  "}\n"
554 
555  "\nExamples:\n"
556  + HelpExampleCli("signrawtransaction", "\"myhex\"")
557  + HelpExampleRpc("signrawtransaction", "\"myhex\"")
558  );
559 
560  RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true);
561 
562  vector<unsigned char> txData(ParseHexV(params[0], "argument 1"));
563  CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
564  vector<CTransaction> txVariants;
565  while (!ssData.empty())
566  {
567  try {
568  CTransaction tx;
569  ssData >> tx;
570  txVariants.push_back(tx);
571  }
572  catch (std::exception &e) {
573  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
574  }
575  }
576 
577  if (txVariants.empty())
578  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
579 
580  // mergedTx will end up with all the signatures; it
581  // starts as a clone of the rawtx:
582  CTransaction mergedTx(txVariants[0]);
583  bool fComplete = true;
584 
585  // Fetch previous transactions (inputs):
586  CCoinsView viewDummy;
587  CCoinsViewCache view(viewDummy);
588  {
589  LOCK(mempool.cs);
590  CCoinsViewCache &viewChain = *pcoinsTip;
591  CCoinsViewMemPool viewMempool(viewChain, mempool);
592  view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
593 
594  BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) {
595  const uint256& prevHash = txin.prevout.hash;
596  CCoins coins;
597  view.GetCoins(prevHash, coins); // this is certainly allowed to fail
598  }
599 
600  view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
601  }
602 
603  bool fGivenKeys = false;
604  CBasicKeyStore tempKeystore;
605  if (params.size() > 2 && params[2].type() != null_type)
606  {
607  fGivenKeys = true;
608  Array keys = params[2].get_array();
609  BOOST_FOREACH(Value k, keys)
610  {
611  CAnoncoinSecret vchSecret;
612  bool fGood = vchSecret.SetString(k.get_str());
613  if (!fGood)
614  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
615  CKey key = vchSecret.GetKey();
616  tempKeystore.AddKey(key);
617  }
618  }
619 #ifdef ENABLE_WALLET
620  else
622 #endif
623 
624  // Add previous txouts given in the RPC call:
625  if (params.size() > 1 && params[1].type() != null_type)
626  {
627  Array prevTxs = params[1].get_array();
628  BOOST_FOREACH(Value& p, prevTxs)
629  {
630  if (p.type() != obj_type)
631  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
632 
633  Object prevOut = p.get_obj();
634 
635  RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type));
636 
637  uint256 txid = ParseHashO(prevOut, "txid");
638 
639  int nOut = find_value(prevOut, "vout").get_int();
640  if (nOut < 0)
641  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
642 
643  vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
644  CScript scriptPubKey(pkData.begin(), pkData.end());
645 
646  CCoins coins;
647  if (view.GetCoins(txid, coins)) {
648  if (coins.IsAvailable(nOut) && coins.vout[nOut].scriptPubKey != scriptPubKey) {
649  string err("Previous output scriptPubKey mismatch:\n");
650  err = err + coins.vout[nOut].scriptPubKey.ToString() + "\nvs:\n"+
651  scriptPubKey.ToString();
653  }
654  // what todo if txid is known, but the actual output isn't?
655  }
656  if ((unsigned int)nOut >= coins.vout.size())
657  coins.vout.resize(nOut+1);
658  coins.vout[nOut].scriptPubKey = scriptPubKey;
659  coins.vout[nOut].nValue = 0; // we don't know the actual output value
660  view.SetCoins(txid, coins);
661 
662  // if redeemScript given and not using the local wallet (private keys
663  // given), add redeemScript to the tempKeystore so it can be signed:
664  if (fGivenKeys && scriptPubKey.IsPayToScriptHash())
665  {
666  RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)("redeemScript",str_type));
667  Value v = find_value(prevOut, "redeemScript");
668  if (!(v == Value::null))
669  {
670  vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
671  CScript redeemScript(rsData.begin(), rsData.end());
672  tempKeystore.AddCScript(redeemScript);
673  }
674  }
675  }
676  }
677 
678 #ifdef ENABLE_WALLET
679  const CKeyStore& keystore = ((fGivenKeys || !pwalletMain) ? tempKeystore : *pwalletMain);
680 #else
681  const CKeyStore& keystore = tempKeystore;
682 #endif
683 
684  int nHashType = SIGHASH_ALL;
685  if (params.size() > 3 && params[3].type() != null_type)
686  {
687  static map<string, int> mapSigHashValues =
688  boost::assign::map_list_of
689  (string("ALL"), int(SIGHASH_ALL))
690  (string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
691  (string("NONE"), int(SIGHASH_NONE))
692  (string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
693  (string("SINGLE"), int(SIGHASH_SINGLE))
694  (string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
695  ;
696  string strHashType = params[3].get_str();
697  if (mapSigHashValues.count(strHashType))
698  nHashType = mapSigHashValues[strHashType];
699  else
700  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
701  }
702 
703  bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
704 
705  // Sign what we can:
706  for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
707  {
708  CTxIn& txin = mergedTx.vin[i];
709  CCoins coins;
710  if (!view.GetCoins(txin.prevout.hash, coins) || !coins.IsAvailable(txin.prevout.n))
711  {
712  fComplete = false;
713  continue;
714  }
715  const CScript& prevPubKey = coins.vout[txin.prevout.n].scriptPubKey;
716 
717  txin.scriptSig.clear();
718  // Only sign SIGHASH_SINGLE if there's a corresponding output:
719  if (!fHashSingle || (i < mergedTx.vout.size()))
720  SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
721 
722  // ... and merge in other signatures:
723  BOOST_FOREACH(const CTransaction& txv, txVariants)
724  {
725  txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
726  }
727  if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, 0))
728  fComplete = false;
729  }
730 
731  Object result;
732  CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
733  ssTx << mergedTx;
734  result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end())));
735  result.push_back(Pair("complete", fComplete));
736 
737  return result;
738 }
739 
740 Value sendrawtransaction(const Array& params, bool fHelp)
741 {
742  if (fHelp || params.size() < 1 || params.size() > 2)
743  throw runtime_error(
744  "sendrawtransaction \"hexstring\" ( allowhighfees )\n"
745  "\nSubmits raw transaction (serialized, hex-encoded) to local node and network.\n"
746  "\nAlso see createrawtransaction and signrawtransaction calls.\n"
747  "\nArguments:\n"
748  "1. \"hexstring\" (string, required) The hex string of the raw transaction)\n"
749  "2. allowhighfees (boolean, optional, default=false) Allow high fees\n"
750  "\nResult:\n"
751  "\"hex\" (string) The transaction hash in hex\n"
752  "\nExamples:\n"
753  "\nCreate a transaction\n"
754  + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\" : \\\"mytxid\\\",\\\"vout\\\":0}]\" \"{\\\"myaddress\\\":0.01}\"") +
755  "Sign the transaction, and get back the hex\n"
756  + HelpExampleCli("signrawtransaction", "\"myhex\"") +
757  "\nSend the transaction (signed hex)\n"
758  + HelpExampleCli("sendrawtransaction", "\"signedhex\"") +
759  "\nAs a json rpc call\n"
760  + HelpExampleRpc("sendrawtransaction", "\"signedhex\"")
761  );
762 
763 
764  // parse hex string from parameter
765  vector<unsigned char> txData(ParseHexV(params[0], "parameter"));
766  CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
767  CTransaction tx;
768 
769  bool fOverrideFees = false;
770  if (params.size() > 1)
771  fOverrideFees = params[1].get_bool();
772 
773  // deserialize binary data stream
774  try {
775  ssData >> tx;
776  }
777  catch (std::exception &e) {
778  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
779  }
780  uint256 hashTx = tx.GetHash();
781 
782  CCoinsViewCache &view = *pcoinsTip;
783  CCoins existingCoins;
784  bool fHaveMempool = mempool.exists(hashTx);
785  bool fHaveChain = view.GetCoins(hashTx, existingCoins) && existingCoins.nHeight < 1000000000;
786  if (!fHaveMempool && !fHaveChain) {
787  // push to local node and sync with wallets
788  CValidationState state;
789  if (AcceptToMemoryPool(mempool, state, tx, false, NULL, !fOverrideFees))
790  SyncWithWallets(hashTx, tx, NULL);
791  else {
792  if(state.IsInvalid())
794  else
796  }
797  } else if (fHaveChain) {
798  throw JSONRPCError(RPC_TRANSACTION_ALREADY_IN_CHAIN, "transaction already in block chain");
799  }
800  RelayTransaction(tx, hashTx);
801 
802  return hashTx.GetHex();
803 }
int nVersion
Definition: core.h:185
int i
Definition: wallet.h:828
Value createrawtransaction(const Array &params, bool fHelp)
std::string HelpRequiringPassphrase()
Definition: rpcwallet.cpp:30
const_iterator begin() const
Definition: serialize.h:933
CScript scriptPubKey
Definition: core.h:125
Definition: init.h:14
CScript CombineSignatures(CScript scriptPubKey, const CTransaction &txTo, unsigned int nIn, const CScript &scriptSig1, const CScript &scriptSig2)
Definition: script.cpp:1803
void SetBackend(CCoinsView &viewIn)
Definition: coins.cpp:69
vector< unsigned char > ParseHexO(const Object &o, string strKey)
Definition: rpcserver.cpp:139
uint256 ParseHashO(const Object &o, string strKey)
Definition: rpcserver.cpp:126
std::vector< CTxOut > vout
Definition: coins.h:76
std::map< CTxDestination, CAddressBookData > mapAddressBook
Definition: wallet.h:174
#define strprintf
Definition: tinyformat.h:1011
bool IsPayToScriptHash() const
Definition: script.cpp:1866
std::string HelpExampleRpc(string methodname, string args)
Definition: rpcserver.cpp:903
Value sendrawtransaction(const Array &params, bool fHelp)
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CTransaction &txTo, unsigned int nIn, unsigned int flags, int nHashType)
Definition: script.cpp:1608
bool SignSignature(const CKeyStore &keystore, const CScript &fromPubKey, CTransaction &txTo, unsigned int nIn, int nHashType)
Definition: script.cpp:1650
int nHeight
Definition: coins.h:79
CTxDestination Get() const
Definition: base58.cpp:223
uint256 GetHash() const
Definition: core.cpp:76
const char * GetTxnOutputType(txnouttype t)
Definition: script.cpp:66
Double ended buffer combining vector and stream-like interfaces.
Definition: serialize.h:848
Object JSONRPCError(int code, const string &message)
pruned version of CTransaction: only retains metadata and unspent transaction outputs ...
Definition: coins.h:69
unsigned int n
Definition: core.h:28
void RPCTypeCheck(const Array &params, const list< Value_type > &typesExpected, bool fAllowNull)
Definition: rpcserver.cpp:49
bool fSpendable
Definition: wallet.h:830
CChain chainActive
The currently-connected chain of blocks.
Definition: main.cpp:43
Value decodescript(const Array &params, bool fHelp)
bool IsValid() const
Definition: base58.cpp:216
bool GetCoins(const uint256 &txid, CCoins &coins)
Definition: coins.cpp:75
std::string ToString() const
Definition: script.h:692
bool IsAvailable(unsigned int nPos) const
Definition: coins.h:229
void SetDestination(const CTxDestination &address)
Definition: script.cpp:1945
virtual bool AddCScript(const CScript &redeemScript)
Definition: keystore.cpp:35
json_spirit::Value listunspent(const json_spirit::Array &params, bool fHelp)
bool AcceptToMemoryPool(CTxMemPool &pool, CValidationState &state, const CTransaction &tx, bool fLimitFree, bool *pfMissingInputs, bool fRejectInsaneFee)
(try to) add transaction to memory pool
Definition: main.cpp:878
void ScriptPubKeyToJSON(const CScript &scriptPubKey, Object &out, bool fIncludeHex)
Value decoderawtransaction(const Array &params, bool fHelp)
int Height() const
Return the maximal height in the chain.
Definition: main.h:1055
unsigned int nTime
Definition: main.h:735
unsigned int nLockTime
Definition: core.h:188
Value ValueFromAmount(int64_t amount)
Definition: rpcserver.cpp:100
int nDepth
Definition: wallet.h:829
Abstract view on the open txout dataset.
Definition: coins.h:259
An input of a transaction.
Definition: core.h:72
void EnsureWalletIsUnlocked()
Definition: rpcwallet.cpp:37
#define LOCK(cs)
Definition: sync.h:157
A base58-encoded secret key.
Definition: base58.h:122
std::vector< CTxOut > vout
Definition: core.h:187
txnouttype
Definition: script.h:207
void TxToJSON(const CTransaction &tx, const uint256 hashBlock, Object &entry)
std::vector< CTxIn > vin
Definition: core.h:186
base58-encoded Anoncoin addresses.
Definition: base58.h:102
void RelayTransaction(const CTransaction &tx, const uint256 &hash)
Definition: net.cpp:2106
bool SetString(const char *pszSecret)
Definition: base58.cpp:268
An output of a transaction.
Definition: core.h:121
void AvailableCoins(std::vector< COutput > &vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl=NULL) const
Definition: wallet.cpp:1110
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: core.h:24
CCoinsViewCache * pcoinsTip
Global variable that points to the active CCoinsView (protected by cs_main)
Definition: main.cpp:436
virtual bool AddKey(const CKey &key)
Definition: keystore.cpp:24
std::string GetHex() const
Definition: uint256.h:298
CCriticalSection cs
Definition: txmempool.h:62
CTxMemPool mempool
Definition: main.cpp:40
bool IsInvalid() const
Definition: main.h:992
std::string GetRejectReason() const
Definition: main.h:1009
unsigned char GetRejectCode() const
Definition: main.h:1008
CScript scriptSig
Definition: core.h:76
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
A txout script template with a specific destination.
Definition: keystore.h:17
unsigned int nSequence
Definition: core.h:77
Capture information about block/transaction validation.
Definition: main.h:950
256-bit unsigned integer
Definition: uint256.h:532
void SyncWithWallets(const uint256 &hash, const CTransaction &tx, const CBlock *pblock)
Push an updated transaction to all registered wallets.
Definition: main.cpp:183
bool ExtractDestinations(const CScript &scriptPubKey, txnouttype &typeRet, vector< CTxDestination > &addressRet, int &nRequiredRet)
Definition: script.cpp:1539
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: main.h:698
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:413
vector< unsigned char > ParseHexV(const Value &v, string strName)
Definition: rpcserver.cpp:130
A virtual base class for key stores.
Definition: keystore.h:28
Value signrawtransaction(const Array &params, bool fHelp)
bool exists(uint256 hash)
Definition: txmempool.h:92
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Definition: script.cpp:1513
const CWalletTx * tx
Definition: wallet.h:827
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: main.h:1042
CScriptID GetID() const
Definition: script.h:720
bool GetTransaction(const uint256 &hash, CTransaction &txOut, uint256 &hashBlock, bool fAllowSlow)
Retrieve a transaction (from memory pool, or from disk, if possible)
Definition: main.cpp:1075
virtual bool GetCScript(const CScriptID &hash, CScript &redeemScriptOut) const
Definition: keystore.cpp:51
int64_t AmountFromValue(const Value &value)
Definition: rpcserver.cpp:89
Value getrawtransaction(const Array &params, bool fHelp)
bool IsCoinBase() const
Definition: core.h:228
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: key.h:35
bool SetCoins(const uint256 &txid, const CCoins &coins)
Definition: coins.cpp:105
uint256 ParseHashV(const Value &v, string strName)
Definition: rpcserver.cpp:115
std::string HelpExampleCli(string methodname, string args)
Definition: rpcserver.cpp:899
An encapsulated private key.
Definition: key.h:180
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: core.h:179
#define ENABLE_WALLET
int nHeight
Definition: main.h:708
CCoinsView that adds a memory cache for transactions to another CCoinsView.
Definition: coins.h:309
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
Definition: util.h:256
CKey GetKey()
Definition: base58.cpp:256
COutPoint prevout
Definition: core.h:75
CCoinsView that brings transactions from a memorypool into view.
Definition: txmempool.h:103
map< uint256, CBlockIndex * > mapBlockIndex
Definition: main.cpp:42
Basic key store, that keeps keys in an address->secret map.
Definition: keystore.h:63
CWallet * pwalletMain
bool empty() const
Definition: serialize.h:938
int64_t nValue
Definition: core.h:124
const_iterator end() const
Definition: serialize.h:935
uint256 hash
Definition: core.h:27