[bug]: txscript.CalcScriptInfo panics (index out of range) on P2WSH pkScript with empty witness
Background
txscript.CalcScriptInfo (a public but DEPRECATED function, txscript/standard.go:789) indexes the witness stack without a length guard in its P2WSH branch, so calling it with a valid P2WSH pkScript and an empty witness panics with an index-out-of-range.
txscript/standard.go:838-839—case si.PkScriptClass == WitnessV0ScriptHashTy && segwit:→witnessScript := witness[len(witness)-1]
When segwit == true and len(witness) == 0, witness[len(witness)-1] is witness[-1]. The sibling helper getWitnessSigOps guards the same access with len(witness) > 0 (txscript/script.go:502), which is why block validation is unaffected — the defect is specific to CalcScriptInfo.
CalcScriptInfo has no callers anywhere in the btcd tree (only txscript/standard.go itself and its test import it), so it is not reachable from a peer message, an RPC request, or block validation. It is only reachable by a third-party program that imports txscript and calls this deprecated API directly. No adversary in any btcd deployment, so this is library hardening rather than a security issue. Found during a code review.
Your environment
btcdv0.26.2, and present onmaster(txscript/standard.go:838-839unchanged)- platform-independent
Steps to reproduce
package main
import "github.com/btcsuite/btcd/txscript/v2"
func main() {
sigScript := []byte{txscript.OP_PUSHDATA1, 1, 0x51}
pkScript := append([]byte{txscript.OP_0, txscript.OP_DATA_32}, make([]byte, 32)...)
_, _ = txscript.CalcScriptInfo(sigScript, pkScript, nil, true, true) // valid P2WSH output, empty witness
}Expected behaviour
An empty witness for a P2WSH output returns an error (e.g. ErrStackUnderflow or an equivalent informative error), not a panic.
Actual behaviour
panic: runtime error: index out of range [-1] at txscript/standard.go:839.
Suggested fix
Guard the witness access with len(witness) > 0 (mirroring getWitnessSigOps), returning an informative error for an empty witness.
Source: btcsuite/btcd