-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathkey_factory.go
More file actions
95 lines (77 loc) · 1.99 KB
/
Copy pathkey_factory.go
File metadata and controls
95 lines (77 loc) · 1.99 KB
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
83
84
85
86
87
88
89
90
91
92
93
94
95
package cnlib
import (
"encoding/hex"
"errors"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcutil/hdkeychain"
)
/// Type Definition
// KeyFactory is a struct holding a ref to an HDWallet, with receiver methods to obtain keys relative to the wallet.
type keyFactory struct {
masterPrivateKey *hdkeychain.ExtendedKey
}
/// Receiver methods
func (kf keyFactory) indexPrivateKey(path *DerivationPath) (*hdkeychain.ExtendedKey, error) {
purposeKey, err := kf.masterPrivateKey.Child(hardened(path.Purpose))
if err != nil {
return nil, err
}
coinKey, err := purposeKey.Child(hardened(path.Coin))
if err != nil {
return nil, err
}
accountKey, err := coinKey.Child(hardened(path.Account))
if err != nil {
return nil, err
}
changeKey, err := accountKey.Child(uint32(path.Change))
if err != nil {
return nil, err
}
indexKey, err := changeKey.Child(uint32(path.Index))
if err != nil {
return nil, err
}
return indexKey, nil
}
func (kf keyFactory) signingMasterKey() (*hdkeychain.ExtendedKey, error) {
masterKey := kf.masterPrivateKey
if masterKey == nil {
return nil, errors.New("missing master private key")
}
childKey, err := masterKey.Child(42)
if err != nil {
return nil, err
}
return childKey, nil
}
func (kf keyFactory) signData(message []byte) ([]byte, error) {
messageHash := chainhash.DoubleHashB(message)
key, err := kf.signingMasterKey()
if err != nil {
return nil, err
}
privKey, err := key.ECPrivKey()
if err != nil {
return nil, err
}
signature, err := privKey.Sign(messageHash)
if err != nil {
return nil, err
}
verified := signature.Verify(messageHash, privKey.PubKey())
if !verified {
return nil, errors.New("failed to sign data")
}
return signature.Serialize(), nil
}
func (kf keyFactory) signatureSigningData(message []byte) (string, error) {
sign, err := kf.signData(message)
if err != nil {
return "", err
}
if len(sign) == 0 {
return "", errors.New("signature is empty")
}
return hex.EncodeToString(sign), nil
}