5#include <bitcoin-build-config.h>
63 argsman.AddArg(
"outmultisig=VALUE:REQUIRED:PUBKEYS:PUBKEY1:PUBKEY2:....[:FLAGS]",
"Add Pay To n-of-m Multi-sig output to TX. n = REQUIRED, m = PUBKEYS. "
64 "Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output. "
66 argsman.AddArg(
"outpubkey=VALUE:PUBKEY[:FLAGS]",
"Add pay-to-pubkey output to TX. "
67 "Optionally add the \"W\" flag to produce a pay-to-witness-pubkey-hash output. "
69 argsman.AddArg(
"outscript=VALUE:SCRIPT[:FLAGS]",
"Add raw script output to TX. "
70 "Optionally add the \"W\" flag to produce a pay-to-witness-script-hash output. "
72 argsman.AddArg(
"replaceable(=N)",
"Sets Replace-By-Fee (RBF) opt-in sequence number for input N. "
73 "If N is not provided, the command attempts to opt-in all available inputs for RBF. "
75 argsman.AddArg(
"sign=SIGHASH-FLAGS",
"Add zero or more signatures to transaction. "
76 "This command requires JSON registers:"
77 "prevtxs=JSON object, "
78 "privatekeys=JSON object. "
94 tfm::format(std::cerr,
"Error parsing command line arguments: %s\n", error);
101 }
catch (
const std::exception&
e) {
116 "The bitcoin-tx tool is used for creating and modifying bitcoin transactions.\n\n"
117 "bitcoin-tx can be used with \"<hex-tx> [commands]\" to update a hex-encoded bitcoin transaction, or with \"-create [commands]\" to create a hex-encoded bitcoin transaction.\n"
119 "Usage: bitcoin-tx [options] <hex-tx> [commands]\n"
120 "or: bitcoin-tx [options] -create [commands]\n"
128 tfm::format(std::cerr,
"Error: too few parameters\n");
140 std::string
strErr =
"Cannot parse JSON for key " + key;
141 throw std::runtime_error(
strErr);
151 if ((pos == std::string::npos) ||
154 throw std::runtime_error(
"Register input requires NAME:VALUE");
156 std::string key =
strInput.substr(0, pos);
166 if ((pos == std::string::npos) ||
169 throw std::runtime_error(
"Register load requires NAME:FILENAME");
171 std::string key =
strInput.substr(0, pos);
172 std::string filename =
strInput.substr(pos + 1, std::string::npos);
176 std::string
strErr =
"Cannot open file " + filename;
177 throw std::runtime_error(
strErr);
182 while ((!feof(
f)) && (!
ferror(
f))) {
195 std::string
strErr =
"Error reading file " + filename;
196 throw std::runtime_error(
strErr);
208 throw std::runtime_error(
"invalid TX output value");
216 throw std::runtime_error(
"Invalid TX version requested: '" +
cmdVal +
"'");
225 throw std::runtime_error(
"Invalid TX locktime requested: '" +
cmdVal +
"'");
233 if (
strInIdx !=
"" && (!idx || *idx >= tx.
vin.size())) {
234 throw std::runtime_error(
"Invalid TX input index '" +
strInIdx +
"'");
253 if (!
parsed.has_value()) {
254 throw std::runtime_error(err +
" '" +
int_str +
"'");
265 throw std::runtime_error(
"TX input missing separator");
270 throw std::runtime_error(
"invalid TX input txid");
279 if (!vout || *vout >
maxVout) {
280 throw std::runtime_error(
"invalid TX input vout '" +
strVout +
"'");
300 throw std::runtime_error(
"TX output missing or too many separators");
309 throw std::runtime_error(
"invalid TX output address");
314 CTxOut txout(value, scriptPubKey);
315 tx.
vout.push_back(txout);
324 throw std::runtime_error(
"TX output missing or too many separators");
332 throw std::runtime_error(
"invalid TX output pubkey");
346 throw std::runtime_error(
"Uncompressed pubkeys are not useable for SegWit outputs");
357 CTxOut txout(value, scriptPubKey);
358 tx.
vout.push_back(txout);
368 throw std::runtime_error(
"Not enough multisig parameters");
381 throw std::runtime_error(
"incorrect number of multisig pubkeys");
384 throw std::runtime_error(
"multisig parameter mismatch. Required " \
388 std::vector<CPubKey> pubkeys;
389 for(
int pos = 1; pos <=
int(
numkeys); pos++) {
392 throw std::runtime_error(
"invalid TX output pubkey");
393 pubkeys.push_back(pubkey);
406 throw std::runtime_error(
"Too many parameters");
412 for (
const CPubKey& pubkey : pubkeys) {
413 if (!pubkey.IsCompressed()) {
414 throw std::runtime_error(
"Uncompressed pubkeys are not useable for SegWit outputs");
430 CTxOut txout(value, scriptPubKey);
431 tx.
vout.push_back(txout);
442 throw std::runtime_error(
"TX output value not specified");
444 if (pos == std::string::npos) {
456 throw std::runtime_error(
"invalid TX output data");
461 tx.
vout.push_back(txout);
469 throw std::runtime_error(
"TX output missing separator");
504 CTxOut txout(value, scriptPubKey);
505 tx.
vout.push_back(txout);
511 if (!idx || idx >= tx.
vin.size()) {
512 throw std::runtime_error(
"Invalid TX input index '" +
strInIdx +
"'");
514 tx.
vin.erase(tx.
vin.begin() + *idx);
520 if (!idx || idx >= tx.
vout.size()) {
521 throw std::runtime_error(
"Invalid TX output index '" +
strOutIdx +
"'");
523 tx.
vout.erase(tx.
vout.begin() + *idx);
557 throw std::runtime_error(
"Amount is not a number or string");
560 throw std::runtime_error(
"Invalid amount");
562 throw std::runtime_error(
"Amount out of range");
572 throw std::runtime_error(
strName +
" must be hexadecimal string (not '" +
strHex +
"')");
582 throw std::runtime_error(
"unknown sighash flag/sign option");
592 throw std::runtime_error(
"privatekeys register variable must be set.");
598 throw std::runtime_error(
"privatekey not a std::string");
601 throw std::runtime_error(
"privatekey not valid");
608 throw std::runtime_error(
"prevtxs register variable must be set.");
614 throw std::runtime_error(
"expected prevtxs internal object");
616 std::map<std::string, UniValue::VType> types = {
621 if (!
prevOut.checkObject(types))
622 throw std::runtime_error(
"prevtxs internal object typecheck fail");
626 throw std::runtime_error(
"txid must be hexadecimal string (not '" +
prevOut[
"txid"].get_str() +
"')");
631 throw std::runtime_error(
"vout cannot be negative");
638 const Coin& coin =
view.AccessCoin(out);
640 std::string err(
"Previous output scriptPubKey mismatch:\n");
643 throw std::runtime_error(err);
648 if (
prevOut.exists(
"amount")) {
658 prevOut.exists(
"redeemScript")) {
672 for (
unsigned int i = 0; i <
mergedTx.vin.size(); i++) {
683 if (!fHashSingle || (i <
mergedTx.vout.size()))
699 std::unique_ptr<ECC_Context>
ecc;
703 else if (
command ==
"locktime")
705 else if (
command ==
"replaceable") {
718 else if (
command ==
"outpubkey") {
721 }
else if (
command ==
"outmultisig") {
724 }
else if (
command ==
"outscript")
741 throw std::runtime_error(
"unknown command");
782 while (!feof(
stdin)) {
785 if (
bread <
sizeof(buf))
790 throw std::runtime_error(
"error reading stdin");
792 return TrimString(
ret);
813 throw std::runtime_error(
"too few parameters");
821 throw std::runtime_error(
"invalid transaction encoding");
829 std::string key, value;
831 if (
eqpos == std::string::npos)
843 catch (
const std::exception&
e) {
844 strPrint = std::string(
"error: ") +
e.what();
867 catch (
const std::exception&
e) {
879 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, PayToAnchor, 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 std::vector< unsigned char > ParseHexUV(const UniValue &v, const std::string &strName)
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)
static T TrimAndParse(const std::string &int_str, const std::string &err)
static void MutateTxAddOutPubKey(CMutableTransaction &tx, const std::string &strInput)
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[])
const TranslateFn G_TRANSLATION_FUN
Translate string to current locale using Qt.
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 GetBoolArg(const std::string &strArg, bool fDefault) const
Return boolean argument or default value.
CCoinsView that adds a memory cache for transactions to another CCoinsView.
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.
RAII class initializing and deinitializing global state for elliptic curve support.
Fillable signing provider that keeps keys in an address->secret map.
A signature creator for transactions.
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
const std::string & getValStr() const
bool read(std::string_view raw)
std::string GetHex() const
static std::optional< transaction_identifier > FromHex(std::string_view hex)
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)
CScript ParseScript(const std::string &s)
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness, bool try_witness)
void TxToUniv(const CTransaction &tx, const uint256 &block_hash, UniValue &entry, bool include_hex, const CTxUndo *txundo, TxVerbosity verbosity, std::function< bool(const CTxOut &)> is_change_func)
std::string ScriptToAsmStr(const CScript &script, const bool fAttemptSighashDecode)
Create the assembly string representation of a CScript object.
void PrintExceptionContinue(const std::exception *pex, std::string_view thread_name)
#define T(expected, seed, data)
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
@ 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)
std::vector< std::string > SplitString(std::string_view str, char sep)
std::string_view TrimStringView(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
std::string ToString(const T &t)
Locale-independent version of std::to_string.
std::string TrimString(std::string_view str, std::string_view pattern=" \f\n\r\t\v")
static constexpr decltype(CTransaction::version) 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.
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...
std::function< std::string(const char *)> TranslateFn
Translate a message to the native language of the user.
static constexpr uint32_t MAX_BIP125_RBF_SEQUENCE
bool ParseFixedPoint(std::string_view val, int decimals, int64_t *amount_out)
Parse number as fixed point according to JSON number syntax.
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.
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.