Update CMakeLists.txt - play with openssl
[novacoin.git] / src / rpcrawtransaction.cpp
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #include "base58.h"
7 #include "bitcoinrpc.h"
8 #include "txdb-leveldb.h"
9 #include "init.h"
10 #include "main.h"
11 #include "net.h"
12 #include "wallet.h"
13
14 using namespace json_spirit;
15
16 void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out, bool fIncludeHex)
17 {
18     txnouttype type;
19     std::vector<CTxDestination> addresses;
20     int nRequired;
21
22     out.push_back(Pair("asm", scriptPubKey.ToString()));
23
24     if (fIncludeHex)
25         out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
26
27     if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired))
28     {
29         out.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD)));
30         return;
31     }
32
33     if (type != TX_NULL_DATA)
34     {
35         out.push_back(Pair("reqSigs", nRequired));
36         out.push_back(Pair("type", GetTxnOutputType(type)));
37
38         if (type == TX_PUBKEY_DROP)
39         {
40             std::vector<valtype> vSolutions;
41             Solver(scriptPubKey, type, vSolutions);
42             out.push_back(Pair("keyVariant", HexStr(vSolutions[0])));
43             out.push_back(Pair("R", HexStr(vSolutions[1])));
44
45             CMalleableKeyView view;
46             if (pwalletMain->CheckOwnership(CPubKey(vSolutions[0]), CPubKey(vSolutions[1]), view))
47                 out.push_back(Pair("pubkeyPair", CBitcoinAddress(view.GetMalleablePubKey()).ToString()));
48         }
49         else
50         {
51             Array a;
52             for (const CTxDestination& addr : addresses)
53                 a.push_back(CBitcoinAddress(addr).ToString());
54             out.push_back(Pair("addresses", a));
55         }
56     }
57     else
58     {
59         out.push_back(Pair("type", GetTxnOutputType(type)));
60     }
61 }
62
63 void TxToJSON(const CTransaction& tx, const uint256& hashBlock, Object& entry)
64 {
65     entry.push_back(Pair("txid", tx.GetHash().GetHex()));
66     entry.push_back(Pair("version", tx.nVersion));
67     entry.push_back(Pair("time", (int64_t)tx.nTime));
68     entry.push_back(Pair("locktime", (int64_t)tx.nLockTime));
69     Array vin;
70     for (const CTxIn& txin : tx.vin)
71     {
72         Object in;
73         if (tx.IsCoinBase())
74             in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
75         else
76         {
77             in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
78             in.push_back(Pair("vout", (int64_t)txin.prevout.n));
79             Object o;
80             o.push_back(Pair("asm", txin.scriptSig.ToString()));
81             o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
82             in.push_back(Pair("scriptSig", o));
83         }
84         in.push_back(Pair("sequence", (int64_t)txin.nSequence));
85         vin.push_back(in);
86     }
87     entry.push_back(Pair("vin", vin));
88     Array vout;
89     for (unsigned int i = 0; i < tx.vout.size(); i++)
90     {
91         const CTxOut& txout = tx.vout[i];
92         Object out;
93         out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
94         out.push_back(Pair("n", (int64_t)i));
95         Object o;
96         ScriptPubKeyToJSON(txout.scriptPubKey, o, true);
97         out.push_back(Pair("scriptPubKey", o));
98         vout.push_back(out);
99     }
100     entry.push_back(Pair("vout", vout));
101
102     if (hashBlock != 0)
103     {
104         entry.push_back(Pair("blockhash", hashBlock.GetHex()));
105         std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
106         if (mi != mapBlockIndex.end() && (*mi).second)
107         {
108             CBlockIndex* pindex = (*mi).second;
109             if (pindex->IsInMainChain())
110             {
111                 entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
112                 entry.push_back(Pair("time", (int64_t)pindex->nTime));
113                 entry.push_back(Pair("blocktime", (int64_t)pindex->nTime));
114             }
115             else
116                 entry.push_back(Pair("confirmations", 0));
117         }
118     }
119 }
120
121 Value getrawtransaction(const Array& params, bool fHelp)
122 {
123     if (fHelp || params.size() < 1 || params.size() > 2)
124         throw std::runtime_error(
125             "getrawtransaction <txid> [verbose=0]\n"
126             "If verbose=0, returns a string that is\n"
127             "serialized, hex-encoded data for <txid>.\n"
128             "If verbose is non-zero, returns an Object\n"
129             "with information about <txid>.");
130
131     uint256 hash;
132     hash.SetHex(params[0].get_str());
133
134     bool fVerbose = false;
135     if (params.size() > 1)
136         fVerbose = (params[1].get_int() != 0);
137
138     CTransaction tx;
139     uint256 hashBlock = 0;
140     if (!GetTransaction(hash, tx, hashBlock))
141         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
142
143     CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
144     ssTx << tx;
145     std::string strHex = HexStr(ssTx.begin(), ssTx.end());
146
147     if (!fVerbose)
148         return strHex;
149
150     Object result;
151     result.push_back(Pair("hex", strHex));
152     TxToJSON(tx, hashBlock, result);
153     return result;
154 }
155
156 Value listunspent(const Array& params, bool fHelp)
157 {
158     if (fHelp || params.size() > 3)
159         throw std::runtime_error(
160             "listunspent [minconf=1] [maxconf=9999999]  [\"address\",...]\n"
161             "Returns array of unspent transaction outputs\n"
162             "with between minconf and maxconf (inclusive) confirmations.\n"
163             "Optionally filtered to only include txouts paid to specified addresses.\n"
164             "Results are an array of Objects, each of which has:\n"
165             "{txid, vout, scriptPubKey, amount, confirmations}");
166
167     RPCTypeCheck(params, {int_type, int_type, array_type});
168
169     int nMinDepth = 1;
170     if (params.size() > 0)
171         nMinDepth = params[0].get_int();
172
173     int nMaxDepth = 9999999;
174     if (params.size() > 1)
175         nMaxDepth = params[1].get_int();
176
177     std::set<CBitcoinAddress> setAddress;
178     if (params.size() > 2)
179     {
180         Array inputs = params[2].get_array();
181         for (Value& input : inputs)
182         {
183             CBitcoinAddress address(input.get_str());
184             if (!address.IsValid())
185                 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid NovaCoin address: ")+input.get_str());
186             if (setAddress.count(address))
187                 throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+input.get_str());
188            setAddress.insert(address);
189         }
190     }
191
192     Array results;
193     std::vector<COutput> vecOutputs;
194     pwalletMain->AvailableCoins(vecOutputs, false);
195     for (const COutput& out : vecOutputs)
196     {
197         if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
198             continue;
199
200         if(setAddress.size())
201         {
202             CTxDestination address;
203             if(!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
204                 continue;
205
206             if (!setAddress.count(address))
207                 continue;
208         }
209
210         int64_t nValue = out.tx->vout[out.i].nValue;
211         const CScript& pk = out.tx->vout[out.i].scriptPubKey;
212         Object entry;
213         entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
214         entry.push_back(Pair("vout", out.i));
215         CTxDestination address;
216         if (ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
217         {
218             entry.push_back(Pair("address", CBitcoinAddress(address).ToString()));
219             if (pwalletMain->mapAddressBook.count(address))
220                 entry.push_back(Pair("account", pwalletMain->mapAddressBook[address]));
221         }
222         entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
223         if (pk.IsPayToScriptHash())
224         {
225             CTxDestination address;
226             if (ExtractDestination(pk, address))
227             {
228                 const CScriptID& hash = std::get<CScriptID>(address);
229                 CScript redeemScript;
230                 if (pwalletMain->GetCScript(hash, redeemScript))
231                     entry.push_back(Pair("redeemScript", HexStr(redeemScript.begin(), redeemScript.end())));
232             }
233         }
234         entry.push_back(Pair("amount",ValueFromAmount(nValue)));
235         entry.push_back(Pair("confirmations",out.nDepth));
236         entry.push_back(Pair("spendable", out.fSpendable));
237         results.push_back(entry);
238     }
239
240     return results;
241 }
242
243 Value createrawtransaction(const Array& params, bool fHelp)
244 {
245     if (fHelp || params.size() > 3 || params.size() < 2)
246         throw std::runtime_error(
247             "createrawtransaction <'[{\"txid\":txid,\"vout\":n},...]'> <'{address:amount,...}'> [hex data]\n"
248             "Create a transaction spending given inputs\n"
249             "(array of objects containing transaction id and output number),\n"
250             "sending to given address(es),\n"
251             "optional data to add into data-carrying output.\n"
252             "Returns hex-encoded raw transaction.\n"
253             "Note that the transaction's inputs are not signed, and\n"
254             "it is not stored in the wallet or transmitted to the network.");
255
256     RPCTypeCheck(params, {array_type, obj_type});
257
258     Array inputs = params[0].get_array();
259     Object sendTo = params[1].get_obj();
260
261     CTransaction rawTx;
262
263     for (Value& input : inputs)
264     {
265         const Object& o = input.get_obj();
266
267         const Value& txid_v = find_value(o, "txid");
268         if (txid_v.type() != str_type)
269             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
270         std::string txid = txid_v.get_str();
271         if (!IsHex(txid))
272             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
273
274         const Value& vout_v = find_value(o, "vout");
275         if (vout_v.type() != int_type)
276             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
277         int nOutput = vout_v.get_int();
278         if (nOutput < 0)
279             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
280
281         CTxIn in(COutPoint(uint256(txid), nOutput));
282         rawTx.vin.push_back(in);
283     }
284
285     std::set<CBitcoinAddress> setAddress;
286     for (const Pair& s : sendTo)
287     {
288         // Create output destination script
289         CScript scriptPubKey;
290         CBitcoinAddress address(s.name_);
291
292         if (address.IsValid())
293         {
294             scriptPubKey.SetAddress(address);
295
296             // Don't perform duplication checking for pubkey-pair addresses
297             if (!address.IsPair())
298             {
299                 if (setAddress.count(address))
300                     throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ")+s.name_);
301                 setAddress.insert(address);
302             }
303         }
304         else
305             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid output destination: ")+s.name_);
306
307         int64_t nAmount = AmountFromValue(s.value_);
308
309         CTxOut out(nAmount, scriptPubKey);
310         rawTx.vout.push_back(out);
311     }
312
313     if (params.size() == 3)
314     {
315         // Data carrying output
316         CScript scriptPubKey;
317         scriptPubKey << OP_RETURN << ParseHex(params[2].get_str());
318         CTxOut out(0, scriptPubKey);
319         rawTx.vout.push_back(out);
320     }
321
322     CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
323     ss << rawTx;
324     return HexStr(ss.begin(), ss.end());
325 }
326
327 Value decoderawtransaction(const Array& params, bool fHelp)
328 {
329     if (fHelp || params.size() != 1)
330         throw std::runtime_error(
331             "decoderawtransaction <hex string>\n"
332             "Return a JSON object representing the serialized, hex-encoded transaction.");
333
334     RPCTypeCheck(params, {str_type});
335
336     std::vector<unsigned char> txData(ParseHex(params[0].get_str()));
337     CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
338     CTransaction tx;
339     try {
340         ssData >> tx;
341     }
342     catch (const std::exception&) {
343         throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
344     }
345
346     Object result;
347     TxToJSON(tx, 0, result);
348
349     return result;
350 }
351
352 Value decodescript(const Array& params, bool fHelp)
353 {
354     if (fHelp || params.size() != 1)
355         throw std::runtime_error(
356             "decodescript <hex string>\n"
357             "Decode a hex-encoded script.");
358
359     RPCTypeCheck(params, {str_type});
360
361     Object r;
362     CScript script;
363     if (params[0].get_str().size() > 0){
364         std::vector<unsigned char> scriptData(ParseHexV(params[0], "argument"));
365         script = CScript(scriptData.begin(), scriptData.end());
366     } else {
367         // Empty scripts are valid
368     }
369     ScriptPubKeyToJSON(script, r, false);
370
371     r.push_back(Pair("p2sh", CBitcoinAddress(script.GetID()).ToString()));
372     return r;
373 }
374
375 Value signrawtransaction(const Array& params, bool fHelp)
376 {
377     if (fHelp || params.size() < 1 || params.size() > 4)
378         throw std::runtime_error(
379             "signrawtransaction <hex string> '[{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex,\"redeemScript\":hex},...]' '[<privatekey1>,...]' [sighashtype=\"ALL\"]\n"
380             "Sign inputs for raw transaction (serialized, hex-encoded).\n"
381             "Second optional argument (may be null) is an array of previous transaction outputs that\n"
382             "this transaction depends on but may not yet be in the blockchain.\n"
383             "Third optional argument (may be null) is an array of base58-encoded private\n"
384             "keys that, if given, will be the only keys used to sign the transaction.\n"
385             "Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n"
386             "ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n"
387             "Returns json object with keys:\n"
388             "  hex : raw transaction with signature(s) (hex-encoded string)\n"
389             "  complete : 1 if transaction has a complete set of signature (0 if not)"
390             + HelpRequiringPassphrase());
391
392     RPCTypeCheck(params, {str_type, array_type, array_type, str_type}, true);
393
394     std::vector<unsigned char> txData(ParseHex(params[0].get_str()));
395     CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
396     std::vector<CTransaction> txVariants;
397     while (!ssData.empty())
398     {
399         try {
400             CTransaction tx;
401             ssData >> tx;
402             txVariants.push_back(tx);
403         }
404         catch (const std::exception&) {
405             throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
406         }
407     }
408
409     if (txVariants.empty())
410         throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
411
412     // mergedTx will end up with all the signatures; it
413     // starts as a clone of the rawtx:
414     CTransaction mergedTx(txVariants[0]);
415     bool fComplete = true;
416
417     // Fetch previous transactions (inputs):
418     std::map<COutPoint, CScript> mapPrevOut;
419     for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
420     {
421         CTransaction tempTx;
422         MapPrevTx mapPrevTx;
423         CTxDB txdb("r");
424         std::map<uint256, CTxIndex> unused;
425         bool fInvalid;
426
427         // FetchInputs aborts on failure, so we go one at a time.
428         tempTx.vin.push_back(mergedTx.vin[i]);
429         tempTx.FetchInputs(txdb, unused, false, false, mapPrevTx, fInvalid);
430
431         // Copy results into mapPrevOut:
432         for (const CTxIn& txin : tempTx.vin)
433         {
434             const uint256& prevHash = txin.prevout.hash;
435             if (mapPrevTx.count(prevHash) && mapPrevTx[prevHash].second.vout.size()>txin.prevout.n)
436                 mapPrevOut[txin.prevout] = mapPrevTx[prevHash].second.vout[txin.prevout.n].scriptPubKey;
437         }
438     }
439
440     bool fGivenKeys = false;
441     CBasicKeyStore tempKeystore;
442     if (params.size() > 2 && params[2].type() != null_type)
443     {
444         fGivenKeys = true;
445         Array keys = params[2].get_array();
446         for (Value k : keys)
447         {
448             CBitcoinSecret vchSecret;
449             bool fGood = vchSecret.SetString(k.get_str());
450             if (!fGood)
451                 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
452             CKey key;
453             bool fCompressed;
454             CSecret secret = vchSecret.GetSecret(fCompressed);
455             key.SetSecret(secret, fCompressed);
456             tempKeystore.AddKey(key);
457         }
458     }
459     else
460         EnsureWalletIsUnlocked();
461
462     // Add previous txouts given in the RPC call:
463     if (params.size() > 1 && params[1].type() != null_type)
464     {
465         Array prevTxs = params[1].get_array();
466         for (Value& p : prevTxs)
467         {
468             if (p.type() != obj_type)
469                 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
470
471             Object prevOut = p.get_obj();
472
473             RPCTypeCheck(prevOut, {{"txid", str_type}, {"vout", int_type}, {"scriptPubKey", str_type}});
474
475             std::string txidHex = find_value(prevOut, "txid").get_str();
476             if (!IsHex(txidHex))
477                 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "txid must be hexadecimal");
478             uint256 txid;
479             txid.SetHex(txidHex);
480
481             int nOut = find_value(prevOut, "vout").get_int();
482             if (nOut < 0)
483                 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
484
485             std::string pkHex = find_value(prevOut, "scriptPubKey").get_str();
486             if (!IsHex(pkHex))
487                 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "scriptPubKey must be hexadecimal");
488             std::vector<unsigned char> pkData(ParseHex(pkHex));
489             CScript scriptPubKey(pkData.begin(), pkData.end());
490
491             COutPoint outpoint(txid, nOut);
492             if (mapPrevOut.count(outpoint))
493             {
494                 // Complain if scriptPubKey doesn't match
495                 if (mapPrevOut[outpoint] != scriptPubKey)
496                 {
497                     std::string err("Previous output scriptPubKey mismatch:\n");
498                     err = err + mapPrevOut[outpoint].ToString() + "\nvs:\n"+
499                         scriptPubKey.ToString();
500                     throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
501                 }
502             }
503             else
504                 mapPrevOut[outpoint] = scriptPubKey;
505
506             // if redeemScript given and not using the local wallet (private keys
507             // given), add redeemScript to the tempKeystore so it can be signed:
508             Value v = find_value(prevOut, "redeemScript");
509             if (fGivenKeys && scriptPubKey.IsPayToScriptHash())
510             {
511                 RPCTypeCheck(prevOut, {{"txid", str_type}, {"vout", int_type}, {"scriptPubKey", str_type}, {"redeemScript",str_type}});
512                 Value v = find_value(prevOut, "redeemScript");
513                 if (!(v == Value::null))
514                 {
515                     std::vector<unsigned char> rsData(ParseHexV(v, "redeemScript"));
516                     CScript redeemScript(rsData.begin(), rsData.end());
517                     tempKeystore.AddCScript(redeemScript);
518                 }
519             }
520         }
521     }
522
523     const CKeyStore& keystore = (fGivenKeys ? tempKeystore : *pwalletMain);
524
525     int nHashType = SIGHASH_ALL;
526     if (params.size() > 3 && params[3].type() != null_type)
527     {
528         static std::map<std::string, int> mapSigHashValues =
529         {
530             {"ALL", SIGHASH_ALL},
531             {"ALL|ANYONECANPAY", SIGHASH_ALL|SIGHASH_ANYONECANPAY},
532             {"NONE", SIGHASH_NONE},
533             {"NONE|ANYONECANPAY", SIGHASH_NONE|SIGHASH_ANYONECANPAY},
534             {"SINGLE", SIGHASH_SINGLE},
535             {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE|SIGHASH_ANYONECANPAY}
536         };
537         std::string strHashType = params[3].get_str();
538         if (mapSigHashValues.count(strHashType))
539             nHashType = mapSigHashValues[strHashType];
540         else
541             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
542     }
543
544     bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
545
546     // Sign what we can:
547     for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
548     {
549         CTxIn& txin = mergedTx.vin[i];
550         if (mapPrevOut.count(txin.prevout) == 0)
551         {
552             fComplete = false;
553             continue;
554         }
555         const CScript& prevPubKey = mapPrevOut[txin.prevout];
556
557         txin.scriptSig.clear();
558         // Only sign SIGHASH_SINGLE if there's a corresponding output:
559         if (!fHashSingle || (i < mergedTx.vout.size()))
560             SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
561
562         // ... and merge in other signatures:
563         for (const CTransaction& txv : txVariants)
564         {
565             txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
566         }
567         if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, STRICT_FLAGS, 0))
568             fComplete = false;
569     }
570
571     Object result;
572     CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
573     ssTx << mergedTx;
574     result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end())));
575     result.push_back(Pair("complete", fComplete));
576
577     return result;
578 }
579
580 Value sendrawtransaction(const Array& params, bool fHelp)
581 {
582     if (fHelp || params.size() < 1 || params.size() > 1)
583         throw std::runtime_error(
584             "sendrawtransaction <hex string>\n"
585             "Submits raw transaction (serialized, hex-encoded) to local node and network.");
586
587     RPCTypeCheck(params, {str_type});
588
589     // parse hex string from parameter
590     std::vector<unsigned char> txData(ParseHex(params[0].get_str()));
591     CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
592     CTransaction tx;
593
594     // deserialize binary data stream
595     try {
596         ssData >> tx;
597     }
598     catch (const std::exception&) {
599         throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
600     }
601     uint256 hashTx = tx.GetHash();
602
603     // See if the transaction is already in a block
604     // or in the memory pool:
605     CTransaction existingTx;
606     uint256 hashBlock = 0;
607     if (GetTransaction(hashTx, existingTx, hashBlock))
608     {
609         if (hashBlock != 0)
610             throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("transaction already in block ")+hashBlock.GetHex());
611         // Not in block, but already in the memory pool; will drop
612         // through to re-relay it.
613     }
614     else
615     {
616         // push to local node
617         CTxDB txdb("r");
618         if (!tx.AcceptToMemoryPool(txdb))
619             throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX rejected");
620
621         SyncWithWallets(tx, NULL, true);
622     }
623     RelayTransaction(tx, hashTx);
624
625     return hashTx.GetHex();
626 }
627
628 Value createmultisig(const Array& params, bool fHelp)
629 {
630     if (fHelp || params.size() < 2 || params.size() > 3)
631     {
632         std::string msg = "createmultisig <nrequired> <'[\"key\",\"key\"]'>\n"
633             "\nCreates a multi-signature address with n signature of m keys required.\n"
634             "It returns a json object with the address and redeemScript.";
635         throw std::runtime_error(msg);
636     }
637
638     int nRequired = params[0].get_int();
639     const Array& keys = params[1].get_array();
640
641     // Gather public keys
642     if (nRequired < 1)
643         throw std::runtime_error("a multisignature address must require at least one key to redeem");
644     if ((int)keys.size() < nRequired)
645         throw std::runtime_error(
646             strprintf("not enough keys supplied "
647                       "(got %" PRIszu " keys, but need at least %d to redeem)", keys.size(), nRequired));
648     if (keys.size() > 16)
649         throw std::runtime_error("Number of addresses involved in the multisignature address creation > 16\nReduce the number");
650     std::vector<CPubKey> pubkeys;
651     pubkeys.resize(keys.size());
652     for (unsigned int i = 0; i < keys.size(); i++)
653     {
654         const std::string& ks = keys[i].get_str();
655
656         // Case 1: Bitcoin address and we have full public key:
657         CBitcoinAddress address(ks);
658         if (address.IsValid())
659         {
660             CKeyID keyID;
661             if (!address.GetKeyID(keyID))
662                 throw std::runtime_error(
663                     strprintf("%s does not refer to a key",ks.c_str()));
664             CPubKey vchPubKey;
665             if (!pwalletMain->GetPubKey(keyID, vchPubKey))
666                 throw std::runtime_error(
667                     strprintf("no full public key for address %s",ks.c_str()));
668             if (!vchPubKey.IsFullyValid())
669                 throw std::runtime_error(" Invalid public key: "+ks);
670             pubkeys[i] = vchPubKey;
671         }
672
673         // Case 2: hex public key
674         else if (IsHex(ks))
675         {
676             CPubKey vchPubKey(ParseHex(ks));
677             if (!vchPubKey.IsFullyValid())
678                 throw std::runtime_error(" Invalid public key: "+ks);
679             pubkeys[i] = vchPubKey;
680         }
681         else
682         {
683             throw std::runtime_error(" Invalid public key: "+ks);
684         }
685     }
686
687     // Construct using pay-to-script-hash:
688     CScript inner;
689     inner.SetMultisig(nRequired, pubkeys);
690
691     if (inner.size() > MAX_SCRIPT_ELEMENT_SIZE)
692         throw std::runtime_error(
693             strprintf("redeemScript exceeds size limit: %" PRIszu " > %d", inner.size(), MAX_SCRIPT_ELEMENT_SIZE));
694
695     CScriptID innerID = inner.GetID();
696     CBitcoinAddress address(innerID);
697
698     Object result;
699     result.push_back(Pair("address", address.ToString()));
700     result.push_back(Pair("redeemScript", HexStr(inner.begin(), inner.end())));
701
702     return result;
703 }