psbt: multi_a finalizer builds invalid witnesses
finalizeTaprootInput assumes TaprootScriptSpendSig slice order is final witness order:
for _, scriptSpendSig := range pInput.TaprootScriptSpendSig {
witnessStack = append(witnessStack, scriptSpendSig.Signature)
}However, PSBT_IN_TAP_SCRIPT_SIG is keyed by pubkey and leaf hash; its order has no witness semantics. For multi_a, signatures must be matched to script keys and emitted in reverse key order.
Minimal reproducer for multi_a(2, A, B):
func TestFinalizeMultiAOrder(t *testing.T) {
keyA := bytes.Repeat([]byte{0x02}, 32)
keyB := bytes.Repeat([]byte{0x03}, 32)
sigA := bytes.Repeat([]byte{0xaa}, 64)
sigB := bytes.Repeat([]byte{0xbb}, 64)
script, err := txscript.NewScriptBuilder().
AddData(keyA).AddOp(txscript.OP_CHECKSIG).
AddData(keyB).AddOp(txscript.OP_CHECKSIGADD).
AddOp(txscript.OP_2).AddOp(txscript.OP_NUMEQUAL).Script()
require.NoError(t, err)
leafHash := txscript.NewBaseTapLeaf(script).TapHash()
tx := wire.NewMsgTx(2)
tx.AddTxIn(wire.NewTxIn(&wire.OutPoint{}, nil, nil))
tx.AddTxOut(wire.NewTxOut(0, nil))
packet, err := NewFromUnsignedTx(tx)
require.NoError(t, err)
packet.Inputs[0].WitnessUtxo = wire.NewTxOut(
1, append([]byte{txscript.OP_1, 32}, make([]byte, 32)...),
)
packet.Inputs[0].TaprootLeafScript = []*TaprootTapLeafScript{{
ControlBlock: make([]byte, 33),
Script: script, LeafVersion: txscript.BaseLeafVersion,
}}
packet.Inputs[0].TaprootScriptSpendSig = []*TaprootScriptSpendSig{
{XOnlyPubKey: keyA, LeafHash: leafHash[:], Signature: sigA},
{XOnlyPubKey: keyB, LeafHash: leafHash[:], Signature: sigB},
}
require.NoError(t, MaybeFinalizeAll(packet))
finalTx, err := Extract(packet)
require.NoError(t, err)
// Fails: the first item is sigA. It must be sigB.
require.Equal(t, sigB, finalTx.TxIn[0].Witness[0])
}For k-of-n, where k < n, finalization additionally needs n-k empty placeholders, so btcd's present algorithm cannot correctly finalize it.
The finalizer should parse the selected leaf, map signatures by x-only pubkey, emit one item per key in reverse script order, and use empty items for missing signatures. If the script is unsupported, it should return an error rather than produce an invalid FinalScriptWitness.
Affected in btcutil/psbt v1.2.0 and current master.
Source: btcsuite/btcd