Merge pull request #2655 from yyforyongyu/task/txscript-signature-validation
What changed, and why it matters
This commit tightens how Bitcoin script signatures are validated in btcd. It moves several security checks earlier in the process, limits a special 'OP_SUCCESS' shortcut to ordinary tapscript leaves, and fixes the signature-removal logic so it only matches actual data pushes. These changes reduce the chance that an attacker could craft a transaction that passes validation when it should fail, or that future script versions accidentally inherit today's rules.
Reviewers should verify that the new ordering of checks matches Bitcoin Core's consensus and policy behavior, run the existing txscript test suite (especially signature and tapscript tests), and consider adding targeted tests for empty-signature/empty-pubkey edge cases and future leaf versions.
Security signals we found
Moved ScriptVerifyConstScriptCode check before signature parsing in legacy scripts
Restricted OP_SUCCESS shortcut to base tapscript leaf version
Fixed removeOpcodeByData to match only data pushes and handle empty dataToRemove
Centralized tapscript pubkey encoding validation before empty-signature branches
Removed sigMatch from verifyResult; signature removal now handled in opcode
Evidence from the diff
The patch refactors txscript signature validation: (1) OP_SUCCESS is now only checked for base tapscript leaves (BaseLeafVersion), preserving future leaf-version opaqueness; (2) ScriptVerifyConstScriptCode is enforced before signature/key parsing in legacy scripts, and signature removal is moved out of the verifier into opcodeCheckSig; (3) removeOpcodeByData now uses removeMatchingDataPush, matching only byte-vector pushes (OP_DATA_1 or canonical pushes) and no longer treating empty dataToRemove as a no-match blocker; (4) tapscript pubkey encoding checks are centralized in checkTapscriptPubKeyEncoding and applied before empty-signature handling; (5) verifyResult drops the sigMatch field. These are correctness/policy alignment fixes rather than a single obvious exploit patch.
Changed components
txscript/engine.gotxscript/opcode.gotxscript/script.gotxscript/sigvalidate.goInspect captured patch +90 / −76
### txscript/engine.go
@@ -737,10 +737,12 @@ func (vm *Engine) verifyWitnessProgram(witness wire.TxWitness) error {
}
// Now that we know the commitment is valid, we'll
- // check to see if OP_SUCCESS op codes are found in the
- // script. If so, then we'll return here early as we
- // skip proper validation.
- if ScriptHasOpSuccess(witnessScript) {
+ // check for OP_SUCCESS only in a base tapscript leaf.
+ // Future leaves have unknown execution rules, so their bytes
+ // must remain opaque to preserve leaf-version policy below.
+ if controlBlock.LeafVersion == BaseLeafVersion &&
+ ScriptHasOpSuccess(witnessScript) {
+
// An op success op code has been found, however if
// the policy flag forbidding them is active, then
// we'll return an error.
### txscript/opcode.go
@@ -1985,6 +1985,17 @@ func opcodeCheckSig(op *opcode, data []byte, vm *Engine) error {
return err
}
+ // Legacy script-code policy is checked before signature/key encoding
+ // or parsing. Witness scripts do not perform signature removal.
+ if vm.witnessProgram == nil &&
+ vm.hasFlag(ScriptVerifyConstScriptCode) {
+
+ _, match := removeOpcodeByData(vm.subScript(), fullSigBytes)
+ if match {
+ return scriptError(ErrNonConstScriptCode, "non-const script code")
+ }
+ }
+
// The signature actually needs to be longer than this, but at
// least 1 byte is needed for the hash type below. The full length is
// checked depending on the script flags and upon parsing the signature.
@@ -2008,31 +2019,13 @@ func opcodeCheckSig(op *opcode, data []byte, vm *Engine) error {
sigVerifier, err = newBaseSigVerifier(
pkBytes, fullSigBytes, vm,
)
- if err != nil {
- var scriptErr Error
- if errors.As(err, &scriptErr) {
- return err
- }
-
- vm.dstack.PushBool(false)
- return nil
- }
// If the base segwit version is active, then we'll create the verifier
// that factors in those new consensus rules.
case vm.isWitnessVersionActive(BaseSegwitWitnessVersion):
sigVerifier, err = newBaseSegwitSigVerifier(
pkBytes, fullSigBytes, vm,
)
- if err != nil {
- var scriptErr Error
- if errors.As(err, &scriptErr) {
- return err
- }
-
- vm.dstack.PushBool(false)
- return nil
- }
// Otherwise, this is routine tapscript execution.
case vm.taprootCtx != nil:
@@ -2044,23 +2037,22 @@ func opcodeCheckSig(op *opcode, data []byte, vm *Engine) error {
}
}
- // Empty public keys immediately cause execution to fail.
- if len(pkBytes) == 0 {
- return scriptError(ErrTaprootPubkeyIsEmpty, "")
+ // Key-type rules apply even to empty signatures. Check them
+ // after sigop accounting to preserve its error precedence.
+ if err := vm.checkTapscriptPubKeyEncoding(pkBytes); err != nil {
+ return err
}
// If this is tapscript execution, and the signature was
// actually an empty vector, then we push on an empty vector
- // and continue execution from there, but only if the pubkey
- // isn't empty.
+ // and continue execution from there.
if len(fullSigBytes) == 0 {
vm.dstack.PushByteArray([]byte{})
return nil
}
- // If the constructor fails immediately, then it's because
- // the public key size is zero, so we'll fail all script
- // execution.
+ // The key type is already checked, so constructor errors mean
+ // a malformed key or signature and fail script execution.
sigVerifier, err = newBaseTapscriptSigVerifier(
pkBytes, fullSigBytes, vm,
)
@@ -2079,13 +2071,16 @@ func opcodeCheckSig(op *opcode, data []byte, vm *Engine) error {
// TODO(roasbeef): return an error?
}
- result := sigVerifier.Verify()
- valid := result.sigValid
-
- if vm.hasFlag(ScriptVerifyConstScriptCode) && result.sigMatch {
- str := "non-const script code"
- return scriptError(ErrNonConstScriptCode, str)
+ // Encoding violations remain immediate script errors. Parsing failures
+ // instead produce an invalid result for the shared NULLFAIL handling;
+ // short-circuiting avoids calling a verifier that could not be built.
+ if err != nil {
+ var scriptErr Error
+ if errors.As(err, &scriptErr) {
+ return err
+ }
}
+ valid := err == nil && sigVerifier.Verify().sigValid
switch {
// For tapscript, and prior execution with null fail active, if the
@@ -2155,9 +2150,10 @@ func opcodeCheckSigAdd(op *opcode, data []byte, vm *Engine) error {
}
}
- // Empty public keys immediately cause execution to fail.
- if len(pubKeyBytes) == 0 {
- return scriptError(ErrTaprootPubkeyIsEmpty, "")
+ // Key-type rules apply even to empty signatures. Check them after
+ // sigop accounting to preserve its error precedence.
+ if err := vm.checkTapscriptPubKeyEncoding(pubKeyBytes); err != nil {
+ return err
}
// If the signature is empty, then we'll just push the value N back
@@ -2169,8 +2165,8 @@ func opcodeCheckSigAdd(op *opcode, data []byte, vm *Engine) error {
// Otherwise, we'll attempt to validate the signature as normal.
//
- // If the constructor fails immediately, then it's because the public
- // key size is zero, so we'll fail all script execution.
+ // The key type is already checked, so constructor errors mean a
+ // malformed key or signature and fail script execution.
sigVerifier, err := newBaseTapscriptSigVerifier(
pubKeyBytes, sigBytes, vm,
)
@@ -2349,6 +2345,12 @@ func opcodeCheckMultiSig(op *opcode, data []byte, vm *Engine) error {
rawSig := sigInfo.signature
if len(rawSig) == 0 {
+ // Empty signatures still require considered-key encoding
+ // checks; non-empty signatures keep their ordering below.
+ if err := vm.checkPubKeyEncoding(pubKey); err != nil {
+ return err
+ }
+
// Skip to the next pubkey if signature is empty.
continue
}
### txscript/script.go
@@ -241,8 +241,8 @@ func isCanonicalPush(opcode byte, data []byte) bool {
return true
}
-// removeOpcodeByData will return the script minus any opcodes that perform a
-// canonical push of data that contains the passed data to remove. This
+// removeOpcodeByData returns the script minus pushes that exactly match the
+// passed data using FindAndDelete's byte-vector push encoding. This
// function assumes it is provided a version 0 script as any future version of
// script should avoid this functionality since it is unnecessary due to the
// signature scripts not being part of the witness-free transaction hash.
@@ -257,20 +257,19 @@ func isCanonicalPush(opcode byte, data []byte) bool {
// versions.
func removeOpcodeByData(script []byte, dataToRemove []byte) ([]byte, bool) {
// Avoid work when possible.
- if len(script) == 0 || len(dataToRemove) == 0 {
+ if len(script) == 0 {
return script, false
}
- // Parse through the script looking for a canonical data push that contains
- // the data to remove.
+ // Parse through the script looking for matching byte-vector pushes.
const scriptVersion = 0
var result []byte
var prevOffset int32
var match bool
tokenizer := MakeScriptTokenizer(scriptVersion, script)
for tokenizer.Next() {
var found bool
- result, prevOffset, found = removeOpcodeCanonical(
+ result, prevOffset, found = removeMatchingDataPush(
&tokenizer, script, dataToRemove, prevOffset, result,
)
if found {
@@ -283,7 +282,9 @@ func removeOpcodeByData(script []byte, dataToRemove []byte) ([]byte, bool) {
return result, match
}
-func removeOpcodeCanonical(t *ScriptTokenizer, script, dataToRemove []byte,
+// removeMatchingDataPush omits matching byte-vector pushes from a tokenized
+// script, allocating a replacement only when the first match is found.
+func removeMatchingDataPush(t *ScriptTokenizer, script, dataToRemove []byte,
prevOffset int32, result []byte) ([]byte, int32, bool) {
var found bool
@@ -296,7 +297,13 @@ func removeOpcodeCanonical(t *ScriptTokenizer, script, dataToRemove []byte,
// Thus, as an optimization, avoid allocating a new script unless there
// is actually a match that needs to be removed.
op, data := t.Opcode(), t.Data()
- if isCanonicalPush(op, data) && bytes.Equal(data, dataToRemove) {
+ // FindAndDelete uses OP_DATA_1 even when an integer opcode would be
+ // minimal. Restrict matches to pushes so nil data on ordinary opcodes
+ // cannot match an empty byte vector.
+ if op <= OP_PUSHDATA4 &&
+ (op == OP_DATA_1 || isCanonicalPush(op, data)) &&
+ bytes.Equal(data, dataToRemove) {
+
if result == nil {
fullPushLen := t.ByteIndex() - prevOffset
result = make([]byte, 0, int32(len(script))-fullPushLen)
### txscript/sigvalidate.go
@@ -27,7 +27,6 @@ type signatureVerifier interface {
type verifyResult struct {
sigValid bool
- sigMatch bool
}
// baseSigVerifier is used to verify signatures for the _base_ system, meaning
@@ -158,16 +157,16 @@ func (b *baseSigVerifier) verifySig(sigHash []byte) bool {
// NOTE: This is part of the baseSigVerifier interface.
func (b *baseSigVerifier) Verify() verifyResult {
// Remove the signature since there is no way for a signature
- // to sign itself.
- subScript, match := removeOpcodeByData(b.subScript, b.fullSigBytes)
+ // to sign itself. The opcode already applied script-code policy
+ // before constructing this verifier.
+ subScript, _ := removeOpcodeByData(b.subScript, b.fullSigBytes)
sigHash := calcSignatureHash(
subScript, b.hashType, &b.vm.tx, b.vm.txIdx,
)
return verifyResult{
sigValid: b.verifySig(sigHash),
- sigMatch: match,
}
}
@@ -404,21 +403,35 @@ type baseTapscriptSigVerifier struct {
vm *Engine
}
-// newBaseTapscriptSigVerifier returns a new sig verifier for tapscript input
-// spends. If the public key or signature aren't correctly formatted, an error
-// is returned.
+// checkTapscriptPubKeyEncoding applies the tapscript key-type rules before an
+// opcode handles an empty signature. Empty keys always fail, while unknown key
+// types remain valid under consensus unless the policy flag rejects them.
+func (vm *Engine) checkTapscriptPubKeyEncoding(pkBytes []byte) error {
+ switch {
+ case len(pkBytes) == 0:
+ return scriptError(ErrTaprootPubkeyIsEmpty, "")
+
+ case len(pkBytes) != schnorr.PubKeyBytesLen &&
+ vm.hasFlag(ScriptVerifyDiscourageUpgradeablePubkeyType):
+
+ str := fmt.Sprintf("pubkey of length %v was used", len(pkBytes))
+ return scriptError(ErrDiscourageUpgradeablePubKeyType, str)
+ }
+
+ return nil
+}
+
+// newBaseTapscriptSigVerifier returns a verifier for a tapscript spend.
+// Callers must first apply checkTapscriptPubKeyEncoding and handle empty
+// signatures. For 32-byte keys, malformed keys or signatures return an error.
+// Other permitted key types verify successfully without parsing.
func newBaseTapscriptSigVerifier(pkBytes, rawSig []byte,
vm *Engine) (*baseTapscriptSigVerifier, error) {
switch len(pkBytes) {
- // If the public key is zero bytes, then this is invalid, and will fail
- // immediately.
- case 0:
- return nil, scriptError(ErrTaprootPubkeyIsEmpty, "")
-
// If the public key is 32 byte as we expect, then we'll parse things
// as normal.
- case 32:
+ case schnorr.PubKeyBytesLen:
baseTaprootVerifier, err := newTaprootSigVerifier(
pkBytes, rawSig, &vm.tx, vm.txIdx, vm.prevOutFetcher,
vm.sigCache, vm.hashCache, vm.taprootCtx.annex,
@@ -433,18 +446,9 @@ func newBaseTapscriptSigVerifier(pkBytes, rawSig []byte,
}, nil
// Otherwise, we consider this to be an unknown public key, which means
- // that we'll just assume the sig to be valid.
+ // that we'll just assume the sig to be valid. Callers already checked
+ // the key-type policy before handling empty signatures.
default:
- // However, if the flag preventing usage of unknown key types
- // is active, then we'll return that error.
- if vm.hasFlag(ScriptVerifyDiscourageUpgradeablePubkeyType) {
- str := fmt.Sprintf("pubkey of length %v was used",
- len(pkBytes))
- return nil, scriptError(
- ErrDiscourageUpgradeablePubKeyType, str,
- )
- }
-
return &baseTapscriptSigVerifier{
taprootSigVerifier: &taprootSigVerifier{},
}, nil
@@ -456,9 +460,8 @@ func newBaseTapscriptSigVerifier(pkBytes, rawSig []byte,
//
// NOTE: This is part of the baseSigVerifier interface.
func (b *baseTapscriptSigVerifier) Verify() verifyResult {
- // If the public key is blank, then that means it wasn't 0 or 32 bytes,
- // so we'll treat this as an unknown public key version and return
- // that it's valid.
+ // A nil parsed key represents an unknown key type already checked by
+ // the caller. Such keys succeed without parsing the signature.
if b.pubKey == nil {
return verifyResult{
sigValid: true,Why this scored 57/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.