1 // Copyright (c) 2009-2016 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 || IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-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("outpubkey=VALUE:PUBKEY[:FLAGS]", _("Add pay-to-pubkey output to TX") + ". " +
82 _("Optionally add the \"W\" flag to produce a pay-to-witness-pubkey-hash output") + ". " +
83 _("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
84 strUsage
+= HelpMessageOpt("outdata=[VALUE:]DATA", _("Add data-based output to TX"));
85 strUsage
+= HelpMessageOpt("outscript=VALUE:SCRIPT[:FLAGS]", _("Add raw script output to TX") + ". " +
86 _("Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output") + ". " +
87 _("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
88 strUsage
+= HelpMessageOpt("outmultisig=VALUE:REQUIRED:PUBKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]", _("Add Pay To n-of-m Multi-sig output to TX. n = REQUIRED, m = PUBKEYS") + ". " +
89 _("Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output") + ". " +
90 _("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
91 strUsage
+= HelpMessageOpt("sign=SIGHASH-FLAGS", _("Add zero or more signatures to transaction") + ". " +
92 _("This command requires JSON registers:") +
93 _("prevtxs=JSON object") + ", " +
94 _("privatekeys=JSON object") + ". " +
95 _("See signrawtransaction docs for format of sighash flags, JSON objects."));
96 fprintf(stdout
, "%s", strUsage
.c_str());
98 strUsage
= HelpMessageGroup(_("Register Commands:"));
99 strUsage
+= HelpMessageOpt("load=NAME:FILENAME", _("Load JSON file FILENAME into register NAME"));
100 strUsage
+= HelpMessageOpt("set=NAME:JSON-STRING", _("Set register NAME to given JSON-STRING"));
101 fprintf(stdout
, "%s", strUsage
.c_str());
104 fprintf(stderr
, "Error: too few parameters\n");
109 return CONTINUE_EXECUTION
;
112 static void RegisterSetJson(const std::string
& key
, const std::string
& rawJson
)
115 if (!val
.read(rawJson
)) {
116 std::string strErr
= "Cannot parse JSON for key " + key
;
117 throw std::runtime_error(strErr
);
120 registers
[key
] = val
;
123 static void RegisterSet(const std::string
& strInput
)
125 // separate NAME:VALUE in string
126 size_t pos
= strInput
.find(':');
127 if ((pos
== std::string::npos
) ||
129 (pos
== (strInput
.size() - 1)))
130 throw std::runtime_error("Register input requires NAME:VALUE");
132 std::string key
= strInput
.substr(0, pos
);
133 std::string valStr
= strInput
.substr(pos
+ 1, std::string::npos
);
135 RegisterSetJson(key
, valStr
);
138 static void RegisterLoad(const std::string
& strInput
)
140 // separate NAME:FILENAME in string
141 size_t pos
= strInput
.find(':');
142 if ((pos
== std::string::npos
) ||
144 (pos
== (strInput
.size() - 1)))
145 throw std::runtime_error("Register load requires NAME:FILENAME");
147 std::string key
= strInput
.substr(0, pos
);
148 std::string filename
= strInput
.substr(pos
+ 1, std::string::npos
);
150 FILE *f
= fopen(filename
.c_str(), "r");
152 std::string strErr
= "Cannot open file " + filename
;
153 throw std::runtime_error(strErr
);
156 // load file chunks into one big buffer
158 while ((!feof(f
)) && (!ferror(f
))) {
160 int bread
= fread(buf
, 1, sizeof(buf
), f
);
164 valStr
.insert(valStr
.size(), buf
, bread
);
167 int error
= ferror(f
);
171 std::string strErr
= "Error reading file " + filename
;
172 throw std::runtime_error(strErr
);
175 // evaluate as JSON buffer register
176 RegisterSetJson(key
, valStr
);
179 static CAmount
ExtractAndValidateValue(const std::string
& strValue
)
182 if (!ParseMoney(strValue
, value
))
183 throw std::runtime_error("invalid TX output value");
187 static void MutateTxVersion(CMutableTransaction
& tx
, const std::string
& cmdVal
)
189 int64_t newVersion
= atoi64(cmdVal
);
190 if (newVersion
< 1 || newVersion
> CTransaction::MAX_STANDARD_VERSION
)
191 throw std::runtime_error("Invalid TX version requested");
193 tx
.nVersion
= (int) newVersion
;
196 static void MutateTxLocktime(CMutableTransaction
& tx
, const std::string
& cmdVal
)
198 int64_t newLocktime
= atoi64(cmdVal
);
199 if (newLocktime
< 0LL || newLocktime
> 0xffffffffLL
)
200 throw std::runtime_error("Invalid TX locktime requested");
202 tx
.nLockTime
= (unsigned int) newLocktime
;
205 static void MutateTxAddInput(CMutableTransaction
& tx
, const std::string
& strInput
)
207 std::vector
<std::string
> vStrInputParts
;
208 boost::split(vStrInputParts
, strInput
, boost::is_any_of(":"));
210 // separate TXID:VOUT in string
211 if (vStrInputParts
.size()<2)
212 throw std::runtime_error("TX input missing separator");
214 // extract and validate TXID
215 std::string strTxid
= vStrInputParts
[0];
216 if ((strTxid
.size() != 64) || !IsHex(strTxid
))
217 throw std::runtime_error("invalid TX input txid");
218 uint256
txid(uint256S(strTxid
));
220 static const unsigned int minTxOutSz
= 9;
221 static const unsigned int maxVout
= MAX_BLOCK_BASE_SIZE
/ minTxOutSz
;
223 // extract and validate vout
224 std::string strVout
= vStrInputParts
[1];
225 int vout
= atoi(strVout
);
226 if ((vout
< 0) || (vout
> (int)maxVout
))
227 throw std::runtime_error("invalid TX input vout");
229 // extract the optional sequence number
230 uint32_t nSequenceIn
=std::numeric_limits
<unsigned int>::max();
231 if (vStrInputParts
.size() > 2)
232 nSequenceIn
= std::stoul(vStrInputParts
[2]);
234 // append to transaction input list
235 CTxIn
txin(txid
, vout
, CScript(), nSequenceIn
);
236 tx
.vin
.push_back(txin
);
239 static void MutateTxAddOutAddr(CMutableTransaction
& tx
, const std::string
& strInput
)
241 // Separate into VALUE:ADDRESS
242 std::vector
<std::string
> vStrInputParts
;
243 boost::split(vStrInputParts
, strInput
, boost::is_any_of(":"));
245 // Extract and validate VALUE
246 CAmount value
= ExtractAndValidateValue(vStrInputParts
[0]);
248 // extract and validate ADDRESS
249 std::string strAddr
= vStrInputParts
[1];
250 CBitcoinAddress
addr(strAddr
);
252 throw std::runtime_error("invalid TX output address");
253 // build standard output script via GetScriptForDestination()
254 CScript scriptPubKey
= GetScriptForDestination(addr
.Get());
256 // construct TxOut, append to transaction output list
257 CTxOut
txout(value
, scriptPubKey
);
258 tx
.vout
.push_back(txout
);
261 static void MutateTxAddOutPubKey(CMutableTransaction
& tx
, const std::string
& strInput
)
263 // Separate into VALUE:PUBKEY[:FLAGS]
264 std::vector
<std::string
> vStrInputParts
;
265 boost::split(vStrInputParts
, strInput
, boost::is_any_of(":"));
267 // Extract and validate VALUE
268 CAmount value
= ExtractAndValidateValue(vStrInputParts
[0]);
270 // Extract and validate PUBKEY
271 CPubKey
pubkey(ParseHex(vStrInputParts
[1]));
272 if (!pubkey
.IsFullyValid())
273 throw std::runtime_error("invalid TX output pubkey");
274 CScript scriptPubKey
= GetScriptForRawPubKey(pubkey
);
275 CBitcoinAddress
addr(scriptPubKey
);
277 // Extract and validate FLAGS
278 bool bSegWit
= false;
279 bool bScriptHash
= false;
280 if (vStrInputParts
.size() == 3) {
281 std::string flags
= vStrInputParts
[2];
282 bSegWit
= (flags
.find("W") != std::string::npos
);
283 bScriptHash
= (flags
.find("S") != std::string::npos
);
287 // Call GetScriptForWitness() to build a P2WSH scriptPubKey
288 scriptPubKey
= GetScriptForWitness(scriptPubKey
);
291 // Get the address for the redeem script, then call
292 // GetScriptForDestination() to construct a P2SH scriptPubKey.
293 CBitcoinAddress
redeemScriptAddr(scriptPubKey
);
294 scriptPubKey
= GetScriptForDestination(redeemScriptAddr
.Get());
297 // construct TxOut, append to transaction output list
298 CTxOut
txout(value
, scriptPubKey
);
299 tx
.vout
.push_back(txout
);
302 static void MutateTxAddOutMultiSig(CMutableTransaction
& tx
, const std::string
& strInput
)
304 // Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]
305 std::vector
<std::string
> vStrInputParts
;
306 boost::split(vStrInputParts
, strInput
, boost::is_any_of(":"));
308 // Check that there are enough parameters
309 if (vStrInputParts
.size()<3)
310 throw std::runtime_error("Not enough multisig parameters");
312 // Extract and validate VALUE
313 CAmount value
= ExtractAndValidateValue(vStrInputParts
[0]);
316 uint32_t required
= stoul(vStrInputParts
[1]);
319 uint32_t numkeys
= stoul(vStrInputParts
[2]);
321 // Validate there are the correct number of pubkeys
322 if (vStrInputParts
.size() < numkeys
+ 3)
323 throw std::runtime_error("incorrect number of multisig pubkeys");
325 if (required
< 1 || required
> 20 || numkeys
< 1 || numkeys
> 20 || numkeys
< required
)
326 throw std::runtime_error("multisig parameter mismatch. Required " \
327 + std::to_string(required
) + " of " + std::to_string(numkeys
) + "signatures.");
329 // extract and validate PUBKEYs
330 std::vector
<CPubKey
> pubkeys
;
331 for(int pos
= 1; pos
<= int(numkeys
); pos
++) {
332 CPubKey
pubkey(ParseHex(vStrInputParts
[pos
+ 2]));
333 if (!pubkey
.IsFullyValid())
334 throw std::runtime_error("invalid TX output pubkey");
335 pubkeys
.push_back(pubkey
);
339 bool bSegWit
= false;
340 bool bScriptHash
= false;
341 if (vStrInputParts
.size() == numkeys
+ 4) {
342 std::string flags
= vStrInputParts
.back();
343 bSegWit
= (flags
.find("W") != std::string::npos
);
344 bScriptHash
= (flags
.find("S") != std::string::npos
);
346 else if (vStrInputParts
.size() > numkeys
+ 4) {
347 // Validate that there were no more parameters passed
348 throw std::runtime_error("Too many parameters");
351 CScript scriptPubKey
= GetScriptForMultisig(required
, pubkeys
);
354 // Call GetScriptForWitness() to build a P2WSH scriptPubKey
355 scriptPubKey
= GetScriptForWitness(scriptPubKey
);
358 // Get the address for the redeem script, then call
359 // GetScriptForDestination() to construct a P2SH scriptPubKey.
360 CBitcoinAddress
addr(scriptPubKey
);
361 scriptPubKey
= GetScriptForDestination(addr
.Get());
364 // construct TxOut, append to transaction output list
365 CTxOut
txout(value
, scriptPubKey
);
366 tx
.vout
.push_back(txout
);
369 static void MutateTxAddOutData(CMutableTransaction
& tx
, const std::string
& strInput
)
373 // separate [VALUE:]DATA in string
374 size_t pos
= strInput
.find(':');
377 throw std::runtime_error("TX output value not specified");
379 if (pos
!= std::string::npos
) {
380 // Extract and validate VALUE
381 value
= ExtractAndValidateValue(strInput
.substr(0, pos
));
384 // extract and validate DATA
385 std::string strData
= strInput
.substr(pos
+ 1, std::string::npos
);
388 throw std::runtime_error("invalid TX output data");
390 std::vector
<unsigned char> data
= ParseHex(strData
);
392 CTxOut
txout(value
, CScript() << OP_RETURN
<< data
);
393 tx
.vout
.push_back(txout
);
396 static void MutateTxAddOutScript(CMutableTransaction
& tx
, const std::string
& strInput
)
398 // separate VALUE:SCRIPT[:FLAGS]
399 std::vector
<std::string
> vStrInputParts
;
400 boost::split(vStrInputParts
, strInput
, boost::is_any_of(":"));
401 if (vStrInputParts
.size() < 2)
402 throw std::runtime_error("TX output missing separator");
404 // Extract and validate VALUE
405 CAmount value
= ExtractAndValidateValue(vStrInputParts
[0]);
407 // extract and validate script
408 std::string strScript
= vStrInputParts
[1];
409 CScript scriptPubKey
= ParseScript(strScript
);
412 bool bSegWit
= false;
413 bool bScriptHash
= false;
414 if (vStrInputParts
.size() == 3) {
415 std::string flags
= vStrInputParts
.back();
416 bSegWit
= (flags
.find("W") != std::string::npos
);
417 bScriptHash
= (flags
.find("S") != std::string::npos
);
421 scriptPubKey
= GetScriptForWitness(scriptPubKey
);
424 CBitcoinAddress
addr(scriptPubKey
);
425 scriptPubKey
= GetScriptForDestination(addr
.Get());
428 // construct TxOut, append to transaction output list
429 CTxOut
txout(value
, scriptPubKey
);
430 tx
.vout
.push_back(txout
);
433 static void MutateTxDelInput(CMutableTransaction
& tx
, const std::string
& strInIdx
)
435 // parse requested deletion index
436 int inIdx
= atoi(strInIdx
);
437 if (inIdx
< 0 || inIdx
>= (int)tx
.vin
.size()) {
438 std::string strErr
= "Invalid TX input index '" + strInIdx
+ "'";
439 throw std::runtime_error(strErr
.c_str());
442 // delete input from transaction
443 tx
.vin
.erase(tx
.vin
.begin() + inIdx
);
446 static void MutateTxDelOutput(CMutableTransaction
& tx
, const std::string
& strOutIdx
)
448 // parse requested deletion index
449 int outIdx
= atoi(strOutIdx
);
450 if (outIdx
< 0 || outIdx
>= (int)tx
.vout
.size()) {
451 std::string strErr
= "Invalid TX output index '" + strOutIdx
+ "'";
452 throw std::runtime_error(strErr
.c_str());
455 // delete output from transaction
456 tx
.vout
.erase(tx
.vout
.begin() + outIdx
);
459 static const unsigned int N_SIGHASH_OPTS
= 6;
460 static const struct {
463 } sighashOptions
[N_SIGHASH_OPTS
] = {
464 {"ALL", SIGHASH_ALL
},
465 {"NONE", SIGHASH_NONE
},
466 {"SINGLE", SIGHASH_SINGLE
},
467 {"ALL|ANYONECANPAY", SIGHASH_ALL
|SIGHASH_ANYONECANPAY
},
468 {"NONE|ANYONECANPAY", SIGHASH_NONE
|SIGHASH_ANYONECANPAY
},
469 {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE
|SIGHASH_ANYONECANPAY
},
472 static bool findSighashFlags(int& flags
, const std::string
& flagStr
)
476 for (unsigned int i
= 0; i
< N_SIGHASH_OPTS
; i
++) {
477 if (flagStr
== sighashOptions
[i
].flagStr
) {
478 flags
= sighashOptions
[i
].flags
;
486 uint256
ParseHashUO(std::map
<std::string
,UniValue
>& o
, std::string strKey
)
488 if (!o
.count(strKey
))
490 return ParseHashUV(o
[strKey
], strKey
);
493 std::vector
<unsigned char> ParseHexUO(std::map
<std::string
,UniValue
>& o
, std::string strKey
)
495 if (!o
.count(strKey
)) {
496 std::vector
<unsigned char> emptyVec
;
499 return ParseHexUV(o
[strKey
], strKey
);
502 static CAmount
AmountFromValue(const UniValue
& value
)
504 if (!value
.isNum() && !value
.isStr())
505 throw std::runtime_error("Amount is not a number or string");
507 if (!ParseFixedPoint(value
.getValStr(), 8, &amount
))
508 throw std::runtime_error("Invalid amount");
509 if (!MoneyRange(amount
))
510 throw std::runtime_error("Amount out of range");
514 static void MutateTxSign(CMutableTransaction
& tx
, const std::string
& flagStr
)
516 int nHashType
= SIGHASH_ALL
;
518 if (flagStr
.size() > 0)
519 if (!findSighashFlags(nHashType
, flagStr
))
520 throw std::runtime_error("unknown sighash flag/sign option");
522 std::vector
<CTransaction
> txVariants
;
523 txVariants
.push_back(tx
);
525 // mergedTx will end up with all the signatures; it
526 // starts as a clone of the raw tx:
527 CMutableTransaction
mergedTx(txVariants
[0]);
528 bool fComplete
= true;
529 CCoinsView viewDummy
;
530 CCoinsViewCache
view(&viewDummy
);
532 if (!registers
.count("privatekeys"))
533 throw std::runtime_error("privatekeys register variable must be set.");
534 CBasicKeyStore tempKeystore
;
535 UniValue keysObj
= registers
["privatekeys"];
537 for (unsigned int kidx
= 0; kidx
< keysObj
.size(); kidx
++) {
538 if (!keysObj
[kidx
].isStr())
539 throw std::runtime_error("privatekey not a std::string");
540 CBitcoinSecret vchSecret
;
541 bool fGood
= vchSecret
.SetString(keysObj
[kidx
].getValStr());
543 throw std::runtime_error("privatekey not valid");
545 CKey key
= vchSecret
.GetKey();
546 tempKeystore
.AddKey(key
);
549 // Add previous txouts given in the RPC call:
550 if (!registers
.count("prevtxs"))
551 throw std::runtime_error("prevtxs register variable must be set.");
552 UniValue prevtxsObj
= registers
["prevtxs"];
554 for (unsigned int previdx
= 0; previdx
< prevtxsObj
.size(); previdx
++) {
555 UniValue prevOut
= prevtxsObj
[previdx
];
556 if (!prevOut
.isObject())
557 throw std::runtime_error("expected prevtxs internal object");
559 std::map
<std::string
,UniValue::VType
> types
= boost::assign::map_list_of("txid", UniValue::VSTR
)("vout",UniValue::VNUM
)("scriptPubKey",UniValue::VSTR
);
560 if (!prevOut
.checkObject(types
))
561 throw std::runtime_error("prevtxs internal object typecheck fail");
563 uint256 txid
= ParseHashUV(prevOut
["txid"], "txid");
565 int nOut
= atoi(prevOut
["vout"].getValStr());
567 throw std::runtime_error("vout must be positive");
569 std::vector
<unsigned char> pkData(ParseHexUV(prevOut
["scriptPubKey"], "scriptPubKey"));
570 CScript
scriptPubKey(pkData
.begin(), pkData
.end());
573 CCoinsModifier coins
= view
.ModifyCoins(txid
);
574 if (coins
->IsAvailable(nOut
) && coins
->vout
[nOut
].scriptPubKey
!= scriptPubKey
) {
575 std::string
err("Previous output scriptPubKey mismatch:\n");
576 err
= err
+ ScriptToAsmStr(coins
->vout
[nOut
].scriptPubKey
) + "\nvs:\n"+
577 ScriptToAsmStr(scriptPubKey
);
578 throw std::runtime_error(err
);
580 if ((unsigned int)nOut
>= coins
->vout
.size())
581 coins
->vout
.resize(nOut
+1);
582 coins
->vout
[nOut
].scriptPubKey
= scriptPubKey
;
583 coins
->vout
[nOut
].nValue
= 0;
584 if (prevOut
.exists("amount")) {
585 coins
->vout
[nOut
].nValue
= AmountFromValue(prevOut
["amount"]);
589 // if redeemScript given and private keys given,
590 // add redeemScript to the tempKeystore so it can be signed:
591 if ((scriptPubKey
.IsPayToScriptHash() || scriptPubKey
.IsPayToWitnessScriptHash()) &&
592 prevOut
.exists("redeemScript")) {
593 UniValue v
= prevOut
["redeemScript"];
594 std::vector
<unsigned char> rsData(ParseHexUV(v
, "redeemScript"));
595 CScript
redeemScript(rsData
.begin(), rsData
.end());
596 tempKeystore
.AddCScript(redeemScript
);
601 const CKeyStore
& keystore
= tempKeystore
;
603 bool fHashSingle
= ((nHashType
& ~SIGHASH_ANYONECANPAY
) == SIGHASH_SINGLE
);
606 for (unsigned int i
= 0; i
< mergedTx
.vin
.size(); i
++) {
607 CTxIn
& txin
= mergedTx
.vin
[i
];
608 const CCoins
* coins
= view
.AccessCoins(txin
.prevout
.hash
);
609 if (!coins
|| !coins
->IsAvailable(txin
.prevout
.n
)) {
613 const CScript
& prevPubKey
= coins
->vout
[txin
.prevout
.n
].scriptPubKey
;
614 const CAmount
& amount
= coins
->vout
[txin
.prevout
.n
].nValue
;
616 SignatureData sigdata
;
617 // Only sign SIGHASH_SINGLE if there's a corresponding output:
618 if (!fHashSingle
|| (i
< mergedTx
.vout
.size()))
619 ProduceSignature(MutableTransactionSignatureCreator(&keystore
, &mergedTx
, i
, amount
, nHashType
), prevPubKey
, sigdata
);
621 // ... and merge in other signatures:
622 BOOST_FOREACH(const CTransaction
& txv
, txVariants
)
623 sigdata
= CombineSignatures(prevPubKey
, MutableTransactionSignatureChecker(&mergedTx
, i
, amount
), sigdata
, DataFromTransaction(txv
, i
));
624 UpdateTransaction(mergedTx
, i
, sigdata
);
626 if (!VerifyScript(txin
.scriptSig
, prevPubKey
, &txin
.scriptWitness
, STANDARD_SCRIPT_VERIFY_FLAGS
, MutableTransactionSignatureChecker(&mergedTx
, i
, amount
)))
631 // do nothing... for now
632 // perhaps store this for later optional JSON output
640 ECCVerifyHandle globalVerifyHandle
;
651 static void MutateTx(CMutableTransaction
& tx
, const std::string
& command
,
652 const std::string
& commandVal
)
654 std::unique_ptr
<Secp256k1Init
> ecc
;
656 if (command
== "nversion")
657 MutateTxVersion(tx
, commandVal
);
658 else if (command
== "locktime")
659 MutateTxLocktime(tx
, commandVal
);
661 else if (command
== "delin")
662 MutateTxDelInput(tx
, commandVal
);
663 else if (command
== "in")
664 MutateTxAddInput(tx
, commandVal
);
666 else if (command
== "delout")
667 MutateTxDelOutput(tx
, commandVal
);
668 else if (command
== "outaddr")
669 MutateTxAddOutAddr(tx
, commandVal
);
670 else if (command
== "outpubkey")
671 MutateTxAddOutPubKey(tx
, commandVal
);
672 else if (command
== "outmultisig")
673 MutateTxAddOutMultiSig(tx
, commandVal
);
674 else if (command
== "outscript")
675 MutateTxAddOutScript(tx
, commandVal
);
676 else if (command
== "outdata")
677 MutateTxAddOutData(tx
, commandVal
);
679 else if (command
== "sign") {
680 if (!ecc
) { ecc
.reset(new Secp256k1Init()); }
681 MutateTxSign(tx
, commandVal
);
684 else if (command
== "load")
685 RegisterLoad(commandVal
);
687 else if (command
== "set")
688 RegisterSet(commandVal
);
691 throw std::runtime_error("unknown command");
694 static void OutputTxJSON(const CTransaction
& tx
)
696 UniValue
entry(UniValue::VOBJ
);
697 TxToUniv(tx
, uint256(), entry
);
699 std::string jsonOutput
= entry
.write(4);
700 fprintf(stdout
, "%s\n", jsonOutput
.c_str());
703 static void OutputTxHash(const CTransaction
& tx
)
705 std::string strHexHash
= tx
.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
707 fprintf(stdout
, "%s\n", strHexHash
.c_str());
710 static void OutputTxHex(const CTransaction
& tx
)
712 std::string strHex
= EncodeHexTx(tx
);
714 fprintf(stdout
, "%s\n", strHex
.c_str());
717 static void OutputTx(const CTransaction
& tx
)
719 if (GetBoolArg("-json", false))
721 else if (GetBoolArg("-txid", false))
727 static std::string
readStdin()
732 while (!feof(stdin
)) {
733 size_t bread
= fread(buf
, 1, sizeof(buf
), stdin
);
734 ret
.append(buf
, bread
);
735 if (bread
< sizeof(buf
))
740 throw std::runtime_error("error reading stdin");
742 boost::algorithm::trim_right(ret
);
747 static int CommandLineRawTx(int argc
, char* argv
[])
749 std::string strPrint
;
752 // Skip switches; Permit common stdin convention "-"
753 while (argc
> 1 && IsSwitchChar(argv
[1][0]) &&
759 CMutableTransaction tx
;
763 // require at least one param
765 throw std::runtime_error("too few parameters");
767 // param: hex-encoded bitcoin transaction
768 std::string
strHexTx(argv
[1]);
769 if (strHexTx
== "-") // "-" implies standard input
770 strHexTx
= readStdin();
772 if (!DecodeHexTx(tx
, strHexTx
, true))
773 throw std::runtime_error("invalid transaction encoding");
779 for (int i
= startArg
; i
< argc
; i
++) {
780 std::string arg
= argv
[i
];
781 std::string key
, value
;
782 size_t eqpos
= arg
.find('=');
783 if (eqpos
== std::string::npos
)
786 key
= arg
.substr(0, eqpos
);
787 value
= arg
.substr(eqpos
+ 1);
790 MutateTx(tx
, key
, value
);
796 catch (const boost::thread_interrupted
&) {
799 catch (const std::exception
& e
) {
800 strPrint
= std::string("error: ") + e
.what();
804 PrintExceptionContinue(NULL
, "CommandLineRawTx()");
808 if (strPrint
!= "") {
809 fprintf((nRet
== 0 ? stdout
: stderr
), "%s\n", strPrint
.c_str());
814 int main(int argc
, char* argv
[])
819 int ret
= AppInitRawTx(argc
, argv
);
820 if (ret
!= CONTINUE_EXECUTION
)
823 catch (const std::exception
& e
) {
824 PrintExceptionContinue(&e
, "AppInitRawTx()");
827 PrintExceptionContinue(NULL
, "AppInitRawTx()");
831 int ret
= EXIT_FAILURE
;
833 ret
= CommandLineRawTx(argc
, argv
);
835 catch (const std::exception
& e
) {
836 PrintExceptionContinue(&e
, "CommandLineRawTx()");
838 PrintExceptionContinue(NULL
, "CommandLineRawTx()");