-
Notifications
You must be signed in to change notification settings - Fork 0
/
sign.go
82 lines (70 loc) · 1.67 KB
/
sign.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package transaction
import (
"fmt"
"github.com/btcsuite/btcd/btcec"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
)
type Signer struct {
privateKey *btcec.PrivateKey
}
// NewSigner initializes a new signer with a private key decoded from WIF.
func NewSigner(wif string) (*Signer, error) {
privateKey, err := privateKeyFromWIF(wif)
if err != nil {
return nil, err
}
return &Signer{
privateKey: privateKey,
}, nil
}
// privateKeyFromWIF decodes WIF and returns a private key from this WIF.
func privateKeyFromWIF(wif string) (*btcec.PrivateKey, error) {
decodedWIF, err := btcutil.DecodeWIF(wif)
if err != nil {
return nil, fmt.Errorf("cannot decode WIF [%s]", err)
}
return decodedWIF.PrivKey, nil
}
func (s *Signer) SignNoWitness(
msgTx *wire.MsgTx,
subscript []byte,
inputToSignIndex uint32,
) error {
sigScript, err := txscript.SignatureScript(
msgTx,
int(inputToSignIndex),
subscript,
txscript.SigHashAll,
s.privateKey,
true,
)
if err != nil {
return fmt.Errorf("signature script calculation failed: [%s]", err)
}
msgTx.TxIn[inputToSignIndex].SignatureScript = sigScript
return nil
}
func (s *Signer) SignWitness(
msgTx *wire.MsgTx,
sourceOutputScript []byte,
inputToSignIndex uint32,
sourceTxOutputAmount uint64,
) error {
witness, err := txscript.WitnessSignature(
msgTx,
txscript.NewTxSigHashes(msgTx),
int(inputToSignIndex),
int64(sourceTxOutputAmount),
sourceOutputScript,
txscript.SigHashAll,
s.privateKey,
true,
)
if err != nil {
return fmt.Errorf("witness signature calculation failed: [%s]", err)
}
msgTx.TxIn[inputToSignIndex].Witness = witness
return nil
}