65 lines
1.8 KiB
Go
Raw Normal View History

2019-10-01 12:22:30 -03:00
package libwallet
import (
"crypto/sha256"
2021-01-29 18:51:08 -03:00
"fmt"
2019-10-01 12:22:30 -03:00
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
2020-11-09 10:05:29 -03:00
"github.com/btcsuite/btcutil"
2019-10-01 12:22:30 -03:00
)
2020-11-09 10:05:29 -03:00
func signNativeSegwitInput(index int, tx *wire.MsgTx, privateKey *HDPrivateKey, witnessScript []byte, amount btcutil.Amount) ([]byte, error) {
2019-12-16 17:59:11 -03:00
privKey, err := privateKey.key.ECPrivKey()
if err != nil {
2021-01-29 18:51:08 -03:00
return nil, fmt.Errorf("failed to produce EC priv key for signing: %w", err)
2019-12-16 17:59:11 -03:00
}
sigHashes := txscript.NewTxSigHashes(tx)
2020-11-09 10:05:29 -03:00
sig, err := txscript.RawTxInWitnessSignature(tx, sigHashes, index, int64(amount), witnessScript, txscript.SigHashAll, privKey)
2019-12-16 17:59:11 -03:00
if err != nil {
2021-01-29 18:51:08 -03:00
return nil, fmt.Errorf("failed to sign V4 input: %w", err)
2019-12-16 17:59:11 -03:00
}
return sig, nil
}
2019-10-01 12:22:30 -03:00
func createNonNativeSegwitRedeemScript(witnessScript []byte) ([]byte, error) {
witnessScriptHash := sha256.Sum256(witnessScript)
builder := txscript.NewScriptBuilder()
builder.AddInt64(0)
builder.AddData(witnessScriptHash[:])
return builder.Script()
}
2020-11-09 10:05:29 -03:00
func signNonNativeSegwitInput(index int, tx *wire.MsgTx, privateKey *HDPrivateKey,
redeemScript, witnessScript []byte, amount btcutil.Amount) ([]byte, error) {
2019-10-01 12:22:30 -03:00
txInput := tx.TxIn[index]
builder := txscript.NewScriptBuilder()
builder.AddData(redeemScript)
script, err := builder.Script()
if err != nil {
2021-01-29 18:51:08 -03:00
return nil, fmt.Errorf("failed to generate signing script: %w", err)
2019-10-01 12:22:30 -03:00
}
txInput.SignatureScript = script
privKey, err := privateKey.key.ECPrivKey()
if err != nil {
2021-01-29 18:51:08 -03:00
return nil, fmt.Errorf("failed to produce EC priv key for signing: %w", err)
2019-10-01 12:22:30 -03:00
}
sigHashes := txscript.NewTxSigHashes(tx)
2020-11-09 10:05:29 -03:00
sig, err := txscript.RawTxInWitnessSignature(
tx, sigHashes, index, int64(amount), witnessScript, txscript.SigHashAll, privKey)
2019-10-01 12:22:30 -03:00
if err != nil {
2021-01-29 18:51:08 -03:00
return nil, fmt.Errorf("failed to sign V3 input: %w", err)
2019-10-01 12:22:30 -03:00
}
return sig, nil
}