-
Notifications
You must be signed in to change notification settings - Fork 44
/
command.go
80 lines (65 loc) · 1.82 KB
/
command.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
package keygen
import (
"encoding/json"
"fmt"
"os"
"github.com/ethereum/go-ethereum/accounts/keystore"
"github.com/ethereum/go-ethereum/crypto"
"github.com/urfave/cli/v2"
"github.com/waku-org/go-waku/waku/v2/utils"
"go.uber.org/zap"
)
// Command generates a key file used to generate the node's peerID, encrypted with an optional password
var Command = cli.Command{
Name: "generate-key",
Usage: "Generate private key file at path specified in --key-file with the password defined by --key-password",
Action: func(cCtx *cli.Context) error {
if err := generateKeyFile(Options.KeyFile, []byte(Options.KeyPasswd), Options.Overwrite); err != nil {
utils.Logger().Fatal("could not write keyfile", zap.Error(err))
}
return nil
},
Flags: []cli.Flag{
KeyFile,
KeyPassword,
Overwrite,
},
}
func checkForFileExistence(path string, overwrite bool) error {
_, err := os.Stat(path)
if err == nil && !overwrite {
return fmt.Errorf("%s already exists. Use --overwrite to overwrite the file", path)
}
if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
return err
}
return nil
}
func generatePrivateKey() ([]byte, error) {
key, err := crypto.GenerateKey()
if err != nil {
return nil, err
}
return key.D.Bytes(), nil
}
func writeKeyFile(path string, key []byte, passwd []byte) error {
encryptedK, err := keystore.EncryptDataV3(key, passwd, keystore.StandardScryptN, keystore.StandardScryptP)
if err != nil {
return err
}
output, err := json.Marshal(encryptedK)
if err != nil {
return err
}
return os.WriteFile(path, output, 0600)
}
func generateKeyFile(path string, passwd []byte, overwrite bool) error {
if err := checkForFileExistence(path, overwrite); err != nil {
return err
}
key, err := generatePrivateKey()
if err != nil {
return err
}
return writeKeyFile(path, key, passwd)
}