1 // Copyright (c) 2009-2015 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #if defined(HAVE_CONFIG_H)
6 #include "config/bitcoin-config.h"
10 #include "clientversion.h"
12 #include "consensus/consensus.h"
15 #include "policy/policy.h"
16 #include "primitives/transaction.h"
17 #include "script/script.h"
18 #include "script/sign.h"
21 #include "utilmoneystr.h"
22 #include "utilstrencodings.h"
26 #include <boost/algorithm/string.hpp>
27 #include <boost/assign/list_of.hpp>
29 static bool fCreateBlank
;
30 static std::map
<std::string
,UniValue
> registers
;
31 static const int CONTINUE_EXECUTION
=-1;
34 // This function returns either one of EXIT_ codes when it's expected to stop the process or
35 // CONTINUE_EXECUTION when it's expected to continue further.
37 static int AppInitRawTx(int argc
, char* argv
[])
42 ParseParameters(argc
, argv
);
44 // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
46 SelectParams(ChainNameFromCommandLine());
47 } catch (const std::exception
& e
) {
48 fprintf(stderr
, "Error: %s\n", e
.what());
52 fCreateBlank
= GetBoolArg("-create", false);
54 if (argc
<2 || mapArgs
.count("-?") || mapArgs
.count("-h") || mapArgs
.count("-help"))
56 // First part of help message is specific to this utility
57 std::string strUsage
= strprintf(_("%s bitcoin-tx utility version"), _(PACKAGE_NAME
)) + " " + FormatFullVersion() + "\n\n" +
59 " bitcoin-tx [options] <hex-tx> [commands] " + _("Update hex-encoded bitcoin transaction") + "\n" +
60 " bitcoin-tx [options] -create [commands] " + _("Create hex-encoded bitcoin transaction") + "\n" +
63 fprintf(stdout
, "%s", strUsage
.c_str());
65 strUsage
= HelpMessageGroup(_("Options:"));
66 strUsage
+= HelpMessageOpt("-?", _("This help message"));
67 strUsage
+= HelpMessageOpt("-create", _("Create new, empty TX."));
68 strUsage
+= HelpMessageOpt("-json", _("Select JSON output"));
69 strUsage
+= HelpMessageOpt("-txid", _("Output only the hex-encoded transaction id of the resultant transaction."));
70 AppendParamsHelpMessages(strUsage
);
72 fprintf(stdout
, "%s", strUsage
.c_str());
74 strUsage
= HelpMessageGroup(_("Commands:"));
75 strUsage
+= HelpMessageOpt("delin=N", _("Delete input N from TX"));
76 strUsage
+= HelpMessageOpt("delout=N", _("Delete output N from TX"));
77 strUsage
+= HelpMessageOpt("in=TXID:VOUT(:SEQUENCE_NUMBER)", _("Add input to TX"));
78 strUsage
+= HelpMessageOpt("locktime=N", _("Set TX lock time to N"));
79 strUsage
+= HelpMessageOpt("nversion=N", _("Set TX version to N"));
80 strUsage
+= HelpMessageOpt("outaddr=VALUE:ADDRESS", _("Add address-based output to TX"));
81 strUsage
+= HelpMessageOpt("outdata=[VALUE:]DATA", _("Add data-based output to TX"));
82 strUsage
+= HelpMessageOpt("outscript=VALUE:SCRIPT", _("Add raw script output to TX"));
83 strUsage
+= HelpMessageOpt("sign=SIGHASH-FLAGS", _("Add zero or more signatures to transaction") + ". " +
84 _("This command requires JSON registers:") +
85 _("prevtxs=JSON object") + ", " +
86 _("privatekeys=JSON object") + ". " +
87 _("See signrawtransaction docs for format of sighash flags, JSON objects."));
88 fprintf(stdout
, "%s", strUsage
.c_str());
90 strUsage
= HelpMessageGroup(_("Register Commands:"));
91 strUsage
+= HelpMessageOpt("load=NAME:FILENAME", _("Load JSON file FILENAME into register NAME"));
92 strUsage
+= HelpMessageOpt("set=NAME:JSON-STRING", _("Set register NAME to given JSON-STRING"));
93 fprintf(stdout
, "%s", strUsage
.c_str());
96 fprintf(stderr
, "Error: too few parameters\n");
101 return CONTINUE_EXECUTION
;
104 static void RegisterSetJson(const std::string
& key
, const std::string
& rawJson
)
107 if (!val
.read(rawJson
)) {
108 std::string strErr
= "Cannot parse JSON for key " + key
;
109 throw std::runtime_error(strErr
);
112 registers
[key
] = val
;
115 static void RegisterSet(const std::string
& strInput
)
117 // separate NAME:VALUE in string
118 size_t pos
= strInput
.find(':');
119 if ((pos
== std::string::npos
) ||
121 (pos
== (strInput
.size() - 1)))
122 throw std::runtime_error("Register input requires NAME:VALUE");
124 std::string key
= strInput
.substr(0, pos
);
125 std::string valStr
= strInput
.substr(pos
+ 1, std::string::npos
);
127 RegisterSetJson(key
, valStr
);
130 static void RegisterLoad(const std::string
& strInput
)
132 // separate NAME:FILENAME in string
133 size_t pos
= strInput
.find(':');
134 if ((pos
== std::string::npos
) ||
136 (pos
== (strInput
.size() - 1)))
137 throw std::runtime_error("Register load requires NAME:FILENAME");
139 std::string key
= strInput
.substr(0, pos
);
140 std::string filename
= strInput
.substr(pos
+ 1, std::string::npos
);
142 FILE *f
= fopen(filename
.c_str(), "r");
144 std::string strErr
= "Cannot open file " + filename
;
145 throw std::runtime_error(strErr
);
148 // load file chunks into one big buffer
150 while ((!feof(f
)) && (!ferror(f
))) {
152 int bread
= fread(buf
, 1, sizeof(buf
), f
);
156 valStr
.insert(valStr
.size(), buf
, bread
);
159 int error
= ferror(f
);
163 std::string strErr
= "Error reading file " + filename
;
164 throw std::runtime_error(strErr
);
167 // evaluate as JSON buffer register
168 RegisterSetJson(key
, valStr
);
171 static void MutateTxVersion(CMutableTransaction
& tx
, const std::string
& cmdVal
)
173 int64_t newVersion
= atoi64(cmdVal
);
174 if (newVersion
< 1 || newVersion
> CTransaction::MAX_STANDARD_VERSION
)
175 throw std::runtime_error("Invalid TX version requested");
177 tx
.nVersion
= (int) newVersion
;
180 static void MutateTxLocktime(CMutableTransaction
& tx
, const std::string
& cmdVal
)
182 int64_t newLocktime
= atoi64(cmdVal
);
183 if (newLocktime
< 0LL || newLocktime
> 0xffffffffLL
)
184 throw std::runtime_error("Invalid TX locktime requested");
186 tx
.nLockTime
= (unsigned int) newLocktime
;
189 static void MutateTxAddInput(CMutableTransaction
& tx
, const std::string
& strInput
)
191 std::vector
<std::string
> vStrInputParts
;
192 boost::split(vStrInputParts
, strInput
, boost::is_any_of(":"));
194 // separate TXID:VOUT in string
195 if (vStrInputParts
.size()<2)
196 throw std::runtime_error("TX input missing separator");
198 // extract and validate TXID
199 std::string strTxid
= vStrInputParts
[0];
200 if ((strTxid
.size() != 64) || !IsHex(strTxid
))
201 throw std::runtime_error("invalid TX input txid");
202 uint256
txid(uint256S(strTxid
));
204 static const unsigned int minTxOutSz
= 9;
205 static const unsigned int maxVout
= MAX_BLOCK_BASE_SIZE
/ minTxOutSz
;
207 // extract and validate vout
208 std::string strVout
= vStrInputParts
[1];
209 int vout
= atoi(strVout
);
210 if ((vout
< 0) || (vout
> (int)maxVout
))
211 throw std::runtime_error("invalid TX input vout");
213 // extract the optional sequence number
214 uint32_t nSequenceIn
=std::numeric_limits
<unsigned int>::max();
215 if (vStrInputParts
.size() > 2)
216 nSequenceIn
= std::stoul(vStrInputParts
[2]);
218 // append to transaction input list
219 CTxIn
txin(txid
, vout
, CScript(), nSequenceIn
);
220 tx
.vin
.push_back(txin
);
223 static void MutateTxAddOutAddr(CMutableTransaction
& tx
, const std::string
& strInput
)
225 // separate VALUE:ADDRESS in string
226 size_t pos
= strInput
.find(':');
227 if ((pos
== std::string::npos
) ||
229 (pos
== (strInput
.size() - 1)))
230 throw std::runtime_error("TX output missing separator");
232 // extract and validate VALUE
233 std::string strValue
= strInput
.substr(0, pos
);
235 if (!ParseMoney(strValue
, value
))
236 throw std::runtime_error("invalid TX output value");
238 // extract and validate ADDRESS
239 std::string strAddr
= strInput
.substr(pos
+ 1, std::string::npos
);
240 CBitcoinAddress
addr(strAddr
);
242 throw std::runtime_error("invalid TX output address");
244 // build standard output script via GetScriptForDestination()
245 CScript scriptPubKey
= GetScriptForDestination(addr
.Get());
247 // construct TxOut, append to transaction output list
248 CTxOut
txout(value
, scriptPubKey
);
249 tx
.vout
.push_back(txout
);
252 static void MutateTxAddOutData(CMutableTransaction
& tx
, const std::string
& strInput
)
256 // separate [VALUE:]DATA in string
257 size_t pos
= strInput
.find(':');
260 throw std::runtime_error("TX output value not specified");
262 if (pos
!= std::string::npos
) {
263 // extract and validate VALUE
264 std::string strValue
= strInput
.substr(0, pos
);
265 if (!ParseMoney(strValue
, value
))
266 throw std::runtime_error("invalid TX output value");
269 // extract and validate DATA
270 std::string strData
= strInput
.substr(pos
+ 1, std::string::npos
);
273 throw std::runtime_error("invalid TX output data");
275 std::vector
<unsigned char> data
= ParseHex(strData
);
277 CTxOut
txout(value
, CScript() << OP_RETURN
<< data
);
278 tx
.vout
.push_back(txout
);
281 static void MutateTxAddOutScript(CMutableTransaction
& tx
, const std::string
& strInput
)
283 // separate VALUE:SCRIPT in string
284 size_t pos
= strInput
.find(':');
285 if ((pos
== std::string::npos
) ||
287 throw std::runtime_error("TX output missing separator");
289 // extract and validate VALUE
290 std::string strValue
= strInput
.substr(0, pos
);
292 if (!ParseMoney(strValue
, value
))
293 throw std::runtime_error("invalid TX output value");
295 // extract and validate script
296 std::string strScript
= strInput
.substr(pos
+ 1, std::string::npos
);
297 CScript scriptPubKey
= ParseScript(strScript
); // throws on err
299 // construct TxOut, append to transaction output list
300 CTxOut
txout(value
, scriptPubKey
);
301 tx
.vout
.push_back(txout
);
304 static void MutateTxDelInput(CMutableTransaction
& tx
, const std::string
& strInIdx
)
306 // parse requested deletion index
307 int inIdx
= atoi(strInIdx
);
308 if (inIdx
< 0 || inIdx
>= (int)tx
.vin
.size()) {
309 std::string strErr
= "Invalid TX input index '" + strInIdx
+ "'";
310 throw std::runtime_error(strErr
.c_str());
313 // delete input from transaction
314 tx
.vin
.erase(tx
.vin
.begin() + inIdx
);
317 static void MutateTxDelOutput(CMutableTransaction
& tx
, const std::string
& strOutIdx
)
319 // parse requested deletion index
320 int outIdx
= atoi(strOutIdx
);
321 if (outIdx
< 0 || outIdx
>= (int)tx
.vout
.size()) {
322 std::string strErr
= "Invalid TX output index '" + strOutIdx
+ "'";
323 throw std::runtime_error(strErr
.c_str());
326 // delete output from transaction
327 tx
.vout
.erase(tx
.vout
.begin() + outIdx
);
330 static const unsigned int N_SIGHASH_OPTS
= 6;
331 static const struct {
334 } sighashOptions
[N_SIGHASH_OPTS
] = {
335 {"ALL", SIGHASH_ALL
},
336 {"NONE", SIGHASH_NONE
},
337 {"SINGLE", SIGHASH_SINGLE
},
338 {"ALL|ANYONECANPAY", SIGHASH_ALL
|SIGHASH_ANYONECANPAY
},
339 {"NONE|ANYONECANPAY", SIGHASH_NONE
|SIGHASH_ANYONECANPAY
},
340 {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE
|SIGHASH_ANYONECANPAY
},
343 static bool findSighashFlags(int& flags
, const std::string
& flagStr
)
347 for (unsigned int i
= 0; i
< N_SIGHASH_OPTS
; i
++) {
348 if (flagStr
== sighashOptions
[i
].flagStr
) {
349 flags
= sighashOptions
[i
].flags
;
357 uint256
ParseHashUO(std::map
<std::string
,UniValue
>& o
, std::string strKey
)
359 if (!o
.count(strKey
))
361 return ParseHashUV(o
[strKey
], strKey
);
364 std::vector
<unsigned char> ParseHexUO(std::map
<std::string
,UniValue
>& o
, std::string strKey
)
366 if (!o
.count(strKey
)) {
367 std::vector
<unsigned char> emptyVec
;
370 return ParseHexUV(o
[strKey
], strKey
);
373 static CAmount
AmountFromValue(const UniValue
& value
)
375 if (!value
.isNum() && !value
.isStr())
376 throw std::runtime_error("Amount is not a number or string");
378 if (!ParseFixedPoint(value
.getValStr(), 8, &amount
))
379 throw std::runtime_error("Invalid amount");
380 if (!MoneyRange(amount
))
381 throw std::runtime_error("Amount out of range");
385 static void MutateTxSign(CMutableTransaction
& tx
, const std::string
& flagStr
)
387 int nHashType
= SIGHASH_ALL
;
389 if (flagStr
.size() > 0)
390 if (!findSighashFlags(nHashType
, flagStr
))
391 throw std::runtime_error("unknown sighash flag/sign option");
393 std::vector
<CTransaction
> txVariants
;
394 txVariants
.push_back(tx
);
396 // mergedTx will end up with all the signatures; it
397 // starts as a clone of the raw tx:
398 CMutableTransaction
mergedTx(txVariants
[0]);
399 bool fComplete
= true;
400 CCoinsView viewDummy
;
401 CCoinsViewCache
view(&viewDummy
);
403 if (!registers
.count("privatekeys"))
404 throw std::runtime_error("privatekeys register variable must be set.");
405 CBasicKeyStore tempKeystore
;
406 UniValue keysObj
= registers
["privatekeys"];
408 for (unsigned int kidx
= 0; kidx
< keysObj
.size(); kidx
++) {
409 if (!keysObj
[kidx
].isStr())
410 throw std::runtime_error("privatekey not a std::string");
411 CBitcoinSecret vchSecret
;
412 bool fGood
= vchSecret
.SetString(keysObj
[kidx
].getValStr());
414 throw std::runtime_error("privatekey not valid");
416 CKey key
= vchSecret
.GetKey();
417 tempKeystore
.AddKey(key
);
420 // Add previous txouts given in the RPC call:
421 if (!registers
.count("prevtxs"))
422 throw std::runtime_error("prevtxs register variable must be set.");
423 UniValue prevtxsObj
= registers
["prevtxs"];
425 for (unsigned int previdx
= 0; previdx
< prevtxsObj
.size(); previdx
++) {
426 UniValue prevOut
= prevtxsObj
[previdx
];
427 if (!prevOut
.isObject())
428 throw std::runtime_error("expected prevtxs internal object");
430 std::map
<std::string
,UniValue::VType
> types
= boost::assign::map_list_of("txid", UniValue::VSTR
)("vout",UniValue::VNUM
)("scriptPubKey",UniValue::VSTR
);
431 if (!prevOut
.checkObject(types
))
432 throw std::runtime_error("prevtxs internal object typecheck fail");
434 uint256 txid
= ParseHashUV(prevOut
["txid"], "txid");
436 int nOut
= atoi(prevOut
["vout"].getValStr());
438 throw std::runtime_error("vout must be positive");
440 std::vector
<unsigned char> pkData(ParseHexUV(prevOut
["scriptPubKey"], "scriptPubKey"));
441 CScript
scriptPubKey(pkData
.begin(), pkData
.end());
444 CCoinsModifier coins
= view
.ModifyCoins(txid
);
445 if (coins
->IsAvailable(nOut
) && coins
->vout
[nOut
].scriptPubKey
!= scriptPubKey
) {
446 std::string
err("Previous output scriptPubKey mismatch:\n");
447 err
= err
+ ScriptToAsmStr(coins
->vout
[nOut
].scriptPubKey
) + "\nvs:\n"+
448 ScriptToAsmStr(scriptPubKey
);
449 throw std::runtime_error(err
);
451 if ((unsigned int)nOut
>= coins
->vout
.size())
452 coins
->vout
.resize(nOut
+1);
453 coins
->vout
[nOut
].scriptPubKey
= scriptPubKey
;
454 coins
->vout
[nOut
].nValue
= 0;
455 if (prevOut
.exists("amount")) {
456 coins
->vout
[nOut
].nValue
= AmountFromValue(prevOut
["amount"]);
460 // if redeemScript given and private keys given,
461 // add redeemScript to the tempKeystore so it can be signed:
462 if ((scriptPubKey
.IsPayToScriptHash() || scriptPubKey
.IsPayToWitnessScriptHash()) &&
463 prevOut
.exists("redeemScript")) {
464 UniValue v
= prevOut
["redeemScript"];
465 std::vector
<unsigned char> rsData(ParseHexUV(v
, "redeemScript"));
466 CScript
redeemScript(rsData
.begin(), rsData
.end());
467 tempKeystore
.AddCScript(redeemScript
);
472 const CKeyStore
& keystore
= tempKeystore
;
474 bool fHashSingle
= ((nHashType
& ~SIGHASH_ANYONECANPAY
) == SIGHASH_SINGLE
);
477 for (unsigned int i
= 0; i
< mergedTx
.vin
.size(); i
++) {
478 CTxIn
& txin
= mergedTx
.vin
[i
];
479 const CCoins
* coins
= view
.AccessCoins(txin
.prevout
.hash
);
480 if (!coins
|| !coins
->IsAvailable(txin
.prevout
.n
)) {
484 const CScript
& prevPubKey
= coins
->vout
[txin
.prevout
.n
].scriptPubKey
;
485 const CAmount
& amount
= coins
->vout
[txin
.prevout
.n
].nValue
;
487 SignatureData sigdata
;
488 // Only sign SIGHASH_SINGLE if there's a corresponding output:
489 if (!fHashSingle
|| (i
< mergedTx
.vout
.size()))
490 ProduceSignature(MutableTransactionSignatureCreator(&keystore
, &mergedTx
, i
, amount
, nHashType
), prevPubKey
, sigdata
);
492 // ... and merge in other signatures:
493 BOOST_FOREACH(const CTransaction
& txv
, txVariants
)
494 sigdata
= CombineSignatures(prevPubKey
, MutableTransactionSignatureChecker(&mergedTx
, i
, amount
), sigdata
, DataFromTransaction(txv
, i
));
495 UpdateTransaction(mergedTx
, i
, sigdata
);
497 if (!VerifyScript(txin
.scriptSig
, prevPubKey
, mergedTx
.wit
.vtxinwit
.size() > i
? &mergedTx
.wit
.vtxinwit
[i
].scriptWitness
: NULL
, STANDARD_SCRIPT_VERIFY_FLAGS
, MutableTransactionSignatureChecker(&mergedTx
, i
, amount
)))
502 // do nothing... for now
503 // perhaps store this for later optional JSON output
511 ECCVerifyHandle globalVerifyHandle
;
522 static void MutateTx(CMutableTransaction
& tx
, const std::string
& command
,
523 const std::string
& commandVal
)
525 std::unique_ptr
<Secp256k1Init
> ecc
;
527 if (command
== "nversion")
528 MutateTxVersion(tx
, commandVal
);
529 else if (command
== "locktime")
530 MutateTxLocktime(tx
, commandVal
);
532 else if (command
== "delin")
533 MutateTxDelInput(tx
, commandVal
);
534 else if (command
== "in")
535 MutateTxAddInput(tx
, commandVal
);
537 else if (command
== "delout")
538 MutateTxDelOutput(tx
, commandVal
);
539 else if (command
== "outaddr")
540 MutateTxAddOutAddr(tx
, commandVal
);
541 else if (command
== "outdata")
542 MutateTxAddOutData(tx
, commandVal
);
543 else if (command
== "outscript")
544 MutateTxAddOutScript(tx
, commandVal
);
546 else if (command
== "sign") {
547 if (!ecc
) { ecc
.reset(new Secp256k1Init()); }
548 MutateTxSign(tx
, commandVal
);
551 else if (command
== "load")
552 RegisterLoad(commandVal
);
554 else if (command
== "set")
555 RegisterSet(commandVal
);
558 throw std::runtime_error("unknown command");
561 static void OutputTxJSON(const CTransaction
& tx
)
563 UniValue
entry(UniValue::VOBJ
);
564 TxToUniv(tx
, uint256(), entry
);
566 std::string jsonOutput
= entry
.write(4);
567 fprintf(stdout
, "%s\n", jsonOutput
.c_str());
570 static void OutputTxHash(const CTransaction
& tx
)
572 std::string strHexHash
= tx
.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
574 fprintf(stdout
, "%s\n", strHexHash
.c_str());
577 static void OutputTxHex(const CTransaction
& tx
)
579 std::string strHex
= EncodeHexTx(tx
);
581 fprintf(stdout
, "%s\n", strHex
.c_str());
584 static void OutputTx(const CTransaction
& tx
)
586 if (GetBoolArg("-json", false))
588 else if (GetBoolArg("-txid", false))
594 static std::string
readStdin()
599 while (!feof(stdin
)) {
600 size_t bread
= fread(buf
, 1, sizeof(buf
), stdin
);
601 ret
.append(buf
, bread
);
602 if (bread
< sizeof(buf
))
607 throw std::runtime_error("error reading stdin");
609 boost::algorithm::trim_right(ret
);
614 static int CommandLineRawTx(int argc
, char* argv
[])
616 std::string strPrint
;
619 // Skip switches; Permit common stdin convention "-"
620 while (argc
> 1 && IsSwitchChar(argv
[1][0]) &&
626 CTransaction txDecodeTmp
;
630 // require at least one param
632 throw std::runtime_error("too few parameters");
634 // param: hex-encoded bitcoin transaction
635 std::string
strHexTx(argv
[1]);
636 if (strHexTx
== "-") // "-" implies standard input
637 strHexTx
= readStdin();
639 if (!DecodeHexTx(txDecodeTmp
, strHexTx
, true))
640 throw std::runtime_error("invalid transaction encoding");
646 CMutableTransaction
tx(txDecodeTmp
);
648 for (int i
= startArg
; i
< argc
; i
++) {
649 std::string arg
= argv
[i
];
650 std::string key
, value
;
651 size_t eqpos
= arg
.find('=');
652 if (eqpos
== std::string::npos
)
655 key
= arg
.substr(0, eqpos
);
656 value
= arg
.substr(eqpos
+ 1);
659 MutateTx(tx
, key
, value
);
665 catch (const boost::thread_interrupted
&) {
668 catch (const std::exception
& e
) {
669 strPrint
= std::string("error: ") + e
.what();
673 PrintExceptionContinue(NULL
, "CommandLineRawTx()");
677 if (strPrint
!= "") {
678 fprintf((nRet
== 0 ? stdout
: stderr
), "%s\n", strPrint
.c_str());
683 int main(int argc
, char* argv
[])
688 int ret
= AppInitRawTx(argc
, argv
);
689 if (ret
!= CONTINUE_EXECUTION
)
692 catch (const std::exception
& e
) {
693 PrintExceptionContinue(&e
, "AppInitRawTx()");
696 PrintExceptionContinue(NULL
, "AppInitRawTx()");
700 int ret
= EXIT_FAILURE
;
702 ret
= CommandLineRawTx(argc
, argv
);
704 catch (const std::exception
& e
) {
705 PrintExceptionContinue(&e
, "CommandLineRawTx()");
707 PrintExceptionContinue(NULL
, "CommandLineRawTx()");