5 #if defined(HAVE_CONFIG_H) 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. " 93 }
catch (
const std::exception& e) {
108 "Usage: bitcoin-tx [options] <hex-tx> [commands] Update hex-encoded bitcoin transaction\n" 109 "or: bitcoin-tx [options] -create [commands] Create hex-encoded bitcoin transaction\n" 117 tfm::format(std::cerr,
"Error: too few parameters\n");
128 if (!val.
read(rawJson)) {
129 std::string strErr =
"Cannot parse JSON for key " + key;
130 throw std::runtime_error(strErr);
139 size_t pos = strInput.find(
':');
140 if ((pos == std::string::npos) ||
142 (pos == (strInput.size() - 1)))
143 throw std::runtime_error(
"Register input requires NAME:VALUE");
145 std::string key = strInput.substr(0, pos);
146 std::string valStr = strInput.substr(pos + 1, std::string::npos);
154 size_t pos = strInput.find(
':');
155 if ((pos == std::string::npos) ||
157 (pos == (strInput.size() - 1)))
158 throw std::runtime_error(
"Register load requires NAME:FILENAME");
160 std::string key = strInput.substr(0, pos);
161 std::string filename = strInput.substr(pos + 1, std::string::npos);
165 std::string strErr =
"Cannot open file " + filename;
166 throw std::runtime_error(strErr);
171 while ((!feof(f)) && (!ferror(f))) {
173 int bread = fread(buf, 1,
sizeof(buf), f);
177 valStr.insert(valStr.size(), buf, bread);
180 int error = ferror(f);
184 std::string strErr =
"Error reading file " + filename;
185 throw std::runtime_error(strErr);
194 if (std::optional<CAmount> parsed =
ParseMoney(strValue)) {
195 return parsed.value();
197 throw std::runtime_error(
"invalid TX output value");
205 throw std::runtime_error(
"Invalid TX version requested: '" + cmdVal +
"'");
214 if (!
ParseInt64(cmdVal, &newLocktime) || newLocktime < 0LL || newLocktime > 0xffffffffLL)
215 throw std::runtime_error(
"Invalid TX locktime requested: '" + cmdVal +
"'");
217 tx.
nLockTime = (
unsigned int) newLocktime;
224 if (!
ParseInt64(strInIdx, &inIdx) || inIdx < 0 || inIdx >= static_cast<int64_t>(tx.
vin.size())) {
225 throw std::runtime_error(
"Invalid TX input index '" + strInIdx +
"'");
231 if (strInIdx ==
"" || cnt == inIdx) {
240 template <
typename T>
244 if (!parsed.has_value()) {
245 throw std::runtime_error(err +
" '" + int_str +
"'");
247 return parsed.value();
252 std::vector<std::string> vStrInputParts =
SplitString(strInput,
':');
255 if (vStrInputParts.size()<2)
256 throw std::runtime_error(
"TX input missing separator");
261 throw std::runtime_error(
"invalid TX input txid");
264 static const unsigned int minTxOutSz = 9;
268 const std::string& strVout = vStrInputParts[1];
270 if (!
ParseInt64(strVout, &vout) || vout < 0 || vout >
static_cast<int64_t
>(maxVout))
271 throw std::runtime_error(
"invalid TX input vout '" + strVout +
"'");
275 if (vStrInputParts.size() > 2) {
276 nSequenceIn = TrimAndParse<uint32_t>(vStrInputParts.at(2),
"invalid TX sequence id");
281 tx.
vin.push_back(txin);
287 std::vector<std::string> vStrInputParts =
SplitString(strInput,
':');
289 if (vStrInputParts.size() != 2)
290 throw std::runtime_error(
"TX output missing or too many separators");
296 std::string strAddr = vStrInputParts[1];
299 throw std::runtime_error(
"invalid TX output address");
304 CTxOut txout(value, scriptPubKey);
305 tx.
vout.push_back(txout);
311 std::vector<std::string> vStrInputParts =
SplitString(strInput,
':');
313 if (vStrInputParts.size() < 2 || vStrInputParts.size() > 3)
314 throw std::runtime_error(
"TX output missing or too many separators");
322 throw std::runtime_error(
"invalid TX output pubkey");
326 bool bSegWit =
false;
327 bool bScriptHash =
false;
328 if (vStrInputParts.size() == 3) {
329 std::string
flags = vStrInputParts[2];
330 bSegWit = (
flags.find(
'W') != std::string::npos);
331 bScriptHash = (
flags.find(
'S') != std::string::npos);
336 throw std::runtime_error(
"Uncompressed pubkeys are not useable for SegWit outputs");
347 CTxOut txout(value, scriptPubKey);
348 tx.
vout.push_back(txout);
354 std::vector<std::string> vStrInputParts =
SplitString(strInput,
':');
357 if (vStrInputParts.size()<3)
358 throw std::runtime_error(
"Not enough multisig parameters");
364 const uint32_t required{TrimAndParse<uint32_t>(vStrInputParts.at(1),
"invalid multisig required number")};
367 const uint32_t numkeys{TrimAndParse<uint32_t>(vStrInputParts.at(2),
"invalid multisig total number")};
370 if (vStrInputParts.size() < numkeys + 3)
371 throw std::runtime_error(
"incorrect number of multisig pubkeys");
374 throw std::runtime_error(
"multisig parameter mismatch. Required " \
378 std::vector<CPubKey> pubkeys;
379 for(
int pos = 1; pos <= int(numkeys); pos++) {
382 throw std::runtime_error(
"invalid TX output pubkey");
383 pubkeys.push_back(pubkey);
387 bool bSegWit =
false;
388 bool bScriptHash =
false;
389 if (vStrInputParts.size() == numkeys + 4) {
390 std::string
flags = vStrInputParts.back();
391 bSegWit = (
flags.find(
'W') != std::string::npos);
392 bScriptHash = (
flags.find(
'S') != std::string::npos);
394 else if (vStrInputParts.size() > numkeys + 4) {
396 throw std::runtime_error(
"Too many parameters");
402 for (
const CPubKey& pubkey : pubkeys) {
403 if (!pubkey.IsCompressed()) {
404 throw std::runtime_error(
"Uncompressed pubkeys are not useable for SegWit outputs");
420 CTxOut txout(value, scriptPubKey);
421 tx.
vout.push_back(txout);
429 size_t pos = strInput.find(
':');
432 throw std::runtime_error(
"TX output value not specified");
434 if (pos == std::string::npos) {
443 const std::string strData{strInput.substr(pos, std::string::npos)};
446 throw std::runtime_error(
"invalid TX output data");
448 std::vector<unsigned char> data =
ParseHex(strData);
451 tx.
vout.push_back(txout);
457 std::vector<std::string> vStrInputParts =
SplitString(strInput,
':');
458 if (vStrInputParts.size() < 2)
459 throw std::runtime_error(
"TX output missing separator");
465 std::string strScript = vStrInputParts[1];
469 bool bSegWit =
false;
470 bool bScriptHash =
false;
471 if (vStrInputParts.size() == 3) {
472 std::string
flags = vStrInputParts.back();
473 bSegWit = (
flags.find(
'W') != std::string::npos);
474 bScriptHash = (
flags.find(
'S') != std::string::npos);
494 CTxOut txout(value, scriptPubKey);
495 tx.
vout.push_back(txout);
502 if (!
ParseInt64(strInIdx, &inIdx) || inIdx < 0 || inIdx >= static_cast<int64_t>(tx.
vin.size())) {
503 throw std::runtime_error(
"Invalid TX input index '" + strInIdx +
"'");
507 tx.
vin.erase(tx.
vin.begin() + inIdx);
514 if (!
ParseInt64(strOutIdx, &outIdx) || outIdx < 0 || outIdx >= static_cast<int64_t>(tx.
vout.size())) {
515 throw std::runtime_error(
"Invalid TX output index '" + strOutIdx +
"'");
519 tx.
vout.erase(tx.
vout.begin() + outIdx);
523 static const struct {
553 throw std::runtime_error(
"Amount is not a number or string");
556 throw std::runtime_error(
"Invalid amount");
558 throw std::runtime_error(
"Amount out of range");
568 throw std::runtime_error(
"unknown sighash flag/sign option");
578 throw std::runtime_error(
"privatekeys register variable must be set.");
582 for (
unsigned int kidx = 0; kidx < keysObj.
size(); kidx++) {
583 if (!keysObj[kidx].isStr())
584 throw std::runtime_error(
"privatekey not a std::string");
587 throw std::runtime_error(
"privatekey not valid");
594 throw std::runtime_error(
"prevtxs register variable must be set.");
597 for (
unsigned int previdx = 0; previdx < prevtxsObj.
size(); previdx++) {
598 const UniValue& prevOut = prevtxsObj[previdx];
600 throw std::runtime_error(
"expected prevtxs internal object");
602 std::map<std::string, UniValue::VType> types = {
608 throw std::runtime_error(
"prevtxs internal object typecheck fail");
612 throw std::runtime_error(
"txid must be hexadecimal string (not '" + prevOut[
"txid"].get_str() +
"')");
615 const int nOut = prevOut[
"vout"].
getInt<
int>();
617 throw std::runtime_error(
"vout cannot be negative");
620 std::vector<unsigned char> pkData(
ParseHexUV(prevOut[
"scriptPubKey"],
"scriptPubKey"));
621 CScript scriptPubKey(pkData.begin(), pkData.end());
626 std::string err(
"Previous output scriptPubKey mismatch:\n");
629 throw std::runtime_error(err);
634 if (prevOut.
exists(
"amount")) {
638 view.
AddCoin(out, std::move(newcoin),
true);
643 if ((scriptPubKey.IsPayToScriptHash() || scriptPubKey.IsPayToWitnessScriptHash()) &&
644 prevOut.
exists(
"redeemScript")) {
645 UniValue v = prevOut[
"redeemScript"];
646 std::vector<unsigned char> rsData(
ParseHexUV(v,
"redeemScript"));
647 CScript redeemScript(rsData.begin(), rsData.end());
658 for (
unsigned int i = 0; i < mergedTx.vin.size(); i++) {
659 CTxIn& txin = mergedTx.vin[i];
669 if (!fHashSingle || (i < mergedTx.vout.size()))
673 throw std::runtime_error(
strprintf(
"Missing amount for CTxOut with scriptPubKey=%s",
HexStr(prevPubKey)));
696 const std::string& commandVal)
698 std::unique_ptr<Secp256k1Init> ecc;
702 else if (
command ==
"locktime")
704 else if (
command ==
"replaceable") {
717 else if (
command ==
"outpubkey") {
720 }
else if (
command ==
"outmultisig") {
723 }
else if (
command ==
"outscript")
740 throw std::runtime_error(
"unknown command");
748 std::string jsonOutput = entry.
write(4);
781 while (!feof(stdin)) {
782 size_t bread = fread(buf, 1,
sizeof(buf), stdin);
783 ret.append(buf, bread);
784 if (bread <
sizeof(buf))
789 throw std::runtime_error(
"error reading stdin");
812 throw std::runtime_error(
"too few parameters");
815 std::string strHexTx(argv[1]);
820 throw std::runtime_error(
"invalid transaction encoding");
826 for (
int i = startArg; i < argc; i++) {
827 std::string arg = argv[i];
828 std::string key, value;
829 size_t eqpos = arg.find(
'=');
830 if (eqpos == std::string::npos)
833 key = arg.substr(0, eqpos);
834 value = arg.substr(eqpos + 1);
842 catch (
const std::exception& e) {
843 strPrint = std::string(
"error: ") + e.what();
866 catch (
const std::exception& e) {
878 catch (
const std::exception& e) {
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
bool IsSpent() const
Either this coin never existed (see e.g.
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 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.
static const int MAX_SCRIPT_SIZE
bool read(const char *raw, size_t len)
static void MutateTxVersion(CMutableTransaction &tx, const std::string &cmdVal)
bool HelpRequested(const ArgsManager &args)
static const uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime/IsFinalTx().
virtual bool AddCScript(const CScript &redeemScript)
bool MoneyRange(const CAmount &nValue)
bool IsHex(std::string_view str)
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)
std::string_view TrimStringView(std::string_view str, std::string_view pattern=" \\\)
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.
std::string LicenseInfo()
Returns licensing information (for -version)
A signature creator for transactions.
static void MutateTxLocktime(CMutableTransaction &tx, const std::string &cmdVal)
static decltype(CTransaction::nVersion) constexpr TX_MAX_STANDARD_VERSION
static void RegisterSetJson(const std::string &key, const std::string &rawJson)
std::vector< std::string > SplitString(std::string_view str, char sep)
static CAmount ExtractAndValidateValue(const std::string &strValue)
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
static void OutputTxHex(const CTransaction &tx)
const std::string & getValStr() const
static const int MAX_PUBKEYS_PER_MULTISIG
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.
std::vector< Byte > ParseHex(std::string_view str)
Parse the hex string into bytes (uint8_t or std::byte).
static constexpr uint32_t MAX_BIP125_RBF_SEQUENCE
void SetupHelpOptions(ArgsManager &args)
Add help options to the args manager.
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()) ...
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
static void SetupBitcoinTxArgs(ArgsManager &argsman)
Abstract view on the open txout dataset.
An input of a transaction.
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.
void AddArg(const std::string &name, const std::string &help, unsigned int flags, const OptionsCategory &cat)
Add argument.
std::optional< CAmount > ParseMoney(const std::string &money_string)
Parse an amount denoted in full coins.
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
void PrintExceptionContinue(const std::exception *pex, std::string_view thread_name)
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
An output of a transaction.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
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...
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.
CScriptWitness scriptWitness
The scriptWitness of an input. Contains complete signatures or the traditional partial signatures for...
std::string FormatFullVersion()
bool ParseFixedPoint(std::string_view val, int decimals, int64_t *amount_out)
Parse number as fixed point according to JSON number syntax.
static bool findSighashFlags(int &flags, const std::string &flagStr)
bool checkObject(const std::map< std::string, UniValue::VType > &memberTypes) const
static void OutputTx(const CTransaction &tx)
static std::string readStdin()
bool ParseInt64(std::string_view str, int64_t *out)
Convert string to signed 64-bit integer with strict parse error feedback.
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 const unsigned int MAX_SCRIPT_ELEMENT_SIZE
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)
static constexpr CAmount MAX_MONEY
No amount larger than this (in satoshi) is valid.
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.
static T TrimAndParse(const std::string &int_str, const std::string &err)
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]
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
static const int CONTINUE_EXECUTION
CScript ParseScript(const std::string &s)
std::string TrimString(std::string_view str, std::string_view pattern=" \\\)
bool error(const char *fmt, const Args &... args)
static void MutateTxDelOutput(CMutableTransaction &tx, const std::string &strOutIdx)
void TxToUniv(const CTransaction &tx, const uint256 &block_hash, UniValue &entry, bool include_hex=true, int serialize_flags=0, const CTxUndo *txundo=nullptr, TxVerbosity verbosity=TxVerbosity::SHOW_DETAILS)
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)