diff --git a/ci/test/00_setup_env.sh b/ci/test/00_setup_env.sh index a586dbffb8d1..54a938a78613 100755 --- a/ci/test/00_setup_env.sh +++ b/ci/test/00_setup_env.sh @@ -51,7 +51,7 @@ export RUN_STDLIB_PATH_CHECK=${RUN_STDLIB_PATH_CHECK:-false} # By how much to scale the test_runner timeouts (option --timeout-factor). # This is needed because some ci machines have slow CPU or disk, so sanitizers # might be slow or a reindex might be waiting on disk IO. -export TEST_RUNNER_TIMEOUT_FACTOR=${TEST_RUNNER_TIMEOUT_FACTOR:-4} +export TEST_RUNNER_TIMEOUT_FACTOR=${TEST_RUNNER_TIMEOUT_FACTOR:-40} export RUN_FUZZ_TESTS=${RUN_FUZZ_TESTS:-false} # Randomize test order. diff --git a/configure.ac b/configure.ac index 814b70ffdeea..efdc42103dd8 100644 --- a/configure.ac +++ b/configure.ac @@ -2127,7 +2127,7 @@ CPPFLAGS="$CPPFLAGS_TEMP" dnl The ECDH module is required by the wallet's Platform key provider dnl (DashPay contact request encryption, wallet/platformkeys.cpp). -ac_configure_args="${ac_configure_args} --disable-shared --with-pic --enable-benchmark=no --enable-module-recovery --enable-module-ecdh --disable-openssl-tests" +ac_configure_args="${ac_configure_args} --disable-shared --with-pic --enable-benchmark=no --enable-module-recovery --enable-module-ecdh --disable-openssl-tests --enable-module-schnorrsig" AC_CONFIG_SUBDIRS([src/secp256k1]) AC_OUTPUT diff --git a/doc/bips.md b/doc/bips.md index 88ad35004cb8..b20e32da8fb0 100644 --- a/doc/bips.md +++ b/doc/bips.md @@ -41,6 +41,7 @@ Versions and PRs are relevant to Bitcoin's core if not mentioned other. * [`BIP 159`](https://github.com/bitcoin/bips/blob/master/bip-0159.mediawiki): The `NODE_NETWORK_LIMITED` service bit is signalled as of **v0.16.0** ([PR 11740](https://github.com/bitcoin/bitcoin/pull/11740)), and such nodes are connected to as of **v0.17.0** ([PR 10387](https://github.com/bitcoin/bitcoin/pull/10387)). * [`BIP 174`](https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki): RPCs to operate on Partially Signed Bitcoin Transactions (PSBT) are present as of **v18.0** ([PR 13557](https://github.com/bitcoin/bitcoin/pull/13557)). * [`BIP 324`](https://github.com/bitcoin/bips/blob/master/bip-0324.mediawiki): The v2 transport protocol specified by BIP324 and the associated `NODE_P2P_V2` service bit are supported as of **v22.0**, but off by default ([PR 28331](https://github.com/bitcoin/bitcoin/pull/28331)). On by default as of **v22.1** ([PR 29347](https://github.com/bitcoin/bitcoin/pull/29347)). +* [`BIP 340`](https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki) [`341`](https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki) [`342`](https://github.com/bitcoin/bips/blob/master/bip-0342.mediawiki): Validation rules for Taproot (including Schnorr signatures and Tapscript leaves) are implemented as of **v0.21.0** ([PR 19953](https://github.com/bitcoin/bitcoin/pull/19953)), without mainnet activation. * [`BIP 380`](https://github.com/bitcoin/bips/blob/master/bip-0380.mediawiki) [`381`](https://github.com/bitcoin/bips/blob/master/bip-0381.mediawiki) [`383`](https://github.com/bitcoin/bips/blob/master/bip-0383.mediawiki) diff --git a/src/Makefile.test.include b/src/Makefile.test.include index db6502775cf5..65c69845f610 100644 --- a/src/Makefile.test.include +++ b/src/Makefile.test.include @@ -390,6 +390,7 @@ test_fuzz_fuzz_SOURCES = \ test/fuzz/script_flags.cpp \ test/fuzz/script_format.cpp \ test/fuzz/script_interpreter.cpp \ + test/fuzz/script_assets_test_minimizer.cpp \ test/fuzz/script_ops.cpp \ test/fuzz/script_sigcache.cpp \ test/fuzz/script_sign.cpp \ diff --git a/src/bench/ccoins_caching.cpp b/src/bench/ccoins_caching.cpp index 3e029feb2030..738048a27622 100644 --- a/src/bench/ccoins_caching.cpp +++ b/src/bench/ccoins_caching.cpp @@ -44,7 +44,7 @@ static void CCoinsCaching(benchmark::Bench& bench) // Benchmark. const CTransaction tx_1(t1); bench.run([&] { - bool success = AreInputsStandard(tx_1, coins); + bool success = AreInputsStandard(tx_1, coins, false); assert(success); }); ECC_Stop(); diff --git a/src/consensus/params.h b/src/consensus/params.h index 59384abc67da..ea72d0993692 100644 --- a/src/consensus/params.h +++ b/src/consensus/params.h @@ -44,6 +44,7 @@ enum DeploymentPos : uint16_t { DEPLOYMENT_TESTDUMMY, DEPLOYMENT_V24, // Deployment of doubling withdrawal limit, extended addresses DEPLOYMENT_EVO_SHARES, // Deployment of EvoNode shared collateral and multiple owner payouts + DEPLOYMENT_TAPROOT, // Deployment of Taproot (BIP 340, 341, 342) outputs and tapscript // NOTE: Also add new deployments to VersionBitsDeploymentInfo in deploymentinfo.cpp MAX_VERSION_BITS_DEPLOYMENTS }; diff --git a/src/deploymentinfo.cpp b/src/deploymentinfo.cpp index d5646f3840b8..f552284b469c 100644 --- a/src/deploymentinfo.cpp +++ b/src/deploymentinfo.cpp @@ -21,6 +21,10 @@ const struct VBDeploymentInfo VersionBitsDeploymentInfo[Consensus::MAX_VERSION_B /*.name =*/"evo_shares", /*.gbt_force =*/true, }, + { + /*.name =*/"taproot", + /*.gbt_force =*/true, + }, }; std::string DeploymentName(Consensus::BuriedDeployment dep) diff --git a/src/kernel/chainparams.cpp b/src/kernel/chainparams.cpp index 6d0f643ad20f..41b5915db55c 100644 --- a/src/kernel/chainparams.cpp +++ b/src/kernel/chainparams.cpp @@ -239,6 +239,15 @@ class CMainParams : public CChainParams { consensus.vDeployments[Consensus::DEPLOYMENT_EVO_SHARES].nFalloffCoeff = 5; // this corresponds to 10 periods consensus.vDeployments[Consensus::DEPLOYMENT_EVO_SHARES].useEHF = true; + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].bit = 15; + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nStartTime = Consensus::BIP9Deployment::NEVER_ACTIVE; + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT; + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nWindowSize = 4032; + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nThresholdStart = 3226; // 80% of 4032 + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nThresholdMin = 2420; // 60% of 4032 + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nFalloffCoeff = 5; // this corresponds to 10 periods + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].useEHF = true; + consensus.nMinimumChainWork = uint256S("0x00000000000000000000000000000000000000000000c15981a81af44a6abe1a"); // 2563000 consensus.defaultAssumeValid = uint256S("0x000000000000000346a1804da4832b0b69dd9a7f96b14c7cb54585a9ac6ae98f"); // 2563000 @@ -450,6 +459,15 @@ class CTestNetParams : public CChainParams { consensus.vDeployments[Consensus::DEPLOYMENT_EVO_SHARES].nFalloffCoeff = 5; // this corresponds to 10 periods consensus.vDeployments[Consensus::DEPLOYMENT_EVO_SHARES].useEHF = true; + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].bit = 15; + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nStartTime = Consensus::BIP9Deployment::NEVER_ACTIVE; + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT; + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nWindowSize = 100; + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nThresholdStart = 80; // 80% of 100 + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nThresholdMin = 60; // 60% of 100 + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nFalloffCoeff = 5; // this corresponds to 10 periods + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].useEHF = true; + consensus.nMinimumChainWork = uint256S("0x00000000000000000000000000000000000000000000000003ed573a939487fc"); // 1550000 consensus.defaultAssumeValid = uint256S("0x000000116cd3c11d44c88cbc0a26804bd277a5d790f684ec3a8aaa820690318c"); // 1550000 @@ -634,6 +652,15 @@ class CDevNetParams : public CChainParams { consensus.vDeployments[Consensus::DEPLOYMENT_EVO_SHARES].nFalloffCoeff = 5; // this corresponds to 10 periods consensus.vDeployments[Consensus::DEPLOYMENT_EVO_SHARES].useEHF = true; + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].bit = 15; + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nStartTime = 1751328000; // July 1, 2025 + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT; + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nWindowSize = 120; + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nThresholdStart = 96; // 80% of 120 + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nThresholdMin = 72; // 60% of 120 + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nFalloffCoeff = 5; // this corresponds to 10 periods + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].useEHF = true; + consensus.nMinimumChainWork = uint256{}; consensus.defaultAssumeValid = uint256{}; @@ -930,6 +957,15 @@ class CRegTestParams : public CChainParams { consensus.vDeployments[Consensus::DEPLOYMENT_EVO_SHARES].nFalloffCoeff = 5; // this corresponds to 10 periods consensus.vDeployments[Consensus::DEPLOYMENT_EVO_SHARES].useEHF = true; + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].bit = 15; + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nStartTime = 0; + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT; + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nWindowSize = 250; + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nThresholdStart = 250 / 5 * 4; // 80% of window size + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nThresholdMin = 250 / 5 * 3; // 60% of window size + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].nFalloffCoeff = 5; // this corresponds to 10 periods + consensus.vDeployments[Consensus::DEPLOYMENT_TAPROOT].useEHF = true; + consensus.nMinimumChainWork = uint256{}; consensus.defaultAssumeValid = uint256{}; diff --git a/src/policy/policy.cpp b/src/policy/policy.cpp index b045334e3451..bd5dda31dd3d 100644 --- a/src/policy/policy.cpp +++ b/src/policy/policy.cpp @@ -73,7 +73,7 @@ bool IsStandard(const CScript& scriptPubKey, const std::optional& max_ return true; } -bool IsStandardTx(const CTransaction& tx, const std::optional& max_datacarrier_bytes, bool permit_bare_multisig, const CFeeRate& dust_relay_fee, std::string& reason) +bool IsStandardTx(const CTransaction& tx, const std::optional& max_datacarrier_bytes, bool permit_bare_multisig, const CFeeRate& dust_relay_fee, bool taproot_active, std::string& reason) { if (tx.nVersion > TX_MAX_STANDARD_VERSION || tx.nVersion < 1) { reason = "version"; @@ -130,6 +130,10 @@ bool IsStandardTx(const CTransaction& tx, const std::optional& max_dat reason = "scriptpubkey"; return false; } + if (whichType == TxoutType::TAPROOT && !taproot_active) { + reason = "scriptpubkey"; + return false; + } if (whichType == TxoutType::NULL_DATA) nDataOut++; @@ -167,7 +171,7 @@ bool IsStandardTx(const CTransaction& tx, const std::optional& max_dat * expensive-to-check-upon-redemption script like: * DUP CHECKSIG DROP ... repeated 100 times... OP_1 */ -bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs) +bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, bool taproot_active) { if (tx.IsCoinBase()) return true; // Coinbases don't use vin normally @@ -198,6 +202,49 @@ bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs) if (subscript.GetSigOpCount(true) > MAX_P2SH_SIGOPS) { return false; } + } else if (whichType == TxoutType::TAPROOT) { + // Don't allow Taproot spends unless Taproot is active. + if (!taproot_active) return false; + } + } + + return true; +} + +bool IsTaprootStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs) +{ + if (tx.IsCoinBase()) + return true; // Coinbases are skipped + + for (unsigned int i = 0; i < tx.vin.size(); i++) + { + const CTxOut& prev = mapInputs.AccessCoin(tx.vin[i].prevout).out; + if (!prev.scriptPubKey.IsPayToTaproot()) continue; + + std::vector> stack_items; + if (!ParseTaprootStack(tx.vin[i].scriptSig, stack_items)) return false; + Span> stack{stack_items}; + if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) { + // Annexes are nonstandard as long as no semantics are defined for them. + return false; + } + if (stack.size() >= 2) { + // Script path spend (2 or more stack elements after removing optional annex) + const auto& control_block = SpanPopBack(stack); + SpanPopBack(stack); // Ignore script + if (control_block.empty()) return false; // Empty control block is invalid + if ((control_block[0] & TAPROOT_LEAF_MASK) == TAPROOT_LEAF_TAPSCRIPT) { + // Leaf version 0xc0 (aka Tapscript, see BIP 342) + for (const auto& item : stack) { + if (item.size() > MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE) return false; + } + } + } else if (stack.size() == 1) { + // Key path spend (1 stack element after removing optional annex) + // (no policy rules apply) + } else { + // 0 stack elements; this is already invalid by consensus rules + return false; } } diff --git a/src/policy/policy.h b/src/policy/policy.h index 9e4c62ab133a..0c85bc0f359e 100644 --- a/src/policy/policy.h +++ b/src/policy/policy.h @@ -39,6 +39,8 @@ static constexpr unsigned int DEFAULT_BYTES_PER_SIGOP{20}; static constexpr bool DEFAULT_PERMIT_BAREMULTISIG{true}; /** The maximum size of a standard ScriptSig */ static constexpr unsigned int MAX_STANDARD_SCRIPTSIG_SIZE{1650}; +/** The maximum size of each witness stack item in a standard BIP 342 script (Taproot, leaf version 0xc0) */ +static const unsigned int MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE{80}; /** Min feerate for defining dust. * Changing the dust limit changes which transactions are * standard and should be done with care and ideally rarely. It makes sense to @@ -74,7 +76,12 @@ static constexpr unsigned int STANDARD_SCRIPT_VERIFY_FLAGS{MANDATORY_SCRIPT_VERI SCRIPT_VERIFY_CLEANSTACK | SCRIPT_VERIFY_NULLFAIL | SCRIPT_VERIFY_LOW_S | - SCRIPT_VERIFY_CONST_SCRIPTCODE}; + SCRIPT_VERIFY_CONST_SCRIPTCODE | + SCRIPT_VERIFY_TAPROOT | + SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION | + SCRIPT_VERIFY_DISCOURAGE_OP_SUCCESS | + SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_PUBKEYTYPE +}; /** For convenience, standard but not mandatory verify flags. */ static constexpr unsigned int STANDARD_NOT_MANDATORY_VERIFY_FLAGS{STANDARD_SCRIPT_VERIFY_FLAGS & ~MANDATORY_SCRIPT_VERIFY_FLAGS}; @@ -96,15 +103,25 @@ static constexpr decltype(CTransaction::nVersion) TX_MAX_STANDARD_VERSION{3}; /** * Check for standard transaction types +* @param[in] taproot_active Whether taproot rules apply to the next block; a taproot output is +* anyone-can-spend before that, so it is not a standard output until then * @return True if all outputs (scriptPubKeys) use only standard transaction forms */ -bool IsStandardTx(const CTransaction& tx, const std::optional& max_datacarrier_bytes, bool permit_bare_multisig, const CFeeRate& dust_relay_fee, std::string& reason); +bool IsStandardTx(const CTransaction& tx, const std::optional& max_datacarrier_bytes, bool permit_bare_multisig, const CFeeRate& dust_relay_fee, bool taproot_active, std::string& reason); /** * Check for standard transaction types - * @param[in] mapInputs Map of previous transactions that have outputs we're spending + * @param[in] mapInputs Map of previous transactions that have outputs we're spending + * @param[in] taproot_active Whether or taproot consensus rules are active (used to decide whether spends of them are permitted) * @return True if all inputs (scriptSigs) use only standard transaction forms */ -bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs); +bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs, bool taproot_active); +/** + * Check policy limits for Taproot spends: no annex and, for tapscript script + * paths, no stack item larger than MAX_STANDARD_TAPSCRIPT_STACK_ITEM_SIZE + * @param[in] mapInputs Map of previous transactions that have outputs we're spending + * @return True if all Taproot inputs use only standard spending forms + */ +bool IsTaprootStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs); /** Compute the virtual transaction size (taking sigops into account). */ int64_t GetVirtualTransactionSize(int64_t nSize, int64_t nSigOp, unsigned int bytes_per_sigop); diff --git a/src/pubkey.cpp b/src/pubkey.cpp index a40cee3b78f1..2e20c3a6a7fd 100644 --- a/src/pubkey.cpp +++ b/src/pubkey.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include @@ -179,6 +180,41 @@ int ecdsa_signature_parse_der_lax(secp256k1_ecdsa_signature* sig, const unsigned return 1; } +XOnlyPubKey::XOnlyPubKey(Span bytes) +{ + assert(bytes.size() == 32); + std::copy(bytes.begin(), bytes.end(), m_keydata.begin()); +} + +bool XOnlyPubKey::VerifySchnorr(const uint256& msg, Span sigbytes) const +{ + assert(sigbytes.size() == 64); + secp256k1_xonly_pubkey pubkey; + if (!secp256k1_xonly_pubkey_parse(secp256k1_context_static, &pubkey, m_keydata.data())) return false; + return secp256k1_schnorrsig_verify(secp256k1_context_static, sigbytes.data(), msg.begin(), 32, &pubkey); +} + +static const HashWriter HASHER_TAPTWEAK{TaggedHash("TapTweak")}; + +uint256 XOnlyPubKey::ComputeTapTweakHash(const uint256* merkle_root) const +{ + if (merkle_root == nullptr) { + // We have no scripts. The actual tweak does not matter, but follow BIP341 here to + // allow for reproducible tweaking. + return (HashWriter{HASHER_TAPTWEAK} << m_keydata).GetSHA256(); + } else { + return (HashWriter{HASHER_TAPTWEAK} << m_keydata << *merkle_root).GetSHA256(); + } +} + +bool XOnlyPubKey::CheckTapTweak(const XOnlyPubKey& internal, const uint256& merkle_root, bool parity) const +{ + secp256k1_xonly_pubkey internal_key; + if (!secp256k1_xonly_pubkey_parse(secp256k1_context_static, &internal_key, internal.data())) return false; + uint256 tweak = internal.ComputeTapTweakHash(&merkle_root); + return secp256k1_xonly_pubkey_tweak_add_check(secp256k1_context_static, m_keydata.begin(), parity, &internal_key, tweak.begin()); +} + bool CPubKey::Verify(const uint256 &hash, const std::vector& vchSig) const { if (!IsValid()) return false; diff --git a/src/pubkey.h b/src/pubkey.h index a877e866c58a..e2c889f7955a 100644 --- a/src/pubkey.h +++ b/src/pubkey.h @@ -9,6 +9,7 @@ #include #include +#include #include #include @@ -174,7 +175,16 @@ class CPubKey /* * Check syntactic correctness. * - * Note that this is consensus critical as CheckSig() calls it! + * When setting a pubkey (Set()) or deserializing fails (its header bytes + * don't match the length of the data), the size is set to 0. Thus, + * by checking size, one can observe whether Set() or deserialization has + * failed. + * + * This does not check for more than that. In particular, it does not verify + * that the coordinates correspond to a point on the curve (see IsFullyValid() + * for that instead). + * + * Note that this is consensus critical as CheckECDSASignature() calls it! */ bool IsValid() const { @@ -256,6 +266,39 @@ struct EllSwiftPubKey } }; +class XOnlyPubKey +{ +private: + uint256 m_keydata; + +public: + /** Construct an x-only pubkey from exactly 32 bytes. */ + XOnlyPubKey(Span bytes); + + /** Verify a Schnorr signature against this public key. + * + * sigbytes must be exactly 64 bytes. + */ + bool VerifySchnorr(const uint256& msg, Span sigbytes) const; + /** Compute the Taproot tweak as specified in BIP341, with *this as internal + * key: + * - if merkle_root == nullptr: H_TapTweak(xonly_pubkey) + * - otherwise: H_TapTweak(xonly_pubkey || *merkle_root) + * + * Note that the behavior of this function with merkle_root != nullptr is + * consensus critical. + */ + uint256 ComputeTapTweakHash(const uint256* merkle_root) const; + + /** Verify that this is a Taproot tweaked output public key for the given internal key and Merkle root. + * parity selects the parity of the (untweaked) output key. */ + bool CheckTapTweak(const XOnlyPubKey& internal, const uint256& merkle_root, bool parity) const; + + const unsigned char& operator[](int pos) const { return *(m_keydata.begin() + pos); } + const unsigned char* data() const { return m_keydata.begin(); } + size_t size() const { return m_keydata.size(); } +}; + struct CExtPubKey { unsigned char version[4]; unsigned char nDepth; diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index 5a9444f04add..4c95e64c78fd 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -1677,6 +1677,7 @@ UniValue DeploymentInfo(const CBlockIndex* blockindex, const CMNHFManager::Signa for (auto ehf_deploy : { /* sorted by activation block */ Consensus::DEPLOYMENT_V24, Consensus::DEPLOYMENT_EVO_SHARES, + Consensus::DEPLOYMENT_TAPROOT, Consensus::DEPLOYMENT_TESTDUMMY }) { SoftForkDescPushBack(blockindex, ehf_signals, softforks, chainman, ehf_deploy); } diff --git a/src/script/interpreter.cpp b/src/script/interpreter.cpp index f997090edd62..b6d947492c80 100644 --- a/src/script/interpreter.cpp +++ b/src/script/interpreter.cpp @@ -313,13 +313,10 @@ class ConditionStack { }; } -/** Helper for OP_CHECKSIG and OP_CHECKSIGVERIFY - * - * A return value of false means the script fails entirely. When true is returned, the - * fSuccess variable indicates whether the signature check itself succeeded. - */ -static bool EvalChecksig(const valtype& vchSig, const valtype& vchPubKey, CScript::const_iterator pbegincodehash, CScript::const_iterator pend, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror, bool& fSuccess) +static bool EvalChecksigPreTapscript(const valtype& vchSig, const valtype& vchPubKey, CScript::const_iterator pbegincodehash, CScript::const_iterator pend, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror, bool& fSuccess) { + assert(sigversion == SigVersion::BASE); + // Subset of script starting at the most recent codeseparator CScript scriptCode(pbegincodehash, pend); @@ -334,7 +331,7 @@ static bool EvalChecksig(const valtype& vchSig, const valtype& vchPubKey, CScrip //serror is set return false; } - fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion); + fSuccess = checker.CheckECDSASignature(vchSig, vchPubKey, scriptCode, sigversion); if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size()) return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL); @@ -342,8 +339,66 @@ static bool EvalChecksig(const valtype& vchSig, const valtype& vchPubKey, CScrip return true; } +static bool EvalChecksigTapscript(const valtype& sig, const valtype& pubkey, ScriptExecutionData& execdata, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror, bool& success) +{ + assert(sigversion == SigVersion::TAPSCRIPT); + + /* + * The following validation sequence is consensus critical. Please note how -- + * upgradable public key versions precede other rules; + * the script execution fails when using empty signature with invalid public key; + * the script execution fails when using non-empty invalid signature. + */ + success = !sig.empty(); + if (success) { + // Implement the sigops/scriptSig-size ratio test. + // Passing with an upgradable public key version is also counted. + assert(execdata.m_validation_weight_left_init); + execdata.m_validation_weight_left -= VALIDATION_WEIGHT_PER_SIGOP_PASSED; + if (execdata.m_validation_weight_left < 0) { + return set_error(serror, SCRIPT_ERR_TAPSCRIPT_VALIDATION_WEIGHT); + } + } + if (pubkey.size() == 0) { + return set_error(serror, SCRIPT_ERR_PUBKEYTYPE); + } else if (pubkey.size() == 32) { + if (success && !checker.CheckSchnorrSignature(sig, pubkey, sigversion, execdata, serror)) { + return false; // serror is set + } + } else { + /* + * New public key version softforks should be defined before this `else` block. + * Generally, the new code should not do anything but failing the script execution. To avoid + * consensus bugs, it should not modify any existing values (including `success`). + */ + if ((flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_PUBKEYTYPE) != 0) { + return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_PUBKEYTYPE); + } + } + + return true; +} -bool EvalScript(std::vector >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror) +/** Helper for OP_CHECKSIG, OP_CHECKSIGVERIFY, and (in Tapscript) OP_CHECKSIGADD. + * + * A return value of false means the script fails entirely. When true is returned, the + * success variable indicates whether the signature check itself succeeded. + */ +static bool EvalChecksig(const valtype& sig, const valtype& pubkey, CScript::const_iterator pbegincodehash, CScript::const_iterator pend, ScriptExecutionData& execdata, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror, bool& success) +{ + switch (sigversion) { + case SigVersion::BASE: + return EvalChecksigPreTapscript(sig, pubkey, pbegincodehash, pend, flags, checker, sigversion, serror, success); + case SigVersion::TAPSCRIPT: + return EvalChecksigTapscript(sig, pubkey, execdata, flags, checker, sigversion, serror, success); + case SigVersion::TAPROOT: + // Key path spending in Taproot has no script, so this is unreachable. + break; + } + assert(false); +} + +bool EvalScript(std::vector >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror) { static const CScriptNum bnZero(0); static const CScriptNum bnOne(1); @@ -353,6 +408,9 @@ bool EvalScript(std::vector >& stack, const CScript& // static const valtype vchZero(0); static const valtype vchTrue(1, 1); + // sigversion cannot be TAPROOT here, as it admits no script execution. + assert(sigversion == SigVersion::BASE || sigversion == SigVersion::TAPSCRIPT); + CScript::const_iterator pc = script.begin(); CScript::const_iterator pend = script.end(); CScript::const_iterator pbegincodehash = script.begin(); @@ -361,15 +419,18 @@ bool EvalScript(std::vector >& stack, const CScript& ConditionStack vfExec; std::vector altstack; set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR); - if (script.size() > MAX_SCRIPT_SIZE) + if ((sigversion == SigVersion::BASE) && script.size() > MAX_SCRIPT_SIZE) { return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE); + } int nOpCount = 0; bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0; + uint32_t opcode_pos = 0; + execdata.m_codeseparator_pos = 0xFFFFFFFFUL; + execdata.m_codeseparator_pos_init = true; try { - while (pc < pend) - { + for (; pc < pend; ++opcode_pos) { bool fExec = vfExec.all_true(); // @@ -380,9 +441,12 @@ bool EvalScript(std::vector >& stack, const CScript& if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE) return set_error(serror, SCRIPT_ERR_PUSH_SIZE); - // Note how OP_RESERVED does not count towards the opcode limit. - if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT) - return set_error(serror, SCRIPT_ERR_OP_COUNT); + if (sigversion == SigVersion::BASE) { + // Note how OP_RESERVED does not count towards the opcode limit. + if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT) { + return set_error(serror, SCRIPT_ERR_OP_COUNT); + } + } if (opcode == OP_INVERT || opcode == OP_2MUL || @@ -531,6 +595,14 @@ bool EvalScript(std::vector >& stack, const CScript& if (stack.size() < 1) return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL); valtype& vch = stacktop(-1); + // Tapscript requires minimal IF/NOTIF inputs as a consensus rule. + if (sigversion == SigVersion::TAPSCRIPT) { + // The input argument to the OP_IF and OP_NOTIF opcodes must be either + // exactly 0 (the empty vector) or exactly 1 (the one-byte vector with value 1). + if (vch.size() > 1 || (vch.size() == 1 && vch[0] != 1)) { + return set_error(serror, SCRIPT_ERR_TAPSCRIPT_MINIMALIF); + } + } fValue = CastToBool(vch); if (opcode == OP_NOTIF) fValue = !fValue; @@ -1017,6 +1089,7 @@ bool EvalScript(std::vector >& stack, const CScript& // Hash starts after the code separator pbegincodehash = pc; + execdata.m_codeseparator_pos = opcode_pos; } break; @@ -1031,7 +1104,7 @@ bool EvalScript(std::vector >& stack, const CScript& valtype& vchPubKey = stacktop(-1); bool fSuccess = true; - if (!EvalChecksig(vchSig, vchPubKey, pbegincodehash, pend, flags, checker, sigversion, serror, fSuccess)) return false; + if (!EvalChecksig(vchSig, vchPubKey, pbegincodehash, pend, execdata, flags, checker, sigversion, serror, fSuccess)) return false; popstack(stack); popstack(stack); stack.push_back(fSuccess ? vchTrue : vchFalse); @@ -1063,6 +1136,15 @@ bool EvalScript(std::vector >& stack, const CScript& bool fSuccess = false; if (vchSig.size()) { + // Tapscript charges every attempted signature check against the + // validation weight budget (BIP342), data signatures included + if (sigversion == SigVersion::TAPSCRIPT) { + assert(execdata.m_validation_weight_left_init); + execdata.m_validation_weight_left -= VALIDATION_WEIGHT_PER_SIGOP_PASSED; + if (execdata.m_validation_weight_left < 0) { + return set_error(serror, SCRIPT_ERR_TAPSCRIPT_VALIDATION_WEIGHT); + } + } fSuccess = checker.CheckDataSig(vchSig, vchMessage, vchPubKey); } @@ -1084,9 +1166,32 @@ bool EvalScript(std::vector >& stack, const CScript& } break; + case OP_CHECKSIGADD: + { + // OP_CHECKSIGADD is only available in Tapscript + if (sigversion == SigVersion::BASE) return set_error(serror, SCRIPT_ERR_BAD_OPCODE); + + // (sig num pubkey -- num) + if (stack.size() < 3) return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + + const valtype& sig = stacktop(-3); + const CScriptNum num(stacktop(-2), fRequireMinimal); + const valtype& pubkey = stacktop(-1); + + bool success = true; + if (!EvalChecksig(sig, pubkey, pbegincodehash, pend, execdata, flags, checker, sigversion, serror, success)) return false; + popstack(stack); + popstack(stack); + popstack(stack); + stack.push_back((num + (success ? 1 : 0)).getvch()); + } + break; + case OP_CHECKMULTISIG: case OP_CHECKMULTISIGVERIFY: { + if (sigversion == SigVersion::TAPSCRIPT) return set_error(serror, SCRIPT_ERR_TAPSCRIPT_CHECKMULTISIG); + // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool) int i = 1; @@ -1144,7 +1249,7 @@ bool EvalScript(std::vector >& stack, const CScript& } // Check signature - bool fOk = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion); + bool fOk = checker.CheckECDSASignature(vchSig, vchPubKey, scriptCode, sigversion); if (fOk) { isig++; @@ -1333,6 +1438,12 @@ bool EvalScript(std::vector >& stack, const CScript& return set_success(serror); } +bool EvalScript(std::vector >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror) +{ + ScriptExecutionData execdata; + return EvalScript(stack, script, flags, checker, sigversion, execdata, serror); +} + namespace { /** @@ -1468,16 +1579,68 @@ uint256 GetOutputsSHA256(const T& txTo) return ss.GetSHA256(); } +/** Compute the (single) SHA256 of the concatenation of all amounts spent by a tx. */ +uint256 GetSpentAmountsSHA256(const std::vector& outputs_spent) +{ + CHashWriter ss(SER_GETHASH, 0); + for (const auto& txout : outputs_spent) { + ss << txout.nValue; + } + return ss.GetSHA256(); +} + +/** Compute the (single) SHA256 of the concatenation of all scriptPubKeys spent by a tx. */ +uint256 GetSpentScriptsSHA256(const std::vector& outputs_spent) +{ + CHashWriter ss(SER_GETHASH, 0); + for (const auto& txout : outputs_spent) { + ss << txout.scriptPubKey; + } + return ss.GetSHA256(); +} + +/** Compute the single-SHA256 of the serialized special transaction payload. */ +template +uint256 GetExtraPayloadSHA256(const T& txTo) +{ + HashWriter ss{}; + ss << txTo.vExtraPayload; + return ss.GetSHA256(); +} + + } // namespace template void PrecomputedTransactionData::Init(const T& txTo, std::vector&& spent_outputs, bool force) { - assert(!m_ready); + assert(!m_spent_outputs_ready); m_spent_outputs = std::move(spent_outputs); + if (!m_spent_outputs.empty()) { + assert(m_spent_outputs.size() == txTo.vin.size()); + m_spent_outputs_ready = true; + } - m_ready = true; + // Determine whether this transaction spends any Taproot output. This only + // works if spent_outputs was provided as well, but if it wasn't, actual + // validation will fail anyway. + bool uses_bip341_taproot = force; + for (size_t inpos = 0; inpos < txTo.vin.size() && !uses_bip341_taproot; ++inpos) { + if (m_spent_outputs_ready && m_spent_outputs[inpos].scriptPubKey.IsPayToTaproot()) { + uses_bip341_taproot = true; + } + } + if (uses_bip341_taproot) { + m_prevouts_single_hash = GetPrevoutsSHA256(txTo); + m_sequences_single_hash = GetSequencesSHA256(txTo); + m_outputs_single_hash = GetOutputsSHA256(txTo); + + m_spent_amounts_single_hash = GetSpentAmountsSHA256(m_spent_outputs); + m_spent_scripts_single_hash = GetSpentScriptsSHA256(m_spent_outputs); + m_extra_payload_single_hash = GetExtraPayloadSHA256(txTo); + m_bip341_taproot_ready = true; + } } template @@ -1492,7 +1655,7 @@ template void PrecomputedTransactionData::Init(const CMutableTransaction& txTo, template PrecomputedTransactionData::PrecomputedTransactionData(const CTransaction& txTo); template PrecomputedTransactionData::PrecomputedTransactionData(const CMutableTransaction& txTo); -[[maybe_unused]] static bool HandleMissingData(MissingDataBehavior mdb) +static bool HandleMissingData(MissingDataBehavior mdb) { switch (mdb) { case MissingDataBehavior::ASSERT_FAIL: @@ -1504,6 +1667,105 @@ template PrecomputedTransactionData::PrecomputedTransactionData(const CMutableTr assert(!"Unknown MissingDataBehavior value"); } +const HashWriter HASHER_TAPSIGHASH{TaggedHash("TapSighash")}; +const HashWriter HASHER_TAPLEAF{TaggedHash("TapLeaf")}; +const HashWriter HASHER_TAPBRANCH{TaggedHash("TapBranch")}; + +template +bool SignatureHashSchnorr(uint256& hash_out, const ScriptExecutionData& execdata, const T& tx_to, uint32_t in_pos, uint8_t hash_type, SigVersion sigversion, const PrecomputedTransactionData& cache, MissingDataBehavior mdb) +{ + uint8_t ext_flag, key_version; + switch (sigversion) { + case SigVersion::TAPROOT: + ext_flag = 0; + // key_version is not used and left uninitialized. + break; + case SigVersion::TAPSCRIPT: + ext_flag = 1; + // key_version must be 0 for now, representing the current version of + // 32-byte public keys in the tapscript signature opcode execution. + // An upgradable public key version (with a size not 32-byte) may + // request a different key_version with a new sigversion. + key_version = 0; + break; + default: + assert(false); + } + assert(in_pos < tx_to.vin.size()); + if (!(cache.m_bip341_taproot_ready && cache.m_spent_outputs_ready)) { + return HandleMissingData(mdb); + } + + HashWriter ss{HASHER_TAPSIGHASH}; + + // Epoch + static constexpr uint8_t EPOCH = 0; + ss << EPOCH; + + // Hash type + const uint8_t output_type = (hash_type == SIGHASH_DEFAULT) ? SIGHASH_ALL : (hash_type & SIGHASH_OUTPUT_MASK); // Default (no sighash byte) is equivalent to SIGHASH_ALL + const uint8_t input_type = hash_type & SIGHASH_INPUT_MASK; + if (!(hash_type <= 0x03 || (hash_type >= 0x81 && hash_type <= 0x83))) return false; + ss << hash_type; + + // Transaction level data. Dash commits to the 32-bit version|type word like + // the legacy sighash and, for special transactions, to the hash of the payload. + const int32_t n32bitVersion = tx_to.nVersion | (tx_to.nType << 16); + ss << n32bitVersion; + ss << tx_to.nLockTime; + if (tx_to.nVersion >= CTransaction::SPECIAL_VERSION && tx_to.nType != TRANSACTION_NORMAL) { + ss << cache.m_extra_payload_single_hash; + } + if (input_type != SIGHASH_ANYONECANPAY) { + ss << cache.m_prevouts_single_hash; + ss << cache.m_spent_amounts_single_hash; + ss << cache.m_spent_scripts_single_hash; + ss << cache.m_sequences_single_hash; + } + if (output_type == SIGHASH_ALL) { + ss << cache.m_outputs_single_hash; + } + + // Data about the input/prevout being spent + assert(execdata.m_annex_init); + const bool have_annex = execdata.m_annex_present; + const uint8_t spend_type = (ext_flag << 1) + (have_annex ? 1 : 0); // The low bit indicates whether an annex is present. + ss << spend_type; + if (input_type == SIGHASH_ANYONECANPAY) { + ss << tx_to.vin[in_pos].prevout; + ss << cache.m_spent_outputs[in_pos]; + ss << tx_to.vin[in_pos].nSequence; + } else { + ss << in_pos; + } + if (have_annex) { + ss << execdata.m_annex_hash; + } + + // Data about the output (if only one). + if (output_type == SIGHASH_SINGLE) { + if (in_pos >= tx_to.vout.size()) return false; + HashWriter sha_single_output{}; + sha_single_output << tx_to.vout[in_pos]; + ss << sha_single_output.GetSHA256(); + } + + // Additional data for BIP 342 signatures + if (sigversion == SigVersion::TAPSCRIPT) { + assert(execdata.m_tapleaf_hash_init); + ss << execdata.m_tapleaf_hash; + ss << key_version; + assert(execdata.m_codeseparator_pos_init); + ss << execdata.m_codeseparator_pos; + } + + hash_out = ss.GetSHA256(); + return true; +} + +template bool SignatureHashSchnorr(uint256& hash_out, const ScriptExecutionData& execdata, const CTransaction& tx_to, uint32_t in_pos, uint8_t hash_type, SigVersion sigversion, const PrecomputedTransactionData& cache, MissingDataBehavior mdb); +template bool SignatureHashSchnorr(uint256& hash_out, const ScriptExecutionData& execdata, const CMutableTransaction& tx_to, uint32_t in_pos, uint8_t hash_type, SigVersion sigversion, const PrecomputedTransactionData& cache, MissingDataBehavior mdb); + template uint256 SignatureHash(const CScript& scriptCode, const T& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache) { @@ -1543,7 +1805,7 @@ bool BaseSignatureChecker::CheckDataSig(const std::vector& vchSig } template -bool GenericTransactionSignatureChecker::VerifySignature(const std::vector& vchSig, const CPubKey& pubkey, const uint256& sighash) const +bool GenericTransactionSignatureChecker::VerifyECDSASignature(const std::vector& vchSig, const CPubKey& pubkey, const uint256& sighash) const { return pubkey.Verify(sighash, vchSig); } @@ -1557,11 +1819,17 @@ bool GenericTransactionSignatureChecker::CheckDataSig(const std::vector -bool GenericTransactionSignatureChecker::CheckSig(const std::vector& vchSigIn, const std::vector& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const +bool GenericTransactionSignatureChecker::VerifySchnorrSignature(Span sig, const XOnlyPubKey& pubkey, const uint256& sighash) const +{ + return pubkey.VerifySchnorr(sighash, sig); +} + +template +bool GenericTransactionSignatureChecker::CheckECDSASignature(const std::vector& vchSigIn, const std::vector& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const { CPubKey pubkey(vchPubKey); if (!pubkey.IsValid()) @@ -1576,12 +1844,40 @@ bool GenericTransactionSignatureChecker::CheckSig(const std::vectortxdata); - if (!VerifySignature(vchSig, pubkey, sighash)) + if (!VerifyECDSASignature(vchSig, pubkey, sighash)) return false; return true; } +template +bool GenericTransactionSignatureChecker::CheckSchnorrSignature(Span sig, Span pubkey_in, SigVersion sigversion, const ScriptExecutionData& execdata, ScriptError* serror) const +{ + assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT); + // Schnorr signatures have 32-byte public keys. The caller is responsible for enforcing this. + assert(pubkey_in.size() == 32); + // Note that in Tapscript evaluation, empty signatures are treated specially (invalid signature that does not + // abort script execution). This is implemented in EvalChecksigTapscript, which won't invoke + // CheckSchnorrSignature in that case. In other contexts, they are invalid like every other signature with + // size different from 64 or 65. + if (sig.size() != 64 && sig.size() != 65) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_SIZE); + + XOnlyPubKey pubkey{pubkey_in}; + + uint8_t hashtype = SIGHASH_DEFAULT; + if (sig.size() == 65) { + hashtype = SpanPopBack(sig); + if (hashtype == SIGHASH_DEFAULT) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_HASHTYPE); + } + uint256 sighash; + if (!this->txdata) return HandleMissingData(m_mdb); + if (!SignatureHashSchnorr(sighash, execdata, *txTo, nIn, hashtype, sigversion, *this->txdata, m_mdb)) { + return set_error(serror, SCRIPT_ERR_SCHNORR_SIG_HASHTYPE); + } + if (!VerifySchnorrSignature(sig, pubkey, sighash)) return set_error(serror, SCRIPT_ERR_SCHNORR_SIG); + return true; +} + template bool GenericTransactionSignatureChecker::CheckLockTime(const CScriptNum& nLockTime) const { @@ -1670,6 +1966,158 @@ bool GenericTransactionSignatureChecker::CheckSequence(const CScriptNum& nSeq template class GenericTransactionSignatureChecker; template class GenericTransactionSignatureChecker; +static bool ExecuteTapscript(const Span& stack_span, const CScript& exec_script, unsigned int flags, const BaseSignatureChecker& checker, ScriptExecutionData& execdata, ScriptError* serror) +{ + std::vector stack{stack_span.begin(), stack_span.end()}; + + // OP_SUCCESSx processing overrides everything, including stack element size limits + CScript::const_iterator pc = exec_script.begin(); + while (pc < exec_script.end()) { + opcodetype opcode; + if (!exec_script.GetOp(pc, opcode)) { + // Note how this condition would not be reached if an unknown OP_SUCCESSx was found + return set_error(serror, SCRIPT_ERR_BAD_OPCODE); + } + // New opcodes will be listed here. May use a different sigversion to modify existing opcodes. + if (IsOpSuccess(opcode)) { + if (flags & SCRIPT_VERIFY_DISCOURAGE_OP_SUCCESS) { + return set_error(serror, SCRIPT_ERR_DISCOURAGE_OP_SUCCESS); + } + return set_success(serror); + } + } + + // Tapscript enforces initial stack size limits (altstack is empty here) + if (stack.size() > MAX_STACK_SIZE) return set_error(serror, SCRIPT_ERR_STACK_SIZE); + + // Disallow stack item size > MAX_SCRIPT_ELEMENT_SIZE in the initial stack + for (const valtype& elem : stack) { + if (elem.size() > MAX_SCRIPT_ELEMENT_SIZE) return set_error(serror, SCRIPT_ERR_PUSH_SIZE); + } + + // Run the script interpreter. + if (!EvalScript(stack, exec_script, flags, checker, SigVersion::TAPSCRIPT, execdata, serror)) return false; + + // Tapscript implicitly requires cleanstack behaviour + if (stack.size() != 1) return set_error(serror, SCRIPT_ERR_CLEANSTACK); + if (!CastToBool(stack.back())) return set_error(serror, SCRIPT_ERR_EVAL_FALSE); + return true; +} + +uint256 ComputeTapleafHash(uint8_t leaf_version, const CScript& script) +{ + return (HashWriter{HASHER_TAPLEAF} << leaf_version << script).GetSHA256(); +} + +uint256 ComputeTapbranchHash(Span a, Span b) +{ + HashWriter ss_branch{HASHER_TAPBRANCH}; + if (std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end())) { + ss_branch << a << b; + } else { + ss_branch << b << a; + } + return ss_branch.GetSHA256(); +} + +uint256 ComputeTaprootMerkleRoot(Span control, const uint256& tapleaf_hash) +{ + assert(control.size() >= TAPROOT_CONTROL_BASE_SIZE); + assert(control.size() <= TAPROOT_CONTROL_MAX_SIZE); + assert((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE == 0); + + const int path_len = (control.size() - TAPROOT_CONTROL_BASE_SIZE) / TAPROOT_CONTROL_NODE_SIZE; + uint256 k = tapleaf_hash; + for (int i = 0; i < path_len; ++i) { + Span node{Span{control}.subspan(TAPROOT_CONTROL_BASE_SIZE + TAPROOT_CONTROL_NODE_SIZE * i, TAPROOT_CONTROL_NODE_SIZE)}; + k = ComputeTapbranchHash(k, node); + } + return k; +} + +static bool VerifyTaprootCommitment(const std::vector& control, const std::vector& program, const uint256& tapleaf_hash) +{ + assert(control.size() >= TAPROOT_CONTROL_BASE_SIZE); + assert(program.size() >= uint256::size()); + //! The internal pubkey (x-only, so no Y coordinate parity). + const XOnlyPubKey p{Span{control}.subspan(1, TAPROOT_CONTROL_BASE_SIZE - 1)}; + //! The output pubkey (taken from the scriptPubKey). + const XOnlyPubKey q{program}; + // Compute the Merkle root from the leaf and the provided path. + const uint256 merkle_root = ComputeTaprootMerkleRoot(control, tapleaf_hash); + // Verify that the output pubkey matches the tweaked internal pubkey, after correcting for parity. + return q.CheckTapTweak(p, merkle_root, control[0] & 1); +} + +bool ParseTaprootStack(const CScript& scriptSig, std::vector>& stack, ScriptError* serror) +{ + CScript::const_iterator pc = scriptSig.begin(); + while (pc < scriptSig.end()) { + opcodetype opcode; + valtype push; + if (!scriptSig.GetOp(pc, opcode, push)) return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY); + if (opcode > OP_16 || opcode == OP_RESERVED) return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY); + // OP_1NEGATE and OP_1..OP_16 are minimal by construction; a data push has to be + if (opcode <= OP_PUSHDATA4 && !CheckMinimalPush(push, opcode)) return set_error(serror, SCRIPT_ERR_MINIMALDATA); + if (opcode >= OP_1NEGATE) { + push = CScriptNum(static_cast(opcode) - static_cast(OP_1 - 1)).getvch(); + } + stack.push_back(std::move(push)); + } + return true; +} + +static bool VerifyTaprootProgram(const CScript& scriptSig, const std::vector& program, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror) +{ + // BIP341 Taproot: 32-byte program (which encodes a P2C-tweaked pubkey). The + // BIP341 "witness stack" is carried as the pushes of the scriptSig. + std::vector stack_items; + if (!ParseTaprootStack(scriptSig, stack_items, serror)) return false; + Span stack{stack_items}; + ScriptExecutionData execdata; + + if (stack.size() == 0) return set_error(serror, SCRIPT_ERR_TAPROOT_STACK_EMPTY); + if (stack.size() >= 2 && !stack.back().empty() && stack.back()[0] == ANNEX_TAG) { + // Drop annex (this is non-standard; see IsTaprootStandard) + const valtype& annex = SpanPopBack(stack); + execdata.m_annex_hash = (HashWriter{} << annex).GetSHA256(); + execdata.m_annex_present = true; + } else { + execdata.m_annex_present = false; + } + execdata.m_annex_init = true; + if (stack.size() == 1) { + // Key path spending (stack size is 1 after removing optional annex) + if (!checker.CheckSchnorrSignature(stack.front(), program, SigVersion::TAPROOT, execdata, serror)) { + return false; // serror is set + } + return set_success(serror); + } else { + // Script path spending (stack size is >1 after removing optional annex) + const valtype& control = SpanPopBack(stack); + const valtype& script_bytes = SpanPopBack(stack); + const CScript exec_script(script_bytes.begin(), script_bytes.end()); + if (control.size() < TAPROOT_CONTROL_BASE_SIZE || control.size() > TAPROOT_CONTROL_MAX_SIZE || ((control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE) != 0) { + return set_error(serror, SCRIPT_ERR_TAPROOT_WRONG_CONTROL_SIZE); + } + execdata.m_tapleaf_hash = ComputeTapleafHash(control[0] & TAPROOT_LEAF_MASK, exec_script); + if (!VerifyTaprootCommitment(control, program, execdata.m_tapleaf_hash)) { + return set_error(serror, SCRIPT_ERR_TAPROOT_COMMITMENT_MISMATCH); + } + execdata.m_tapleaf_hash_init = true; + if ((control[0] & TAPROOT_LEAF_MASK) == TAPROOT_LEAF_TAPSCRIPT) { + // Tapscript (leaf version 0xc0) + execdata.m_validation_weight_left = ::GetSerializeSize(scriptSig, PROTOCOL_VERSION) + VALIDATION_WEIGHT_OFFSET; + execdata.m_validation_weight_left_init = true; + return ExecuteTapscript(stack, exec_script, flags, checker, execdata, serror); + } + if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION) { + return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION); + } + return set_success(serror); + } +} + bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror) { set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR); @@ -1678,6 +2126,16 @@ bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, unsigne return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY); } + // BIP341 Taproot: the scriptSig carries the stack items directly and is + // never executed as a script, so no element size or minimal-push rule of + // the legacy interpreter applies to it. A node without the flag treats the + // output as a plain script instead and rejects pushes over + // MAX_SCRIPT_ELEMENT_SIZE, so activating the flag is a hard fork for it. + std::vector taproot_program; + if ((flags & SCRIPT_VERIFY_TAPROOT) && scriptPubKey.IsPayToTaproot(taproot_program)) { + return VerifyTaprootProgram(scriptSig, taproot_program, flags, checker, serror); + } + // scriptSig and scriptPubKey must be evaluated sequentially on the same stack // rather than being simply concatenated (see CVE-2010-5141) std::vector > stack, stackCopy; diff --git a/src/script/interpreter.h b/src/script/interpreter.h index e6ec7d3392aa..7b101e5e865b 100644 --- a/src/script/interpreter.h +++ b/src/script/interpreter.h @@ -7,6 +7,7 @@ #define BITCOIN_SCRIPT_INTERPRETER_H #include +#include #include #include