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 "policy/rbf.h"
17 #include "primitives/transaction.h"
18 #include "script/script.h"
19 #include "script/sign.h"
22 #include "utilmoneystr.h"
23 #include "utilstrencodings.h"
27 #include <boost/algorithm/string.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("rbfoptin(=N)", _("Set RBF opt-in sequence number for input N (if not provided, opt-in all available inputs)"));
81 strUsage
+= HelpMessageOpt("outaddr=VALUE:ADDRESS", _("Add address-based output to TX"));
82 strUsage
+= HelpMessageOpt("outpubkey=VALUE:PUBKEY[:FLAGS]", _("Add pay-to-pubkey output to TX") + ". " +
83 _("Optionally add the \"W\" flag to produce a pay-to-witness-pubkey-hash output") + ". " +
84 _("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
85 strUsage
+= HelpMessageOpt("outdata=[VALUE:]DATA", _("Add data-based output to TX"));
86 strUsage
+= HelpMessageOpt("outscript=VALUE:SCRIPT[:FLAGS]", _("Add raw script output to TX") + ". " +
87 _("Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output") + ". " +
88 _("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
89 strUsage
+= HelpMessageOpt("outmultisig=VALUE:REQUIRED:PUBKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]", _("Add Pay To n-of-m Multi-sig output to TX. n = REQUIRED, m = PUBKEYS") + ". " +
90 _("Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output") + ". " +
91 _("Optionally add the \"S\" flag to wrap the output in a pay-to-script-hash."));
92 strUsage
+= HelpMessageOpt("sign=SIGHASH-FLAGS", _("Add zero or more signatures to transaction") + ". " +
93 _("This command requires JSON registers:") +
94 _("prevtxs=JSON object") + ", " +
95 _("privatekeys=JSON object") + ". " +
96 _("See signrawtransaction docs for format of sighash flags, JSON objects."));
97 fprintf(stdout
, "%s", strUsage
.c_str());
99 strUsage
= HelpMessageGroup(_("Register Commands:"));
100 strUsage
+= HelpMessageOpt("load=NAME:FILENAME", _("Load JSON file FILENAME into register NAME"));
101 strUsage
+= HelpMessageOpt("set=NAME:JSON-STRING", _("Set register NAME to given JSON-STRING"));
102 fprintf(stdout
, "%s", strUsage
.c_str());
105 fprintf(stderr
, "Error: too few parameters\n");
110 return CONTINUE_EXECUTION
;
113 static void RegisterSetJson(const std::string
& key
, const std::string
& rawJson
)
116 if (!val
.read(rawJson
)) {
117 std::string strErr
= "Cannot parse JSON for key " + key
;
118 throw std::runtime_error(strErr
);
121 registers
[key
] = val
;
124 static void RegisterSet(const std::string
& strInput
)
126 // separate NAME:VALUE in string
127 size_t pos
= strInput
.find(':');
128 if ((pos
== std::string::npos
) ||
130 (pos
== (strInput
.size() - 1)))
131 throw std::runtime_error("Register input requires NAME:VALUE");
133 std::string key
= strInput
.substr(0, pos
);
134 std::string valStr
= strInput
.substr(pos
+ 1, std::string::npos
);
136 RegisterSetJson(key
, valStr
);
139 static void RegisterLoad(const std::string
& strInput
)
141 // separate NAME:FILENAME in string
142 size_t pos
= strInput
.find(':');
143 if ((pos
== std::string::npos
) ||
145 (pos
== (strInput
.size() - 1)))
146 throw std::runtime_error("Register load requires NAME:FILENAME");
148 std::string key
= strInput
.substr(0, pos
);
149 std::string filename
= strInput
.substr(pos
+ 1, std::string::npos
);
151 FILE *f
= fopen(filename
.c_str(), "r");
153 std::string strErr
= "Cannot open file " + filename
;
154 throw std::runtime_error(strErr
);
157 // load file chunks into one big buffer
159 while ((!feof(f
)) && (!ferror(f
))) {
161 int bread
= fread(buf
, 1, sizeof(buf
), f
);
165 valStr
.insert(valStr
.size(), buf
, bread
);
168 int error
= ferror(f
);
172 std::string strErr
= "Error reading file " + filename
;
173 throw std::runtime_error(strErr
);
176 // evaluate as JSON buffer register
177 RegisterSetJson(key
, valStr
);
180 static CAmount
ExtractAndValidateValue(const std::string
& strValue
)
183 if (!ParseMoney(strValue
, value
))
184 throw std::runtime_error("invalid TX output value");
188 static void MutateTxVersion(CMutableTransaction
& tx
, const std::string
& cmdVal
)
190 int64_t newVersion
= atoi64(cmdVal
);
191 if (newVersion
< 1 || newVersion
> CTransaction::MAX_STANDARD_VERSION
)
192 throw std::runtime_error("Invalid TX version requested");
194 tx
.nVersion
= (int) newVersion
;
197 static void MutateTxLocktime(CMutableTransaction
& tx
, const std::string
& cmdVal
)
199 int64_t newLocktime
= atoi64(cmdVal
);
200 if (newLocktime
< 0LL || newLocktime
> 0xffffffffLL
)
201 throw std::runtime_error("Invalid TX locktime requested");
203 tx
.nLockTime
= (unsigned int) newLocktime
;
206 static void MutateTxRBFOptIn(CMutableTransaction
& tx
, const std::string
& strInIdx
)
208 // parse requested index
209 int inIdx
= atoi(strInIdx
);
210 if (inIdx
< 0 || inIdx
>= (int)tx
.vin
.size()) {
211 throw std::runtime_error("Invalid TX input index '" + strInIdx
+ "'");
214 // set the nSequence to MAX_INT - 2 (= RBF opt in flag)
216 for (CTxIn
& txin
: tx
.vin
) {
217 if (strInIdx
== "" || cnt
== inIdx
) {
218 if (txin
.nSequence
> MAX_BIP125_RBF_SEQUENCE
) {
219 txin
.nSequence
= MAX_BIP125_RBF_SEQUENCE
;
226 static void MutateTxAddInput(CMutableTransaction
& tx
, const std::string
& strInput
)
228 std::vector
<std::string
> vStrInputParts
;
229 boost::split(vStrInputParts
, strInput
, boost::is_any_of(":"));
231 // separate TXID:VOUT in string
232 if (vStrInputParts
.size()<2)
233 throw std::runtime_error("TX input missing separator");
235 // extract and validate TXID
236 std::string strTxid
= vStrInputParts
[0];
237 if ((strTxid
.size() != 64) || !IsHex(strTxid
))
238 throw std::runtime_error("invalid TX input txid");
239 uint256
txid(uint256S(strTxid
));
241 static const unsigned int minTxOutSz
= 9;
242 static const unsigned int maxVout
= MAX_BLOCK_BASE_SIZE
/ minTxOutSz
;
244 // extract and validate vout
245 std::string strVout
= vStrInputParts
[1];
246 int vout
= atoi(strVout
);
247 if ((vout
< 0) || (vout
> (int)maxVout
))
248 throw std::runtime_error("invalid TX input vout");
250 // extract the optional sequence number
251 uint32_t nSequenceIn
=std::numeric_limits
<unsigned int>::max();
252 if (vStrInputParts
.size() > 2)
253 nSequenceIn
= std::stoul(vStrInputParts
[2]);
255 // append to transaction input list
256 CTxIn
txin(txid
, vout
, CScript(), nSequenceIn
);
257 tx
.vin
.push_back(txin
);
260 static void MutateTxAddOutAddr(CMutableTransaction
& tx
, const std::string
& strInput
)
262 // Separate into VALUE:ADDRESS
263 std::vector
<std::string
> vStrInputParts
;
264 boost::split(vStrInputParts
, strInput
, boost::is_any_of(":"));
266 if (vStrInputParts
.size() != 2)
267 throw std::runtime_error("TX output missing or too many separators");
269 // Extract and validate VALUE
270 CAmount value
= ExtractAndValidateValue(vStrInputParts
[0]);
272 // extract and validate ADDRESS
273 std::string strAddr
= vStrInputParts
[1];
274 CBitcoinAddress
addr(strAddr
);
276 throw std::runtime_error("invalid TX output address");
277 // build standard output script via GetScriptForDestination()
278 CScript scriptPubKey
= GetScriptForDestination(addr
.Get());
280 // construct TxOut, append to transaction output list
281 CTxOut
txout(value
, scriptPubKey
);
282 tx
.vout
.push_back(txout
);
285 static void MutateTxAddOutPubKey(CMutableTransaction
& tx
, const std::string
& strInput
)
287 // Separate into VALUE:PUBKEY[:FLAGS]
288 std::vector
<std::string
> vStrInputParts
;
289 boost::split(vStrInputParts
, strInput
, boost::is_any_of(":"));
291 if (vStrInputParts
.size() < 2 || vStrInputParts
.size() > 3)
292 throw std::runtime_error("TX output missing or too many separators");
294 // Extract and validate VALUE
295 CAmount value
= ExtractAndValidateValue(vStrInputParts
[0]);
297 // Extract and validate PUBKEY
298 CPubKey
pubkey(ParseHex(vStrInputParts
[1]));
299 if (!pubkey
.IsFullyValid())
300 throw std::runtime_error("invalid TX output pubkey");
301 CScript scriptPubKey
= GetScriptForRawPubKey(pubkey
);
302 CBitcoinAddress
addr(scriptPubKey
);
304 // Extract and validate FLAGS
305 bool bSegWit
= false;
306 bool bScriptHash
= false;
307 if (vStrInputParts
.size() == 3) {
308 std::string flags
= vStrInputParts
[2];
309 bSegWit
= (flags
.find("W") != std::string::npos
);
310 bScriptHash
= (flags
.find("S") != std::string::npos
);
314 // Call GetScriptForWitness() to build a P2WSH scriptPubKey
315 scriptPubKey
= GetScriptForWitness(scriptPubKey
);
318 // Get the address for the redeem script, then call
319 // GetScriptForDestination() to construct a P2SH scriptPubKey.
320 CBitcoinAddress
redeemScriptAddr(scriptPubKey
);
321 scriptPubKey
= GetScriptForDestination(redeemScriptAddr
.Get());
324 // construct TxOut, append to transaction output list
325 CTxOut
txout(value
, scriptPubKey
);
326 tx
.vout
.push_back(txout
);
329 static void MutateTxAddOutMultiSig(CMutableTransaction
& tx
, const std::string
& strInput
)
331 // Separate into VALUE:REQUIRED:NUMKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]
332 std::vector
<std::string
> vStrInputParts
;
333 boost::split(vStrInputParts
, strInput
, boost::is_any_of(":"));
335 // Check that there are enough parameters
336 if (vStrInputParts
.size()<3)
337 throw std::runtime_error("Not enough multisig parameters");
339 // Extract and validate VALUE
340 CAmount value
= ExtractAndValidateValue(vStrInputParts
[0]);
343 uint32_t required
= stoul(vStrInputParts
[1]);
346 uint32_t numkeys
= stoul(vStrInputParts
[2]);
348 // Validate there are the correct number of pubkeys
349 if (vStrInputParts
.size() < numkeys
+ 3)
350 throw std::runtime_error("incorrect number of multisig pubkeys");
352 if (required
< 1 || required
> 20 || numkeys
< 1 || numkeys
> 20 || numkeys
< required
)
353 throw std::runtime_error("multisig parameter mismatch. Required " \
354 + std::to_string(required
) + " of " + std::to_string(numkeys
) + "signatures.");
356 // extract and validate PUBKEYs
357 std::vector
<CPubKey
> pubkeys
;
358 for(int pos
= 1; pos
<= int(numkeys
); pos
++) {
359 CPubKey
pubkey(ParseHex(vStrInputParts
[pos
+ 2]));
360 if (!pubkey
.IsFullyValid())
361 throw std::runtime_error("invalid TX output pubkey");
362 pubkeys
.push_back(pubkey
);
366 bool bSegWit
= false;
367 bool bScriptHash
= false;
368 if (vStrInputParts
.size() == numkeys
+ 4) {
369 std::string flags
= vStrInputParts
.back();
370 bSegWit
= (flags
.find("W") != std::string::npos
);
371 bScriptHash
= (flags
.find("S") != std::string::npos
);
373 else if (vStrInputParts
.size() > numkeys
+ 4) {
374 // Validate that there were no more parameters passed
375 throw std::runtime_error("Too many parameters");
378 CScript scriptPubKey
= GetScriptForMultisig(required
, pubkeys
);
381 // Call GetScriptForWitness() to build a P2WSH scriptPubKey
382 scriptPubKey
= GetScriptForWitness(scriptPubKey
);
385 // Get the address for the redeem script, then call
386 // GetScriptForDestination() to construct a P2SH scriptPubKey.
387 CBitcoinAddress
addr(scriptPubKey
);
388 scriptPubKey
= GetScriptForDestination(addr
.Get());
391 // construct TxOut, append to transaction output list
392 CTxOut
txout(value
, scriptPubKey
);
393 tx
.vout
.push_back(txout
);
396 static void MutateTxAddOutData(CMutableTransaction
& tx
, const std::string
& strInput
)
400 // separate [VALUE:]DATA in string
401 size_t pos
= strInput
.find(':');
404 throw std::runtime_error("TX output value not specified");
406 if (pos
!= std::string::npos
) {
407 // Extract and validate VALUE
408 value
= ExtractAndValidateValue(strInput
.substr(0, pos
));
411 // extract and validate DATA
412 std::string strData
= strInput
.substr(pos
+ 1, std::string::npos
);
415 throw std::runtime_error("invalid TX output data");
417 std::vector
<unsigned char> data
= ParseHex(strData
);
419 CTxOut
txout(value
, CScript() << OP_RETURN
<< data
);
420 tx
.vout
.push_back(txout
);
423 static void MutateTxAddOutScript(CMutableTransaction
& tx
, const std::string
& strInput
)
425 // separate VALUE:SCRIPT[:FLAGS]
426 std::vector
<std::string
> vStrInputParts
;
427 boost::split(vStrInputParts
, strInput
, boost::is_any_of(":"));
428 if (vStrInputParts
.size() < 2)
429 throw std::runtime_error("TX output missing separator");
431 // Extract and validate VALUE
432 CAmount value
= ExtractAndValidateValue(vStrInputParts
[0]);
434 // extract and validate script
435 std::string strScript
= vStrInputParts
[1];
436 CScript scriptPubKey
= ParseScript(strScript
);
439 bool bSegWit
= false;
440 bool bScriptHash
= false;
441 if (vStrInputParts
.size() == 3) {
442 std::string flags
= vStrInputParts
.back();
443 bSegWit
= (flags
.find("W") != std::string::npos
);
444 bScriptHash
= (flags
.find("S") != std::string::npos
);
448 scriptPubKey
= GetScriptForWitness(scriptPubKey
);
451 CBitcoinAddress
addr(scriptPubKey
);
452 scriptPubKey
= GetScriptForDestination(addr
.Get());
455 // construct TxOut, append to transaction output list
456 CTxOut
txout(value
, scriptPubKey
);
457 tx
.vout
.push_back(txout
);
460 static void MutateTxDelInput(CMutableTransaction
& tx
, const std::string
& strInIdx
)
462 // parse requested deletion index
463 int inIdx
= atoi(strInIdx
);
464 if (inIdx
< 0 || inIdx
>= (int)tx
.vin
.size()) {
465 std::string strErr
= "Invalid TX input index '" + strInIdx
+ "'";
466 throw std::runtime_error(strErr
.c_str());
469 // delete input from transaction
470 tx
.vin
.erase(tx
.vin
.begin() + inIdx
);
473 static void MutateTxDelOutput(CMutableTransaction
& tx
, const std::string
& strOutIdx
)
475 // parse requested deletion index
476 int outIdx
= atoi(strOutIdx
);
477 if (outIdx
< 0 || outIdx
>= (int)tx
.vout
.size()) {
478 std::string strErr
= "Invalid TX output index '" + strOutIdx
+ "'";
479 throw std::runtime_error(strErr
.c_str());
482 // delete output from transaction
483 tx
.vout
.erase(tx
.vout
.begin() + outIdx
);
486 static const unsigned int N_SIGHASH_OPTS
= 6;
487 static const struct {
490 } sighashOptions
[N_SIGHASH_OPTS
] = {
491 {"ALL", SIGHASH_ALL
},
492 {"NONE", SIGHASH_NONE
},
493 {"SINGLE", SIGHASH_SINGLE
},
494 {"ALL|ANYONECANPAY", SIGHASH_ALL
|SIGHASH_ANYONECANPAY
},
495 {"NONE|ANYONECANPAY", SIGHASH_NONE
|SIGHASH_ANYONECANPAY
},
496 {"SINGLE|ANYONECANPAY", SIGHASH_SINGLE
|SIGHASH_ANYONECANPAY
},
499 static bool findSighashFlags(int& flags
, const std::string
& flagStr
)
503 for (unsigned int i
= 0; i
< N_SIGHASH_OPTS
; i
++) {
504 if (flagStr
== sighashOptions
[i
].flagStr
) {
505 flags
= sighashOptions
[i
].flags
;
513 static CAmount
AmountFromValue(const UniValue
& value
)
515 if (!value
.isNum() && !value
.isStr())
516 throw std::runtime_error("Amount is not a number or string");
518 if (!ParseFixedPoint(value
.getValStr(), 8, &amount
))
519 throw std::runtime_error("Invalid amount");
520 if (!MoneyRange(amount
))
521 throw std::runtime_error("Amount out of range");
525 static void MutateTxSign(CMutableTransaction
& tx
, const std::string
& flagStr
)
527 int nHashType
= SIGHASH_ALL
;
529 if (flagStr
.size() > 0)
530 if (!findSighashFlags(nHashType
, flagStr
))
531 throw std::runtime_error("unknown sighash flag/sign option");
533 std::vector
<CTransaction
> txVariants
;
534 txVariants
.push_back(tx
);
536 // mergedTx will end up with all the signatures; it
537 // starts as a clone of the raw tx:
538 CMutableTransaction
mergedTx(txVariants
[0]);
539 bool fComplete
= true;
540 CCoinsView viewDummy
;
541 CCoinsViewCache
view(&viewDummy
);
543 if (!registers
.count("privatekeys"))
544 throw std::runtime_error("privatekeys register variable must be set.");
545 CBasicKeyStore tempKeystore
;
546 UniValue keysObj
= registers
["privatekeys"];
548 for (unsigned int kidx
= 0; kidx
< keysObj
.size(); kidx
++) {
549 if (!keysObj
[kidx
].isStr())
550 throw std::runtime_error("privatekey not a std::string");
551 CBitcoinSecret vchSecret
;
552 bool fGood
= vchSecret
.SetString(keysObj
[kidx
].getValStr());
554 throw std::runtime_error("privatekey not valid");
556 CKey key
= vchSecret
.GetKey();
557 tempKeystore
.AddKey(key
);
560 // Add previous txouts given in the RPC call:
561 if (!registers
.count("prevtxs"))
562 throw std::runtime_error("prevtxs register variable must be set.");
563 UniValue prevtxsObj
= registers
["prevtxs"];
565 for (unsigned int previdx
= 0; previdx
< prevtxsObj
.size(); previdx
++) {
566 UniValue prevOut
= prevtxsObj
[previdx
];
567 if (!prevOut
.isObject())
568 throw std::runtime_error("expected prevtxs internal object");
570 std::map
<std::string
, UniValue::VType
> types
= {
571 {"txid", UniValue::VSTR
},
572 {"vout", UniValue::VNUM
},
573 {"scriptPubKey", UniValue::VSTR
},
575 if (!prevOut
.checkObject(types
))
576 throw std::runtime_error("prevtxs internal object typecheck fail");
578 uint256 txid
= ParseHashUV(prevOut
["txid"], "txid");
580 int nOut
= atoi(prevOut
["vout"].getValStr());
582 throw std::runtime_error("vout must be positive");
584 COutPoint
out(txid
, nOut
);
585 std::vector
<unsigned char> pkData(ParseHexUV(prevOut
["scriptPubKey"], "scriptPubKey"));
586 CScript
scriptPubKey(pkData
.begin(), pkData
.end());
589 const Coin
& coin
= view
.AccessCoin(out
);
590 if (!coin
.IsSpent() && coin
.out
.scriptPubKey
!= scriptPubKey
) {
591 std::string
err("Previous output scriptPubKey mismatch:\n");
592 err
= err
+ ScriptToAsmStr(coin
.out
.scriptPubKey
) + "\nvs:\n"+
593 ScriptToAsmStr(scriptPubKey
);
594 throw std::runtime_error(err
);
597 newcoin
.out
.scriptPubKey
= scriptPubKey
;
598 newcoin
.out
.nValue
= 0;
599 if (prevOut
.exists("amount")) {
600 newcoin
.out
.nValue
= AmountFromValue(prevOut
["amount"]);
603 view
.AddCoin(out
, std::move(newcoin
), true);
606 // if redeemScript given and private keys given,
607 // add redeemScript to the tempKeystore so it can be signed:
608 if ((scriptPubKey
.IsPayToScriptHash() || scriptPubKey
.IsPayToWitnessScriptHash()) &&
609 prevOut
.exists("redeemScript")) {
610 UniValue v
= prevOut
["redeemScript"];
611 std::vector
<unsigned char> rsData(ParseHexUV(v
, "redeemScript"));
612 CScript
redeemScript(rsData
.begin(), rsData
.end());
613 tempKeystore
.AddCScript(redeemScript
);
618 const CKeyStore
& keystore
= tempKeystore
;
620 bool fHashSingle
= ((nHashType
& ~SIGHASH_ANYONECANPAY
) == SIGHASH_SINGLE
);
623 for (unsigned int i
= 0; i
< mergedTx
.vin
.size(); i
++) {
624 CTxIn
& txin
= mergedTx
.vin
[i
];
625 const Coin
& coin
= view
.AccessCoin(txin
.prevout
);
626 if (coin
.IsSpent()) {
630 const CScript
& prevPubKey
= coin
.out
.scriptPubKey
;
631 const CAmount
& amount
= coin
.out
.nValue
;
633 SignatureData sigdata
;
634 // Only sign SIGHASH_SINGLE if there's a corresponding output:
635 if (!fHashSingle
|| (i
< mergedTx
.vout
.size()))
636 ProduceSignature(MutableTransactionSignatureCreator(&keystore
, &mergedTx
, i
, amount
, nHashType
), prevPubKey
, sigdata
);
638 // ... and merge in other signatures:
639 BOOST_FOREACH(const CTransaction
& txv
, txVariants
)
640 sigdata
= CombineSignatures(prevPubKey
, MutableTransactionSignatureChecker(&mergedTx
, i
, amount
), sigdata
, DataFromTransaction(txv
, i
));
641 UpdateTransaction(mergedTx
, i
, sigdata
);
643 if (!VerifyScript(txin
.scriptSig
, prevPubKey
, &txin
.scriptWitness
, STANDARD_SCRIPT_VERIFY_FLAGS
, MutableTransactionSignatureChecker(&mergedTx
, i
, amount
)))
648 // do nothing... for now
649 // perhaps store this for later optional JSON output
657 ECCVerifyHandle globalVerifyHandle
;
668 static void MutateTx(CMutableTransaction
& tx
, const std::string
& command
,
669 const std::string
& commandVal
)
671 std::unique_ptr
<Secp256k1Init
> ecc
;
673 if (command
== "nversion")
674 MutateTxVersion(tx
, commandVal
);
675 else if (command
== "locktime")
676 MutateTxLocktime(tx
, commandVal
);
677 else if (command
== "rbfoptin") {
678 MutateTxRBFOptIn(tx
, commandVal
);
681 else if (command
== "delin")
682 MutateTxDelInput(tx
, commandVal
);
683 else if (command
== "in")
684 MutateTxAddInput(tx
, commandVal
);
686 else if (command
== "delout")
687 MutateTxDelOutput(tx
, commandVal
);
688 else if (command
== "outaddr")
689 MutateTxAddOutAddr(tx
, commandVal
);
690 else if (command
== "outpubkey") {
691 if (!ecc
) { ecc
.reset(new Secp256k1Init()); }
692 MutateTxAddOutPubKey(tx
, commandVal
);
693 } else if (command
== "outmultisig") {
694 if (!ecc
) { ecc
.reset(new Secp256k1Init()); }
695 MutateTxAddOutMultiSig(tx
, commandVal
);
696 } else if (command
== "outscript")
697 MutateTxAddOutScript(tx
, commandVal
);
698 else if (command
== "outdata")
699 MutateTxAddOutData(tx
, commandVal
);
701 else if (command
== "sign") {
702 if (!ecc
) { ecc
.reset(new Secp256k1Init()); }
703 MutateTxSign(tx
, commandVal
);
706 else if (command
== "load")
707 RegisterLoad(commandVal
);
709 else if (command
== "set")
710 RegisterSet(commandVal
);
713 throw std::runtime_error("unknown command");
716 static void OutputTxJSON(const CTransaction
& tx
)
718 UniValue
entry(UniValue::VOBJ
);
719 TxToUniv(tx
, uint256(), entry
);
721 std::string jsonOutput
= entry
.write(4);
722 fprintf(stdout
, "%s\n", jsonOutput
.c_str());
725 static void OutputTxHash(const CTransaction
& tx
)
727 std::string strHexHash
= tx
.GetHash().GetHex(); // the hex-encoded transaction hash (aka the transaction id)
729 fprintf(stdout
, "%s\n", strHexHash
.c_str());
732 static void OutputTxHex(const CTransaction
& tx
)
734 std::string strHex
= EncodeHexTx(tx
);
736 fprintf(stdout
, "%s\n", strHex
.c_str());
739 static void OutputTx(const CTransaction
& tx
)
741 if (GetBoolArg("-json", false))
743 else if (GetBoolArg("-txid", false))
749 static std::string
readStdin()
754 while (!feof(stdin
)) {
755 size_t bread
= fread(buf
, 1, sizeof(buf
), stdin
);
756 ret
.append(buf
, bread
);
757 if (bread
< sizeof(buf
))
762 throw std::runtime_error("error reading stdin");
764 boost::algorithm::trim_right(ret
);
769 static int CommandLineRawTx(int argc
, char* argv
[])
771 std::string strPrint
;
774 // Skip switches; Permit common stdin convention "-"
775 while (argc
> 1 && IsSwitchChar(argv
[1][0]) &&
781 CMutableTransaction tx
;
785 // require at least one param
787 throw std::runtime_error("too few parameters");
789 // param: hex-encoded bitcoin transaction
790 std::string
strHexTx(argv
[1]);
791 if (strHexTx
== "-") // "-" implies standard input
792 strHexTx
= readStdin();
794 if (!DecodeHexTx(tx
, strHexTx
, true))
795 throw std::runtime_error("invalid transaction encoding");
801 for (int i
= startArg
; i
< argc
; i
++) {
802 std::string arg
= argv
[i
];
803 std::string key
, value
;
804 size_t eqpos
= arg
.find('=');
805 if (eqpos
== std::string::npos
)
808 key
= arg
.substr(0, eqpos
);
809 value
= arg
.substr(eqpos
+ 1);
812 MutateTx(tx
, key
, value
);
818 catch (const boost::thread_interrupted
&) {
821 catch (const std::exception
& e
) {
822 strPrint
= std::string("error: ") + e
.what();
826 PrintExceptionContinue(NULL
, "CommandLineRawTx()");
830 if (strPrint
!= "") {
831 fprintf((nRet
== 0 ? stdout
: stderr
), "%s\n", strPrint
.c_str());
836 int main(int argc
, char* argv
[])
841 int ret
= AppInitRawTx(argc
, argv
);
842 if (ret
!= CONTINUE_EXECUTION
)
845 catch (const std::exception
& e
) {
846 PrintExceptionContinue(&e
, "AppInitRawTx()");
849 PrintExceptionContinue(NULL
, "AppInitRawTx()");
853 int ret
= EXIT_FAILURE
;
855 ret
= CommandLineRawTx(argc
, argv
);
857 catch (const std::exception
& e
) {
858 PrintExceptionContinue(&e
, "CommandLineRawTx()");
860 PrintExceptionContinue(NULL
, "CommandLineRawTx()");