-
Notifications
You must be signed in to change notification settings - Fork 9
/
keys.go
64 lines (54 loc) · 1.38 KB
/
keys.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 lightning
import (
"crypto/sha256"
"errors"
"io"
"io/ioutil"
"path/filepath"
"github.com/btcsuite/btcd/btcec/v2"
"golang.org/x/crypto/hkdf"
)
// GetPrivateKey gets the custom key with the parameters that return the node's master key (0 and "nodeid")
func (ln *Client) GetPrivateKey() (sk *btcec.PrivateKey, err error) {
return ln.GetCustomKey(0, "nodeid")
}
// GetCustomKey reads the hsm_secret file in the same directory as the lightning-rpc socket
// (given by Client.Path) and derives the node private key from it.
func (ln *Client) GetCustomKey(
index byte,
label string,
) (sk *btcec.PrivateKey, err error) {
key, err := ln.GetCustomBytes(index, label)
if err != nil {
return nil, err
}
sk, _ = btcec.PrivKeyFromBytes(key)
return
}
func (ln *Client) GetCustomBytes(
index byte,
label string,
) (b []byte, err error) {
if ln.Path == "" {
return nil, errors.New("Path must be set so we know where the lightning folder is.")
}
lightningdir := ln.LightningDir
if lightningdir == "" {
lightningdir = filepath.Dir(ln.Path)
}
hsmsecretpath := filepath.Join(lightningdir, "hsm_secret")
hash := sha256.New
secret, err := ioutil.ReadFile(hsmsecretpath)
if err != nil {
return
}
salt := []byte{index}
info := []byte(label)
hkdf := hkdf.New(hash, secret, salt, info)
b = make([]byte, 32)
_, err = io.ReadFull(hkdf, b)
if err != nil {
return
}
return b, nil
}