5 #if defined(HAVE_CONFIG_H) 32 #include <boost/algorithm/string.hpp> 57 argsman.
AddArg(
"outmultisig=VALUE:REQUIRED:PUBKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]",
"Add Pay To n-of-m Multi-sig output to TX. n = REQUIRED, m = PUBKEYS. " 58 "Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output. " 60 argsman.
AddArg(
"outpubkey=VALUE:PUBKEY[:FLAGS]",
"Add pay-to-pubkey output to TX. " 61 "Optionally add the \"W\" flag to produce a pay-to-witness-pubkey-hash output. " 63 argsman.
AddArg(
"outscript=VALUE:SCRIPT[:FLAGS]",
"Add raw script output to TX. " 64 "Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output. " 67 argsman.
AddArg(
"sign=SIGHASH-FLAGS",
"Add zero or more signatures to transaction. " 68 "This command requires JSON registers:" 69 "prevtxs=JSON object, " 70 "privatekeys=JSON object. " 86 tfm::format(std::cerr,
"Error parsing command line arguments: %s\n", error);
93 }
catch (
const std::exception& e) {
105 "Usage: bitcoin-tx [options] <hex-tx> [commands] Update hex-encoded bitcoin transaction\n" 106 "or: bitcoin-tx [options] -create [commands] Create hex-encoded bitcoin transaction\n" 114 tfm::format(std::cerr,
"Error: too few parameters\n");
125 if (!val.
read(rawJson)) {
126 std::string strErr =
"Cannot parse JSON for key " + key;
127 throw std::runtime_error(strErr);
136 size_t pos = strInput.find(
':');
137 if ((pos == std::string::npos) ||
139 (pos == (strInput.size() - 1)))
140 throw std::runtime_error(
"Register input requires NAME:VALUE");
142 std::string key = strInput.substr(0, pos);
143 std::string valStr = strInput.substr(pos + 1, std::string::npos);
151 size_t pos = strInput.find(
':');
152 if ((pos == std::string::npos) ||
154 (pos == (strInput.size() - 1)))
155 throw std::runtime_error(
"Register load requires NAME:FILENAME");
157 std::string key = strInput.substr(0, pos);
158 std::string filename = strInput.substr(pos + 1, std::string::npos);
160 FILE *f =
fopen(filename.c_str(),
"r");
162 std::string strErr =
"Cannot open file " + filename;
163 throw std::runtime_error(strErr);
168 while ((!feof(f)) && (!ferror(f))) {
170 int bread = fread(buf, 1,
sizeof(buf), f);
174 valStr.insert(valStr.size(), buf, bread);
177 int error = ferror(f);
181 std::string strErr =
"Error reading file " + filename;
182 throw std::runtime_error(strErr);
193 throw std::runtime_error(
"invalid TX output value");
201 throw std::runtime_error(
"Invalid TX version requested: '" + cmdVal +
"'");
210 if (!
ParseInt64(cmdVal, &newLocktime) || newLocktime < 0LL || newLocktime > 0xffffffffLL)
211 throw std::runtime_error(
"Invalid TX locktime requested: '" + cmdVal +
"'");
213 tx.
nLockTime = (
unsigned int) newLocktime;
220 if (!
ParseInt64(strInIdx, &inIdx) || inIdx < 0 || inIdx >= static_cast<int64_t>(tx.
vin.size())) {
221 throw std::runtime_error(
"Invalid TX input index '" + strInIdx +
"'");
227 if (strInIdx ==
"" || cnt == inIdx) {
238 std::vector<std::string> vStrInputParts;
239 boost::split(vStrInputParts, strInput, boost::is_any_of(
":"));
242 if (vStrInputParts.size()<2)
243 throw std::runtime_error(
"TX input missing separator");
248 throw std::runtime_error(
"invalid TX input txid");
251 static const unsigned int minTxOutSz = 9;
255 const std::string& strVout = vStrInputParts[1];
257 if (!
ParseInt64(strVout, &vout) || vout < 0 || vout >
static_cast<int64_t
>(maxVout))
258 throw std::runtime_error(
"invalid TX input vout '" + strVout +
"'");
262 if (vStrInputParts.size() > 2)
263 nSequenceIn = std::stoul(vStrInputParts[2]);
267 tx.
vin.push_back(txin);
273 std::vector<std::string> vStrInputParts;
274 boost::split(vStrInputParts, strInput, boost::is_any_of(
":"));
276 if (vStrInputParts.size() != 2)
277 throw std::runtime_error(
"TX output missing or too many separators");
283 std::string strAddr = vStrInputParts[1];
286 throw std::runtime_error(
"invalid TX output address");
291 CTxOut txout(value, scriptPubKey);
292 tx.
vout.push_back(txout);
298 std::vector<std::string> vStrInputParts;
299 boost::split(vStrInputParts, strInput, boost::is_any_of(
":"));
301 if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3)
302 throw std::runtime_error(
"TX output missing or too many separators");
310 throw std::runtime_error(
"invalid TX output pubkey");
314 bool bSegWit =
false;
315 bool bScriptHash =
false;
316 if (vStrInputParts.size() == 3) {
317 std::string
flags = vStrInputParts[2];
318 bSegWit = (flags.find(
'W') != std::string::npos);
319 bScriptHash = (flags.find(
'S') != std::string::npos);
324 throw std::runtime_error(
"Uncompressed pubkeys are not useable for SegWit outputs");
335 CTxOut txout(value, scriptPubKey);
336 tx.
vout.push_back(txout);
342 std::vector<std::string> vStrInputParts;
343 boost::split(vStrInputParts, strInput, boost::is_any_of(
":"));
346 if (vStrInputParts.size()<3)
347 throw std::runtime_error(
"Not enough multisig parameters");
353 uint32_t required = stoul(vStrInputParts[1]);
356 uint32_t numkeys = stoul(vStrInputParts[2]);
359 if (vStrInputParts.size() < numkeys + 3)
360 throw std::runtime_error(
"incorrect number of multisig pubkeys");
363 throw std::runtime_error(
"multisig parameter mismatch. Required " \
367 std::vector<CPubKey> pubkeys;
368 for(
int pos = 1; pos <= int(numkeys); pos++) {
371 throw std::runtime_error(
"invalid TX output pubkey");
372 pubkeys.push_back(pubkey);
376 bool bSegWit =
false;
377 bool bScriptHash =
false;
378 if (vStrInputParts.size() == numkeys + 4) {
379 std::string
flags = vStrInputParts.back();
380 bSegWit = (flags.find(
'W') != std::string::npos);
381 bScriptHash = (flags.find(
'S') != std::string::npos);
383 else if (vStrInputParts.size() > numkeys + 4) {
385 throw std::runtime_error(
"Too many parameters");
391 for (
const CPubKey& pubkey : pubkeys) {
392 if (!pubkey.IsCompressed()) {
393 throw std::runtime_error(
"Uncompressed pubkeys are not useable for SegWit outputs");
409 CTxOut txout(value, scriptPubKey);
410 tx.
vout.push_back(txout);
418 size_t pos = strInput.find(
':');
421 throw std::runtime_error(
"TX output value not specified");
423 if (pos != std::string::npos) {
429 std::string strData = strInput.substr(pos + 1, std::string::npos);
432 throw std::runtime_error(
"invalid TX output data");
434 std::vector<unsigned char> data =
ParseHex(strData);
437 tx.
vout.push_back(txout);
443 std::vector<std::string> vStrInputParts;
444 boost::split(vStrInputParts, strInput, boost::is_any_of(
":"));
445 if (vStrInputParts.size() < 2)
446 throw std::runtime_error(
"TX output missing separator");
452 std::string strScript = vStrInputParts[1];
456 bool bSegWit =
false;
457 bool bScriptHash =
false;
458 if (vStrInputParts.size() == 3) {
459 std::string
flags = vStrInputParts.back();
460 bSegWit = (flags.find(
'W') != std::string::npos);
461 bScriptHash = (flags.find(
'S') != std::string::npos);
481 CTxOut txout(value, scriptPubKey);
482 tx.
vout.push_back(txout);
489 if (!
ParseInt64(strInIdx, &inIdx) || inIdx < 0 || inIdx >= static_cast<int64_t>(tx.
vin.size())) {
490 throw std::runtime_error(
"Invalid TX input index '" + strInIdx +
"'");
494 tx.
vin.erase(tx.
vin.begin() + inIdx);
501 if (!
ParseInt64(strOutIdx, &outIdx) || outIdx < 0 || outIdx >= static_cast<int64_t>(tx.
vout.size())) {
502 throw std::runtime_error(
"Invalid TX output index '" + strOutIdx +
"'");
506 tx.
vout.erase(tx.
vout.begin() + outIdx);
510 static const struct {
539 throw std::runtime_error(
"Amount is not a number or string");
542 throw std::runtime_error(
"Invalid amount");
544 throw std::runtime_error(
"Amount out of range");
552 if (flagStr.size() > 0)
554 throw std::runtime_error(
"unknown sighash flag/sign option");
564 throw std::runtime_error(
"privatekeys register variable must be set.");
568 for (
unsigned int kidx = 0; kidx < keysObj.
size(); kidx++) {
569 if (!keysObj[kidx].isStr())
570 throw std::runtime_error(
"privatekey not a std::string");
573 throw std::runtime_error(
"privatekey not valid");
580 throw std::runtime_error(
"prevtxs register variable must be set.");
583 for (
unsigned int previdx = 0; previdx < prevtxsObj.
size(); previdx++) {
584 UniValue prevOut = prevtxsObj[previdx];
586 throw std::runtime_error(
"expected prevtxs internal object");
588 std::map<std::string, UniValue::VType> types = {
594 throw std::runtime_error(
"prevtxs internal object typecheck fail");
598 throw std::runtime_error(
"txid must be hexadecimal string (not '" + prevOut[
"txid"].get_str() +
"')");
601 const int nOut = prevOut[
"vout"].
get_int();
603 throw std::runtime_error(
"vout cannot be negative");
606 std::vector<unsigned char> pkData(
ParseHexUV(prevOut[
"scriptPubKey"],
"scriptPubKey"));
607 CScript scriptPubKey(pkData.begin(), pkData.end());
612 std::string err(
"Previous output scriptPubKey mismatch:\n");
615 throw std::runtime_error(err);
620 if (prevOut.
exists(
"amount")) {
624 view.
AddCoin(out, std::move(newcoin),
true);
629 if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) &&
630 prevOut.
exists(
"redeemScript")) {
631 UniValue v = prevOut[
"redeemScript"];
632 std::vector<unsigned char> rsData(
ParseHexUV(v,
"redeemScript"));
633 CScript redeemScript(rsData.begin(), rsData.end());
644 for (
unsigned int i = 0; i < mergedTx.vin.size(); i++) {
645 CTxIn& txin = mergedTx.vin[i];
655 if (!fHashSingle || (i < mergedTx.vout.size()))
678 const std::string& commandVal)
680 std::unique_ptr<Secp256k1Init> ecc;
682 if (command ==
"nversion")
684 else if (command ==
"locktime")
686 else if (command ==
"replaceable") {
690 else if (command ==
"delin")
692 else if (command ==
"in")
695 else if (command ==
"delout")
697 else if (command ==
"outaddr")
699 else if (command ==
"outpubkey") {
702 }
else if (command ==
"outmultisig") {
705 }
else if (command ==
"outscript")
707 else if (command ==
"outdata")
710 else if (command ==
"sign") {
715 else if (command ==
"load")
718 else if (command ==
"set")
722 throw std::runtime_error(
"unknown command");
730 std::string jsonOutput = entry.
write(4);
763 while (!feof(stdin)) {
764 size_t bread = fread(buf, 1,
sizeof(buf), stdin);
765 ret.append(buf, bread);
766 if (bread <
sizeof(buf))
771 throw std::runtime_error(
"error reading stdin");
773 boost::algorithm::trim_right(ret);
780 std::string strPrint;
796 throw std::runtime_error(
"too few parameters");
799 std::string strHexTx(argv[1]);
804 throw std::runtime_error(
"invalid transaction encoding");
810 for (
int i = startArg; i < argc; i++) {
811 std::string arg = argv[i];
812 std::string key, value;
813 size_t eqpos = arg.find(
'=');
814 if (eqpos == std::string::npos)
817 key = arg.substr(0, eqpos);
818 value = arg.substr(eqpos + 1);
826 catch (
const std::exception& e) {
827 strPrint = std::string(
"error: ") + e.what();
835 if (strPrint !=
"") {
836 tfm::format(nRet == 0 ? std::cout : std::cerr,
"%s\n", strPrint);
841 int main(
int argc,
char* argv[])
850 catch (
const std::exception& e) {
858 int ret = EXIT_FAILURE;
862 catch (
const std::exception& e) {
int main(int argc, char *argv[])
std::vector< unsigned char > ParseHexUV(const UniValue &v, const std::string &strName)
static void MutateTxAddOutScript(CMutableTransaction &tx, const std::string &strInput)
static std::map< std::string, UniValue > registers
static const int MAX_PUBKEYS_PER_MULTISIG
void ECC_Start()
Initialize the elliptic curve support.
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
static void MutateTxAddOutAddr(CMutableTransaction &tx, const std::string &strInput)
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
static void MutateTxAddOutMultiSig(CMutableTransaction &tx, const std::string &strInput)
static const uint32_t MAX_BIP125_RBF_SEQUENCE
static const int WITNESS_SCALE_FACTOR
FILE * fopen(const fs::path &p, const char *mode)
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
void TxToUniv(const CTransaction &tx, const uint256 &hashBlock, UniValue &entry, bool include_hex=true, int serialize_flags=0, const CTxUndo *txundo=nullptr)
bool read(const char *raw, size_t len)
static void MutateTxVersion(CMutableTransaction &tx, const std::string &cmdVal)
static const uint32_t SEQUENCE_FINAL
virtual bool AddCScript(const CScript &redeemScript)
bool MoneyRange(const CAmount &nValue)
std::vector< unsigned char > ParseHex(const char *psz)
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
CTxOut out
unspent transaction output
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
static void MutateTxAddOutData(CMutableTransaction &tx, const std::string &strInput)
bool ParseParameters(int argc, const char *const argv[], std::string &error)
const std::function< std::string(const char *)> G_TRANSLATION_FUN
Translate string to current locale using Qt.
static void RegisterLoad(const std::string &strInput)
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
A signature creator for transactions.
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
static void MutateTxLocktime(CMutableTransaction &tx, const std::string &cmdVal)
static decltype(CTransaction::nVersion) constexpr TX_MAX_STANDARD_VERSION
bool ParseMoney(const std::string &money_string, CAmount &nRet)
Parse an amount denoted in full coins.
static void RegisterSetJson(const std::string &key, const std::string &rawJson)
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
static CAmount ExtractAndValidateValue(const std::string &strValue)
static void OutputTxHex(const CTransaction &tx)
const std::string & getValStr() const
bool ParseFixedPoint(const std::string &val, int decimals, int64_t *amount_out)
Parse number as fixed point according to JSON number syntax.
bool ParseInt64(const std::string &str, int64_t *out)
Convert string to signed 64-bit integer with strict parse error feedback.
std::string GetHelpMessage() const
Get the help string.
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
int64_t CAmount
Amount in satoshis (Can be negative)
static void MutateTxSign(CMutableTransaction &tx, const std::string &flagStr)
uint32_t nHeight
at which height this containing transaction was included in the active block chain ...
std::string ToString(const T &t)
Locale-independent version of std::to_string.
static const unsigned int N_SIGHASH_OPTS
Users of this module must hold an ECCVerifyHandle.
static void MutateTxDelInput(CMutableTransaction &tx, const std::string &strInIdx)
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode=false)
Create the assembly string representation of a CScript object.
static CAmount AmountFromValue(const UniValue &value)
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid()) ...
static void SetupBitcoinTxArgs(ArgsManager &argsman)
Abstract view on the open txout dataset.
An input of a transaction.
void ECC_Stop()
Deinitialize the elliptic curve support.
static int AppInitRawTx(int argc, char *argv[])
const uint256 & GetHash() const
bool exists(const std::string &key) const
void SelectParams(const std::string &network)
Sets the params returned by Params() to those for the given chain name.
static void MutateTxRBFOptIn(CMutableTransaction &tx, const std::string &strInIdx)
An encapsulated public key.
Fillable signing provider that keeps keys in an address->secret map.
bool IsHex(const std::string &str)
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
bool HelpRequested(const ArgsManager &args)
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
An output of a transaction.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
static const int MAX_SCRIPT_SIZE
void PrintExceptionContinue(const std::exception *pex, const char *pszThread)
An outpoint - a combination of a transaction hash and an index n into its vout.
std::vector< CTxOut > vout
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
std::string FormatFullVersion()
static bool findSighashFlags(int &flags, const std::string &flagStr)
bool checkObject(const std::map< std::string, UniValue::VType > &memberTypes) const
CTxDestination DecodeDestination(const std::string &str)
static void OutputTx(const CTransaction &tx)
static std::string readStdin()
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn, const CTxOut &txout)
Extract signature data from a transaction input, and insert it.
Serialized script, used inside transaction inputs and outputs.
static void MutateTxAddOutPubKey(CMutableTransaction &tx, const std::string &strInput)
static void MutateTx(CMutableTransaction &tx, const std::string &command, const std::string &commandVal)
static int CommandLineRawTx(int argc, char *argv[])
void UpdateInput(CTxIn &input, const SignatureData &data)
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness=false, bool try_witness=true)
std::string GetHex() const
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
ECCVerifyHandle globalVerifyHandle
static void RegisterSet(const std::string &strInput)
A mutable version of CTransaction.
std::string GetChainName() const
Returns the appropriate chain name from the program arguments.
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
bool IsSwitchChar(char c)
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
An encapsulated private key.
The basic transaction that is broadcasted on the network and contained in blocks. ...
CKey DecodeSecret(const std::string &str)
CCoinsView that adds a memory cache for transactions to another CCoinsView.
static const struct @0 sighashOptions[N_SIGHASH_OPTS]
static const int CONTINUE_EXECUTION
CScript ParseScript(const std::string &s)
bool error(const char *fmt, const Args &... args)
static void MutateTxDelOutput(CMutableTransaction &tx, const std::string &strOutIdx)
static void OutputTxHash(const CTransaction &tx)
virtual bool AddKey(const CKey &key)
static void MutateTxAddInput(CMutableTransaction &tx, const std::string &strInput)
bool IsValid() const
Check whether this private key is valid.
bool IsCompressed() const
Check whether this is a compressed public key.
static void OutputTxJSON(const CTransaction &tx)