-
Notifications
You must be signed in to change notification settings - Fork 2
/
segwit.go
executable file
·64 lines (49 loc) · 1.77 KB
/
segwit.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package libwallet
import (
"crypto/sha256"
"fmt"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
)
func signNativeSegwitInput(index int, tx *wire.MsgTx, privateKey *HDPrivateKey, witnessScript []byte, amount btcutil.Amount) ([]byte, error) {
privKey, err := privateKey.key.ECPrivKey()
if err != nil {
return nil, fmt.Errorf("failed to produce EC priv key for signing: %w", err)
}
sigHashes := txscript.NewTxSigHashes(tx)
sig, err := txscript.RawTxInWitnessSignature(tx, sigHashes, index, int64(amount), witnessScript, txscript.SigHashAll, privKey)
if err != nil {
return nil, fmt.Errorf("failed to sign V4 input: %w", err)
}
return sig, nil
}
func createNonNativeSegwitRedeemScript(witnessScript []byte) ([]byte, error) {
witnessScriptHash := sha256.Sum256(witnessScript)
builder := txscript.NewScriptBuilder()
builder.AddInt64(0)
builder.AddData(witnessScriptHash[:])
return builder.Script()
}
func signNonNativeSegwitInput(index int, tx *wire.MsgTx, privateKey *HDPrivateKey,
redeemScript, witnessScript []byte, amount btcutil.Amount) ([]byte, error) {
txInput := tx.TxIn[index]
builder := txscript.NewScriptBuilder()
builder.AddData(redeemScript)
script, err := builder.Script()
if err != nil {
return nil, fmt.Errorf("failed to generate signing script: %w", err)
}
txInput.SignatureScript = script
privKey, err := privateKey.key.ECPrivKey()
if err != nil {
return nil, fmt.Errorf("failed to produce EC priv key for signing: %w", err)
}
sigHashes := txscript.NewTxSigHashes(tx)
sig, err := txscript.RawTxInWitnessSignature(
tx, sigHashes, index, int64(amount), witnessScript, txscript.SigHashAll, privKey)
if err != nil {
return nil, fmt.Errorf("failed to sign V3 input: %w", err)
}
return sig, nil
}