5 #if defined(HAVE_CONFIG_H)
60 argsman.
AddArg(
"outmultisig=VALUE:REQUIRED:PUBKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]",
"Add Pay To n-of-m Multi-sig output to TX. n = REQUIRED, m = PUBKEYS. "
61 "Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output. "
63 argsman.
AddArg(
"outpubkey=VALUE:PUBKEY[:FLAGS]",
"Add pay-to-pubkey output to TX. "
64 "Optionally add the \"W\" flag to produce a pay-to-witness-pubkey-hash output. "
66 argsman.
AddArg(
"outscript=VALUE:SCRIPT[:FLAGS]",
"Add raw script output to TX. "
67 "Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output. "
69 argsman.
AddArg(
"replaceable(=N)",
"Sets Replace-By-Fee (RBF) opt-in sequence number for input N. "
70 "If N is not provided, the command attempts to opt-in all available inputs for RBF. "
72 argsman.
AddArg(
"sign=SIGHASH-FLAGS",
"Add zero or more signatures to transaction. "
73 "This command requires JSON registers:"
74 "prevtxs=JSON object, "
75 "privatekeys=JSON object. "
91 tfm::format(std::cerr,
"Error parsing command line arguments: %s\n", error);
98 }
catch (
const std::exception& e) {
113 "Usage: bitcoin-tx [options] <hex-tx> [commands] Update hex-encoded bitcoin transaction\n"
114 "or: bitcoin-tx [options] -create [commands] Create hex-encoded bitcoin transaction\n"
122 tfm::format(std::cerr,
"Error: too few parameters\n");
133 if (!val.
read(rawJson)) {
134 std::string strErr =
"Cannot parse JSON for key " + key;
135 throw std::runtime_error(strErr);
144 size_t pos = strInput.find(
':');
145 if ((pos == std::string::npos) ||
147 (pos == (strInput.size() - 1)))
148 throw std::runtime_error(
"Register input requires NAME:VALUE");
150 std::string key = strInput.substr(0, pos);
151 std::string valStr = strInput.substr(pos + 1, std::string::npos);
159 size_t pos = strInput.find(
':');
160 if ((pos == std::string::npos) ||
162 (pos == (strInput.size() - 1)))
163 throw std::runtime_error(
"Register load requires NAME:FILENAME");
165 std::string key = strInput.substr(0, pos);
166 std::string filename = strInput.substr(pos + 1, std::string::npos);
170 std::string strErr =
"Cannot open file " + filename;
171 throw std::runtime_error(strErr);
176 while ((!feof(f)) && (!ferror(f))) {
178 int bread = fread(buf, 1,
sizeof(buf), f);
182 valStr.insert(valStr.size(), buf, bread);
185 int error = ferror(f);
189 std::string strErr =
"Error reading file " + filename;
190 throw std::runtime_error(strErr);
199 if (std::optional<CAmount> parsed =
ParseMoney(strValue)) {
200 return parsed.value();
202 throw std::runtime_error(
"invalid TX output value");
210 throw std::runtime_error(
"Invalid TX version requested: '" + cmdVal +
"'");
219 if (!
ParseInt64(cmdVal, &newLocktime) || newLocktime < 0LL || newLocktime > 0xffffffffLL)
220 throw std::runtime_error(
"Invalid TX locktime requested: '" + cmdVal +
"'");
222 tx.
nLockTime = (
unsigned int) newLocktime;
229 if (strInIdx !=
"" && (!
ParseInt64(strInIdx, &inIdx) || inIdx < 0 || inIdx >=
static_cast<int64_t
>(tx.
vin.size()))) {
230 throw std::runtime_error(
"Invalid TX input index '" + strInIdx +
"'");
236 if (strInIdx ==
"" || cnt == inIdx) {
245 template <
typename T>
249 if (!parsed.has_value()) {
250 throw std::runtime_error(err +
" '" + int_str +
"'");
252 return parsed.value();
257 std::vector<std::string> vStrInputParts =
SplitString(strInput,
':');
260 if (vStrInputParts.size()<2)
261 throw std::runtime_error(
"TX input missing separator");
266 throw std::runtime_error(
"invalid TX input txid");
269 static const unsigned int minTxOutSz = 9;
273 const std::string& strVout = vStrInputParts[1];
275 if (!
ParseInt64(strVout, &vout) || vout < 0 || vout >
static_cast<int64_t
>(maxVout))
276 throw std::runtime_error(
"invalid TX input vout '" + strVout +
"'");
280 if (vStrInputParts.size() > 2) {
281 nSequenceIn = TrimAndParse<uint32_t>(vStrInputParts.at(2),
"invalid TX sequence id");
286 tx.
vin.push_back(txin);
292 std::vector<std::string> vStrInputParts =
SplitString(strInput,
':');
294 if (vStrInputParts.size() != 2)
295 throw std::runtime_error(
"TX output missing or too many separators");
301 std::string strAddr = vStrInputParts[1];
304 throw std::runtime_error(
"invalid TX output address");
309 CTxOut txout(value, scriptPubKey);
310 tx.
vout.push_back(txout);
316 std::vector<std::string> vStrInputParts =
SplitString(strInput,
':');
318 if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3)
319 throw std::runtime_error(
"TX output missing or too many separators");
327 throw std::runtime_error(
"invalid TX output pubkey");
331 bool bSegWit =
false;
332 bool bScriptHash =
false;
333 if (vStrInputParts.size() == 3) {
334 std::string
flags = vStrInputParts[2];
335 bSegWit = (
flags.find(
'W') != std::string::npos);
336 bScriptHash = (
flags.find(
'S') != std::string::npos);
341 throw std::runtime_error(
"Uncompressed pubkeys are not useable for SegWit outputs");
352 CTxOut txout(value, scriptPubKey);
353 tx.
vout.push_back(txout);
359 std::vector<std::string> vStrInputParts =
SplitString(strInput,
':');
362 if (vStrInputParts.size()<3)
363 throw std::runtime_error(
"Not enough multisig parameters");
369 const uint32_t required{TrimAndParse<uint32_t>(vStrInputParts.at(1),
"invalid multisig required number")};
372 const uint32_t numkeys{TrimAndParse<uint32_t>(vStrInputParts.at(2),
"invalid multisig total number")};
375 if (vStrInputParts.size() < numkeys + 3)
376 throw std::runtime_error(
"incorrect number of multisig pubkeys");
379 throw std::runtime_error(
"multisig parameter mismatch. Required " \
383 std::vector<CPubKey> pubkeys;
384 for(
int pos = 1; pos <= int(numkeys); pos++) {
387 throw std::runtime_error(
"invalid TX output pubkey");
388 pubkeys.push_back(pubkey);
392 bool bSegWit =
false;
393 bool bScriptHash =
false;
394 if (vStrInputParts.size() == numkeys + 4) {
395 std::string
flags = vStrInputParts.back();
396 bSegWit = (
flags.find(
'W') != std::string::npos);
397 bScriptHash = (
flags.find(
'S') != std::string::npos);
399 else if (vStrInputParts.size() > numkeys + 4) {
401 throw std::runtime_error(
"Too many parameters");
407 for (
const CPubKey& pubkey : pubkeys) {
408 if (!pubkey.IsCompressed()) {
409 throw std::runtime_error(
"Uncompressed pubkeys are not useable for SegWit outputs");
425 CTxOut txout(value, scriptPubKey);
426 tx.
vout.push_back(txout);
434 size_t pos = strInput.find(
':');
437 throw std::runtime_error(
"TX output value not specified");
439 if (pos == std::string::npos) {
448 const std::string strData{strInput.substr(pos, std::string::npos)};
451 throw std::runtime_error(
"invalid TX output data");
453 std::vector<unsigned char> data =
ParseHex(strData);
456 tx.
vout.push_back(txout);
462 std::vector<std::string> vStrInputParts =
SplitString(strInput,
':');
463 if (vStrInputParts.size() < 2)
464 throw std::runtime_error(
"TX output missing separator");
470 std::string strScript = vStrInputParts[1];
474 bool bSegWit =
false;
475 bool bScriptHash =
false;
476 if (vStrInputParts.size() == 3) {
477 std::string
flags = vStrInputParts.back();
478 bSegWit = (
flags.find(
'W') != std::string::npos);
479 bScriptHash = (
flags.find(
'S') != std::string::npos);
499 CTxOut txout(value, scriptPubKey);
500 tx.
vout.push_back(txout);
507 if (!
ParseInt64(strInIdx, &inIdx) || inIdx < 0 || inIdx >=
static_cast<int64_t
>(tx.
vin.size())) {
508 throw std::runtime_error(
"Invalid TX input index '" + strInIdx +
"'");
512 tx.
vin.erase(tx.
vin.begin() + inIdx);
519 if (!
ParseInt64(strOutIdx, &outIdx) || outIdx < 0 || outIdx >=
static_cast<int64_t
>(tx.
vout.size())) {
520 throw std::runtime_error(
"Invalid TX output index '" + strOutIdx +
"'");
524 tx.
vout.erase(tx.
vout.begin() + outIdx);
528 static const struct {
558 throw std::runtime_error(
"Amount is not a number or string");
561 throw std::runtime_error(
"Invalid amount");
563 throw std::runtime_error(
"Amount out of range");
573 throw std::runtime_error(strName +
" must be hexadecimal string (not '" + strHex +
"')");
583 throw std::runtime_error(
"unknown sighash flag/sign option");
593 throw std::runtime_error(
"privatekeys register variable must be set.");
597 for (
unsigned int kidx = 0; kidx < keysObj.
size(); kidx++) {
598 if (!keysObj[kidx].isStr())
599 throw std::runtime_error(
"privatekey not a std::string");
602 throw std::runtime_error(
"privatekey not valid");
609 throw std::runtime_error(
"prevtxs register variable must be set.");
612 for (
unsigned int previdx = 0; previdx < prevtxsObj.
size(); previdx++) {
613 const UniValue& prevOut = prevtxsObj[previdx];
615 throw std::runtime_error(
"expected prevtxs internal object");
617 std::map<std::string, UniValue::VType> types = {
623 throw std::runtime_error(
"prevtxs internal object typecheck fail");
627 throw std::runtime_error(
"txid must be hexadecimal string (not '" + prevOut[
"txid"].get_str() +
"')");
630 const int nOut = prevOut[
"vout"].
getInt<
int>();
632 throw std::runtime_error(
"vout cannot be negative");
635 std::vector<unsigned char> pkData(
ParseHexUV(prevOut[
"scriptPubKey"],
"scriptPubKey"));
636 CScript scriptPubKey(pkData.begin(), pkData.end());
641 std::string err(
"Previous output scriptPubKey mismatch:\n");
644 throw std::runtime_error(err);
649 if (prevOut.
exists(
"amount")) {
659 prevOut.
exists(
"redeemScript")) {
660 UniValue v = prevOut[
"redeemScript"];
661 std::vector<unsigned char> rsData(
ParseHexUV(v,
"redeemScript"));
662 CScript redeemScript(rsData.begin(), rsData.end());
673 for (
unsigned int i = 0; i < mergedTx.vin.size(); i++) {
674 CTxIn& txin = mergedTx.vin[i];
684 if (!fHashSingle || (i < mergedTx.vout.size()))
688 throw std::runtime_error(
strprintf(
"Missing amount for CTxOut with scriptPubKey=%s",
HexStr(prevPubKey)));
709 const std::string& commandVal)
711 std::unique_ptr<Secp256k1Init> ecc;
715 else if (
command ==
"locktime")
717 else if (
command ==
"replaceable") {
730 else if (
command ==
"outpubkey") {
733 }
else if (
command ==
"outmultisig") {
736 }
else if (
command ==
"outscript")
753 throw std::runtime_error(
"unknown command");
761 std::string jsonOutput = entry.
write(4);
794 while (!feof(stdin)) {
795 size_t bread = fread(buf, 1,
sizeof(buf), stdin);
796 ret.append(buf, bread);
797 if (bread <
sizeof(buf))
802 throw std::runtime_error(
"error reading stdin");
825 throw std::runtime_error(
"too few parameters");
828 std::string strHexTx(argv[1]);
833 throw std::runtime_error(
"invalid transaction encoding");
839 for (
int i = startArg; i < argc; i++) {
840 std::string arg = argv[i];
841 std::string key, value;
842 size_t eqpos = arg.find(
'=');
843 if (eqpos == std::string::npos)
846 key = arg.substr(0, eqpos);
847 value = arg.substr(eqpos + 1);
855 catch (
const std::exception& e) {
856 strPrint = std::string(
"error: ") + e.what();
879 catch (
const std::exception& e) {
891 catch (
const std::exception& e) {
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination corresponds to one with an address.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
bool MoneyRange(const CAmount &nValue)
int64_t CAmount
Amount in satoshis (Can be negative)
bool HelpRequested(const ArgsManager &args)
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
bool IsSwitchChar(char c)
static bool findSighashFlags(int &flags, const std::string &flagStr)
static void OutputTxHash(const CTransaction &tx)
static const unsigned int N_SIGHASH_OPTS
static void MutateTxSign(CMutableTransaction &tx, const std::string &flagStr)
static const int CONTINUE_EXECUTION
static std::string readStdin()
static void OutputTxJSON(const CTransaction &tx)
static void RegisterSet(const std::string &strInput)
static void RegisterSetJson(const std::string &key, const std::string &rawJson)
static CAmount ExtractAndValidateValue(const std::string &strValue)
static void MutateTxDelOutput(CMutableTransaction &tx, const std::string &strOutIdx)
static const struct @0 sighashOptions[N_SIGHASH_OPTS]
static CAmount AmountFromValue(const UniValue &value)
static void MutateTx(CMutableTransaction &tx, const std::string &command, const std::string &commandVal)
const std::function< std::string(const char *)> G_TRANSLATION_FUN
Translate string to current locale using Qt.
static T TrimAndParse(const std::string &int_str, const std::string &err)
static void MutateTxAddOutPubKey(CMutableTransaction &tx, const std::string &strInput)
static std::vector< unsigned char > ParseHexUV(const UniValue &v, const std::string &strName)
static void MutateTxRBFOptIn(CMutableTransaction &tx, const std::string &strInIdx)
static void MutateTxAddOutData(CMutableTransaction &tx, const std::string &strInput)
static void MutateTxVersion(CMutableTransaction &tx, const std::string &cmdVal)
static void MutateTxAddOutAddr(CMutableTransaction &tx, const std::string &strInput)
static int CommandLineRawTx(int argc, char *argv[])
static void OutputTxHex(const CTransaction &tx)
static void RegisterLoad(const std::string &strInput)
static void MutateTxDelInput(CMutableTransaction &tx, const std::string &strInIdx)
static int AppInitRawTx(int argc, char *argv[])
static void MutateTxAddInput(CMutableTransaction &tx, const std::string &strInput)
static std::map< std::string, UniValue > registers
static void SetupBitcoinTxArgs(ArgsManager &argsman)
static void MutateTxAddOutMultiSig(CMutableTransaction &tx, const std::string &strInput)
static void MutateTxAddOutScript(CMutableTransaction &tx, const std::string &strInput)
static void MutateTxLocktime(CMutableTransaction &tx, const std::string &cmdVal)
static void OutputTx(const CTransaction &tx)
void SelectParams(const ChainType chain)
Sets the params returned by Params() to those for the given chain type.
void SetupChainParamsBaseOptions(ArgsManager &argsman)
Set the arguments for chainparams.
@ ALLOW_ANY
disable validation
ChainType GetChainType() const
Returns the appropriate chain type from the program arguments.
bool ParseParameters(int argc, const char *const argv[], std::string &error)
std::string GetHelpMessage() const
Get the help string.
bool IsArgSet(const std::string &strArg) const
Return true if the given argument has been manually set.
bool GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
CCoinsView that adds a memory cache for transactions to another CCoinsView.
void AddCoin(const COutPoint &outpoint, Coin &&coin, bool possible_overwrite)
Add a coin.
const Coin & AccessCoin(const COutPoint &output) const
Return a reference to Coin in the cache, or coinEmpty if not found.
Abstract view on the open txout dataset.
An encapsulated private key.
bool IsValid() const
Check whether this private key is valid.
An outpoint - a combination of a transaction hash and an index n into its vout.
An encapsulated public key.
bool IsCompressed() const
Check whether this is a compressed public key.
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid())
Serialized script, used inside transaction inputs and outputs.
bool IsPayToScriptHash() const
bool IsPayToWitnessScriptHash() const
The basic transaction that is broadcasted on the network and contained in blocks.
const Txid & GetHash() const LIFETIMEBOUND
An input of a transaction.
static const uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime/IsFinalTx().
An output of a transaction.
CTxOut out
unspent transaction output
bool IsSpent() const
Either this coin never existed (see e.g.
uint32_t nHeight
at which height this containing transaction was included in the active block chain
Fillable signing provider that keeps keys in an address->secret map.
virtual bool AddCScript(const CScript &redeemScript)
virtual bool AddKey(const CKey &key)
A signature creator for transactions.
bool checkObject(const std::map< std::string, UniValue::VType > &memberTypes) const
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
const std::string & getValStr() const
bool read(std::string_view raw)
bool exists(const std::string &key) const
std::string GetHex() const
static transaction_identifier FromUint256(const uint256 &id)
std::string FormatFullVersion()
std::string LicenseInfo()
Returns licensing information (for -version)
static const unsigned int MAX_BLOCK_WEIGHT
The maximum allowed weight for a block, see BIP 141 (network rule)
static const int WITNESS_SCALE_FACTOR
std::string EncodeHexTx(const CTransaction &tx)
void TxToUniv(const CTransaction &tx, const uint256 &block_hash, UniValue &entry, bool include_hex=true, const CTxUndo *txundo=nullptr, TxVerbosity verbosity=TxVerbosity::SHOW_DETAILS)
CScript ParseScript(const std::string &s)
bool ParseHashStr(const std::string &strHex, uint256 &result)
Parse a hex string into 256 bits.
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode=false)
Create the assembly string representation of a CScript object.
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness=false, bool try_witness=true)
void PrintExceptionContinue(const std::exception *pex, std::string_view thread_name)
#define T(expected, seed, data)
@ SIGHASH_DEFAULT
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
CKey DecodeSecret(const std::string &str)
std::optional< CAmount > ParseMoney(const std::string &money_string)
Parse an amount denoted in full coins.
FILE * fopen(const fs::path &p, const char *mode)
static constexpr decltype(CTransaction::nVersion) TX_MAX_STANDARD_VERSION
static const unsigned int MAX_SCRIPT_ELEMENT_SIZE
static const int MAX_SCRIPT_SIZE
static const int MAX_PUBKEYS_PER_MULTISIG
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
void UpdateInput(CTxIn &input, const SignatureData &data)
SignatureData DataFromTransaction(const CMutableTransaction &tx, unsigned int nIn, const CTxOut &txout)
Extract signature data from a transaction input, and insert it.
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
std::string TrimString(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
std::vector< std::string > SplitString(std::string_view str, char sep)
std::string ToString(const T &t)
Locale-independent version of std::to_string.
std::string_view TrimStringView(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
A mutable version of CTransaction.
std::vector< CTxOut > vout
CScriptWitness scriptWitness
The scriptWitness of an input. Contains complete signatures or the traditional partial signatures for...
static constexpr uint32_t MAX_BIP125_RBF_SEQUENCE
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
bool ParseFixedPoint(std::string_view val, int decimals, int64_t *amount_out)
Parse number as fixed point according to JSON number syntax.
bool ParseInt64(std::string_view str, int64_t *out)
Convert string to signed 64-bit integer with strict parse error feedback.
bool IsHex(std::string_view str)
std::string FormatParagraph(std::string_view in, size_t width, size_t indent)
Format a paragraph of text to a fixed width, adding spaces for indentation to any added line.