Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Basic Taproot signing support for descriptor wallets #2789

Open
wants to merge 2 commits into
base: bush/taproot-derv
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/bench/verify_script.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ static void VerifyScriptBench(benchmark::State& state)
txCredit.vout[0].scriptPubKey,
&txSpend.vin[0].scriptWitness,
flags,
MutableTransactionSignatureChecker(&txSpend, 0, txCredit.vout[0].nValue),
MutableTransactionSignatureChecker(&txSpend, 0, txCredit.vout[0].nValue, MissingDataBehavior::ASSERT_FAIL),
&err);
assert(err == SCRIPT_ERR_OK);
assert(success);
Expand Down
1 change: 1 addition & 0 deletions src/core_read.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,7 @@ int ParseSighashString(const UniValue& sighash)
int hash_type = SIGHASH_ALL;
if (!sighash.isNull()) {
static std::map<std::string, int> map_sighash_values = {
{std::string("DEFAULT"), int(SIGHASH_DEFAULT)},
{std::string("ALL"), int(SIGHASH_ALL)},
{std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},
{std::string("NONE"), int(SIGHASH_NONE)},
Expand Down
3 changes: 2 additions & 1 deletion src/defi-tx.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -503,11 +503,12 @@ static void MutateTxDelOutput(CMutableTransaction& tx, const std::string& strOut
tx.vout.erase(tx.vout.begin() + outIdx);
}

static const unsigned int N_SIGHASH_OPTS = 6;
static const unsigned int N_SIGHASH_OPTS = 7;
static const struct {
const char *flagStr;
int flags;
} sighashOptions[N_SIGHASH_OPTS] = {
{"DEFAULT", SIGHASH_DEFAULT},
{"ALL", SIGHASH_ALL},
{"NONE", SIGHASH_NONE},
{"SINGLE", SIGHASH_SINGLE},
Expand Down
48 changes: 45 additions & 3 deletions src/key.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@

#include <crypto/common.h>
#include <crypto/hmac_sha512.h>
#include <hash.h>
#include <random.h>

#include <secp256k1.h>
#include <secp256k1_extrakeys.h>
#include <secp256k1_recovery.h>
#include <secp256k1_schnorrsig.h>

static secp256k1_context* secp256k1_context_sign = nullptr;

Expand Down Expand Up @@ -226,6 +229,12 @@ bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig, bool gr
assert(ret);
secp256k1_ecdsa_signature_serialize_der(secp256k1_context_sign, vchSig.data(), &nSigLen, &sig);
vchSig.resize(nSigLen);
// Additional verification step to prevent using a potentially corrupted signature
secp256k1_pubkey pk;
ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pk, begin());
assert(ret);
ret = secp256k1_ecdsa_verify(GetVerifyContext(), &sig, hash.begin(), &pk);
assert(ret);
return true;
}

Expand All @@ -248,16 +257,49 @@ bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig)
return false;
vchSig.resize(CPubKey::COMPACT_SIGNATURE_SIZE);
int rec = -1;
secp256k1_ecdsa_recoverable_signature sig;
int ret = secp256k1_ecdsa_sign_recoverable(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, nullptr);
secp256k1_ecdsa_recoverable_signature rsig;
int ret = secp256k1_ecdsa_sign_recoverable(secp256k1_context_sign, &rsig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, nullptr);
assert(ret);
ret = secp256k1_ecdsa_recoverable_signature_serialize_compact(secp256k1_context_sign, &vchSig[1], &rec, &sig);
ret = secp256k1_ecdsa_recoverable_signature_serialize_compact(secp256k1_context_sign, &vchSig[1], &rec, &rsig);
assert(ret);
assert(rec != -1);
vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
// Additional verification step to prevent using a potentially corrupted signature
secp256k1_pubkey epk, rpk;
ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &epk, begin());
assert(ret);
ret = secp256k1_ecdsa_recover(GetVerifyContext(), &rpk, &rsig, hash.begin());
assert(ret);
ret = secp256k1_ec_pubkey_cmp(GetVerifyContext(), &epk, &rpk);
assert(ret == 0);
return true;
}

bool CKey::SignSchnorr(const uint256& hash, Span<unsigned char> sig, const uint256* merkle_root, const uint256& aux) const
{
assert(sig.size() == 64);
secp256k1_keypair keypair;
if (!secp256k1_keypair_create(secp256k1_context_sign, &keypair, begin())) return false;
if (merkle_root) {
secp256k1_xonly_pubkey pubkey;
if (!secp256k1_keypair_xonly_pub(secp256k1_context_sign, &pubkey, nullptr, &keypair)) return false;
unsigned char pubkey_bytes[32];
if (!secp256k1_xonly_pubkey_serialize(secp256k1_context_sign, pubkey_bytes, &pubkey)) return false;
uint256 tweak = XOnlyPubKey(pubkey_bytes).ComputeTapTweakHash(merkle_root->IsNull() ? nullptr : merkle_root);
if (!secp256k1_keypair_xonly_tweak_add(GetVerifyContext(), &keypair, tweak.data())) return false;
}
bool ret = secp256k1_schnorrsig_sign32(secp256k1_context_sign, sig.data(), hash.data(), &keypair, aux.data());
if (ret) {
// Additional verification step to prevent using a potentially corrupted signature
secp256k1_xonly_pubkey pubkey_verify;
ret = secp256k1_keypair_xonly_pub(GetVerifyContext(), &pubkey_verify, nullptr, &keypair);
ret &= secp256k1_schnorrsig_verify(GetVerifyContext(), sig.data(), hash.begin(), 32, &pubkey_verify);
}
if (!ret) memory_cleanse(sig.data(), sig.size());
memory_cleanse(&keypair, sizeof(keypair));
return ret;
}

bool CKey::Load(const CPrivKey &privkey, const CPubKey &vchPubKey, bool fSkipCheck=false) {
if (!ec_privkey_import_der(secp256k1_context_sign, (unsigned char*)begin(), privkey.data(), privkey.size()))
return false;
Expand Down
12 changes: 12 additions & 0 deletions src/key.h
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,18 @@ class CKey
*/
bool SignCompact(const uint256& hash, std::vector<unsigned char>& vchSig) const;

/**
* Create a BIP-340 Schnorr signature, for the xonly-pubkey corresponding to *this,
* optionally tweaked by *merkle_root. Additional nonce entropy is provided through
* aux.
*
* When merkle_root is not nullptr, this results in a signature with a modified key as
* specified in BIP341:
* - If merkle_root->IsNull(): key + H_TapTweak(pubkey)*G
* - Otherwise: key + H_TapTweak(pubkey || *merkle_root)
*/
bool SignSchnorr(const uint256& hash, Span<unsigned char> sig, const uint256* merkle_root, const uint256& aux) const;

//! Derive BIP32 child key.
bool Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const;

Expand Down
6 changes: 4 additions & 2 deletions src/node/psbt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ PSBTAnalysis AnalyzePSBT(PartiallySignedTransaction psbtx)

result.inputs.resize(psbtx.tx->vin.size());

const PrecomputedTransactionData txdata = PrecomputePSBTData(psbtx);

for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
PSBTInput& input = psbtx.inputs[i];
PSBTInputAnalysis& input_analysis = result.inputs[i];
Expand All @@ -46,7 +48,7 @@ PSBTAnalysis AnalyzePSBT(PartiallySignedTransaction psbtx)

// Figure out what is missing
SignatureData outdata;
bool complete = SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, 1, &outdata);
bool complete = SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, &txdata, 1, &outdata);

// Things are missing
if (!complete) {
Expand Down Expand Up @@ -97,7 +99,7 @@ PSBTAnalysis AnalyzePSBT(PartiallySignedTransaction psbtx)
PSBTInput& input = psbtx.inputs[i];
Coin newcoin;

if (!SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, 1, nullptr, true) || !psbtx.GetInputUTXO(newcoin.out, i)) {
if (!SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, nullptr, 1) || !psbtx.GetInputUTXO(newcoin.out, i)) {
success = false;
break;
} else {
Expand Down
15 changes: 13 additions & 2 deletions src/outputtype.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
static const std::string OUTPUT_TYPE_STRING_LEGACY = "legacy";
static const std::string OUTPUT_TYPE_STRING_P2SH_SEGWIT = "p2sh-segwit";
static const std::string OUTPUT_TYPE_STRING_BECH32 = "bech32";
static const std::string OUTPUT_TYPE_STRING_BECH32M = "bech32m";
static const std::string OUTPUT_TYPE_STRING_ERC55 = "erc55";
static const std::string OUTPUT_TYPE_STRING_ETH = "eth";

Expand All @@ -32,6 +33,9 @@ bool ParseOutputType(const std::string& type, OutputType& output_type)
} else if (type == OUTPUT_TYPE_STRING_BECH32) {
output_type = OutputType::BECH32;
return true;
} else if (type == OUTPUT_TYPE_STRING_BECH32M) {
output_type = OutputType::BECH32M;
return true;
} else if (type == OUTPUT_TYPE_STRING_ERC55 || type == OUTPUT_TYPE_STRING_ETH) {
output_type = OutputType::ERC55;
return true;
Expand All @@ -45,6 +49,7 @@ const std::string& FormatOutputType(OutputType type)
case OutputType::LEGACY: return OUTPUT_TYPE_STRING_LEGACY;
case OutputType::P2SH_SEGWIT: return OUTPUT_TYPE_STRING_P2SH_SEGWIT;
case OutputType::BECH32: return OUTPUT_TYPE_STRING_BECH32;
case OutputType::BECH32M: return OUTPUT_TYPE_STRING_BECH32M;
case OutputType::ERC55: return OUTPUT_TYPE_STRING_ERC55;
default: assert(false);
}
Expand Down Expand Up @@ -72,7 +77,11 @@ CTxDestination GetDestinationForKey(const CPubKey& key, OutputType type)
}
return WitnessV16EthHash(pubkeyCopy);
}
default: assert(false);
case OutputType::BECH32M: {
return WitnessV1Taproot(XOnlyPubKey{key});
}
default:
assert(false);
}
}

Expand Down Expand Up @@ -110,6 +119,8 @@ CTxDestination AddAndGetDestinationForScript(FillableSigningProvider& keystore,
return ScriptHash(witprog);
}
}
default: assert(false);
case OutputType::BECH32M: // This function should not be used for BECH32M, so let it assert
default:
assert(false);
}
}
1 change: 1 addition & 0 deletions src/outputtype.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ enum class OutputType {
LEGACY,
P2SH_SEGWIT,
BECH32,
BECH32M,
ERC55,

/**
Expand Down
31 changes: 26 additions & 5 deletions src/psbt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,12 @@ bool PartiallySignedTransaction::AddOutput(const CTxOut& txout, const PSBTOutput

bool PartiallySignedTransaction::GetInputUTXO(CTxOut& utxo, int input_index) const
{
PSBTInput input = inputs[input_index];
const PSBTInput& input = inputs[input_index];
int prevout_index = tx->vin[input_index].prevout.n;
if (input.non_witness_utxo) {
if (input.non_witness_utxo->GetHash() != tx->vin[input_index].prevout.hash) {
return false;
}
utxo = input.non_witness_utxo->vout[prevout_index];
} else if (!input.witness_utxo.IsNull()) {
utxo = input.witness_utxo; /// @todo tokens: extend with correct txout version (and/or tokenid) when implemented
Expand Down Expand Up @@ -236,7 +239,24 @@ void UpdatePSBTOutput(const SigningProvider& provider, PartiallySignedTransactio
psbt_out.FromSignatureData(sigdata);
}

bool SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, int sighash, SignatureData* out_sigdata, bool use_dummy)
PrecomputedTransactionData PrecomputePSBTData(const PartiallySignedTransaction& psbt)
{
const CMutableTransaction& tx = *psbt.tx;
bool have_all_spent_outputs = true;
std::vector<CTxOut> utxos(tx.vin.size());
for (size_t idx = 0; idx < tx.vin.size(); ++idx) {
if (!psbt.GetInputUTXO(utxos[idx], idx)) have_all_spent_outputs = false;
}
PrecomputedTransactionData txdata;
if (have_all_spent_outputs) {
txdata.Init(tx, std::move(utxos), true);
} else {
txdata.Init(tx, {}, true);
}
return txdata;
}

bool SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, const PrecomputedTransactionData* txdata, int sighash, SignatureData* out_sigdata)
{
PSBTInput& input = psbt.inputs.at(index);
const CMutableTransaction& tx = *psbt.tx;
Expand Down Expand Up @@ -278,10 +298,10 @@ bool SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction&

sigdata.witness = false;
bool sig_complete;
if (use_dummy) {
if (txdata == nullptr) {
sig_complete = ProduceSignature(provider, DUMMY_SIGNATURE_CREATOR, utxo.scriptPubKey, sigdata);
} else {
MutableTransactionSignatureCreator creator(&tx, index, utxo.nValue, sighash);
MutableTransactionSignatureCreator creator(&tx, index, utxo.nValue, txdata, sighash);
sig_complete = ProduceSignature(provider, creator, utxo.scriptPubKey, sigdata);
}
// Verify that a witness signature was produced in case one was required.
Expand Down Expand Up @@ -312,8 +332,9 @@ bool FinalizePSBT(PartiallySignedTransaction& psbtx)
// PartiallySignedTransaction did not understand them), this will combine them into a final
// script.
bool complete = true;
const PrecomputedTransactionData txdata = PrecomputePSBTData(psbtx);
for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
complete &= SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, SIGHASH_ALL);
complete &= SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, &txdata, SIGHASH_ALL);
}

return complete;
Expand Down
11 changes: 9 additions & 2 deletions src/psbt.h
Original file line number Diff line number Diff line change
Expand Up @@ -568,11 +568,18 @@ enum class PSBTRole {

std::string PSBTRoleName(PSBTRole role);

/** Compute a PrecomputedTransactionData object from a psbt. */
PrecomputedTransactionData PrecomputePSBTData(const PartiallySignedTransaction& psbt);

/** Checks whether a PSBTInput is already signed. */
bool PSBTInputSigned(const PSBTInput& input);

/** Signs a PSBTInput, verifying that all provided data matches what is being signed. */
bool SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, int sighash = SIGHASH_ALL, SignatureData* out_sigdata = nullptr, bool use_dummy = false);
/** Signs a PSBTInput, verifying that all provided data matches what is being signed.
*
* txdata should be the output of PrecomputePSBTData (which can be shared across
* multiple SignPSBTInput calls). If it is nullptr, a dummy signature will be created.
**/
bool SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, const PrecomputedTransactionData* txdata, int sighash = SIGHASH_ALL, SignatureData* out_sigdata = nullptr);

/** Updates a PSBTOutput with information from provider.
*
Expand Down
4 changes: 4 additions & 0 deletions src/pubkey.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -385,3 +385,7 @@ ECCVerifyHandle::~ECCVerifyHandle()
secp256k1_context_verify = nullptr;
}
}

const secp256k1_context* GetVerifyContext() {
return secp256k1_context_verify;
}
10 changes: 10 additions & 0 deletions src/pubkey.h
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,10 @@ class XOnlyPubKey
* fail. */
bool IsFullyValid() const;

/** Test whether this is the 0 key (the result of default construction). This implies
* !IsFullyValid(). */
bool IsNull() const { return m_keydata.IsNull(); }

/** Construct an x-only pubkey from exactly 32 bytes. */
XOnlyPubKey(Span<const unsigned char> bytes);

Expand Down Expand Up @@ -353,4 +357,10 @@ class ECCVerifyHandle
~ECCVerifyHandle();
};

typedef struct secp256k1_context_struct secp256k1_context;

/** Access to the internal secp256k1 context used for verification. Only intended to be used
* by key.cpp. */
const secp256k1_context* GetVerifyContext();

#endif // DEFI_PUBKEY_H
4 changes: 3 additions & 1 deletion src/rpc/rawtransaction.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -698,6 +698,7 @@ static UniValue signrawtransactionwithkey(const JSONRPCRequest& request)
},
},
{"sighashtype", RPCArg::Type::STR, /* default */ "ALL", "The signature hash type. Must be one of:\n"
" \"DEFAULT\"\n"
" \"ALL\"\n"
" \"NONE\"\n"
" \"SINGLE\"\n"
Expand Down Expand Up @@ -1520,6 +1521,7 @@ UniValue utxoupdatepsbt(const JSONRPCRequest& request)
}

// Fill the inputs
const PrecomputedTransactionData txdata = PrecomputePSBTData(psbtx);
for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
PSBTInput& input = psbtx.inputs.at(i);

Expand All @@ -1536,7 +1538,7 @@ UniValue utxoupdatepsbt(const JSONRPCRequest& request)
// Update script/keypath information using descriptor data.
// Note that SignPSBTInput does a lot more than just constructing ECDSA signatures
// we don't actually care about those here, in fact.
SignPSBTInput(public_provider, psbtx, i, /* sighash_type */ 1);
SignPSBTInput(public_provider, psbtx, i, &txdata, /* sighash_type */ 1);
}

// Update script/keypath information using descriptor data.
Expand Down
27 changes: 25 additions & 2 deletions src/rpc/rawtransaction_util.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -410,10 +410,33 @@ UniValue SignTransaction(CMutableTransaction& mtx, const UniValue& prevTxsUnival
const CScript& prevPubKey = coin->second.out.scriptPubKey;
const CAmount& amount = coin->second.out.nValue;

// Use CTransaction for the constant parts of the
// transaction to avoid rehashing.
const CTransaction txConst(mtx);

PrecomputedTransactionData txdata;
std::vector<CTxOut> spent_outputs;
spent_outputs.resize(mtx.vin.size());
bool have_all_spent_outputs = true;
for (unsigned int i = 0; i < mtx.vin.size(); i++) {
CTxIn& txin = mtx.vin[i];
auto coin = coins.find(txin.prevout);
if (coin == coins.end() || coin->second.IsSpent()) {
have_all_spent_outputs = false;
} else {
spent_outputs[i] = CTxOut(coin->second.out.nValue, coin->second.out.scriptPubKey);
}
}
if (have_all_spent_outputs) {
txdata.Init(txConst, std::move(spent_outputs), true);
} else {
txdata.Init(txConst, {}, true);
}

SignatureData sigdata = DataFromTransaction(mtx, i, coin->second.out);
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mtx.vout.size())) {
ProduceSignature(*keystore, MutableTransactionSignatureCreator(&mtx, i, amount, nHashType), prevPubKey, sigdata);
ProduceSignature(*keystore, MutableTransactionSignatureCreator(&mtx, i, amount, &txdata, nHashType), prevPubKey, sigdata);
}

UpdateInput(txin, sigdata);
Expand All @@ -424,7 +447,7 @@ UniValue SignTransaction(CMutableTransaction& mtx, const UniValue& prevTxsUnival
}

ScriptError serror = SCRIPT_ERR_OK;
if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount), &serror)) {
if (!VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount, txdata, MissingDataBehavior::FAIL), &serror)) {
if (serror == SCRIPT_ERR_INVALID_STACK_OPERATION) {
// Unable to sign input and verification failed (possible attempt to partially sign).
TxInErrorToJSON(txin, vErrors, "Unable to sign input, invalid stack size (possibly missing key)");
Expand Down
Loading