Skip to content

Commit d07251d

Browse files
authored
Merge pull request #129 from lightninglabs/fix-signpsbt
signpsbt+lnd: fix signing for P2WKH
2 parents f062b53 + 7f840cf commit d07251d

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

cmd/chantools/signpsbt.go

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"github.com/btcsuite/btcd/btcutil"
1111
"github.com/btcsuite/btcd/btcutil/hdkeychain"
1212
"github.com/btcsuite/btcd/btcutil/psbt"
13+
"github.com/btcsuite/btcd/txscript"
1314
"github.com/lightninglabs/chantools/lnd"
1415
"github.com/spf13/cobra"
1516
)
@@ -153,17 +154,25 @@ func signPsbt(rootKey *hdkeychain.ExtendedKey,
153154
return fmt.Errorf("could not derive local key: %w", err)
154155
}
155156

156-
if len(packet.Inputs[inputIndex].WitnessScript) == 0 {
157-
return fmt.Errorf("invalid PSBT, input %d is missing witness "+
158-
"script", inputIndex)
159-
}
160-
witnessScript := packet.Inputs[inputIndex].WitnessScript
161157
if packet.Inputs[inputIndex].WitnessUtxo == nil {
162158
return fmt.Errorf("invalid PSBT, input %d is missing witness "+
163159
"UTXO", inputIndex)
164160
}
165161
utxo := packet.Inputs[inputIndex].WitnessUtxo
166162

163+
// The signing is a bit different for P2WPKH, we need to specify the
164+
// pk script as the witness script.
165+
var witnessScript []byte
166+
if txscript.IsPayToWitnessPubKeyHash(utxo.PkScript) {
167+
witnessScript = utxo.PkScript
168+
} else {
169+
if len(packet.Inputs[inputIndex].WitnessScript) == 0 {
170+
return fmt.Errorf("invalid PSBT, input %d is missing "+
171+
"witness script", inputIndex)
172+
}
173+
witnessScript = packet.Inputs[inputIndex].WitnessScript
174+
}
175+
167176
localPrivateKey, err := localKey.ECPrivKey()
168177
if err != nil {
169178
return fmt.Errorf("error getting private key: %w", err)

lnd/signer.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,14 @@ func (s *Signer) AddPartialSignatureForPrivateKey(packet *psbt.Packet,
210210
if err != nil {
211211
return fmt.Errorf("error creating PSBT updater: %w", err)
212212
}
213+
214+
// If the witness script is the pk script for a P2WPKH output, then we
215+
// need to blank it out for the PSBT code, otherwise it interprets it as
216+
// a P2WSH.
217+
if txscript.IsPayToWitnessPubKeyHash(utxo.PkScript) {
218+
witnessScript = nil
219+
}
220+
213221
status, err := updater.Sign(
214222
inputIndex, ourSig, privateKey.PubKey().SerializeCompressed(),
215223
nil, witnessScript,

0 commit comments

Comments
 (0)