-
Notifications
You must be signed in to change notification settings - Fork 202
/
main.go
237 lines (196 loc) · 5.24 KB
/
main.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
package main
import (
"encoding/hex"
"fmt"
"os"
"path/filepath"
"time"
logger "github.com/ElrondNetwork/elrond-go-logger"
"github.com/ElrondNetwork/elrond-go/config"
"github.com/ElrondNetwork/elrond-go/core"
"github.com/ElrondNetwork/elrond-go/crypto"
"github.com/ElrondNetwork/elrond-go/crypto/signing"
"github.com/ElrondNetwork/elrond-go/crypto/signing/ed25519"
"github.com/ElrondNetwork/elrond-go/crypto/signing/mcl"
"github.com/ElrondNetwork/elrond-go/data/state/factory"
"github.com/urfave/cli"
)
type cfg struct {
numKeys int
keyType string
}
const keysFolderPattern = "node-%d"
const blsPubkeyLen = 96
const txSignPubkeyLen = 32
var (
fileGenHelpTemplate = `NAME:
{{.Name}} - {{.Usage}}
USAGE:
{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}
{{if len .Authors}}
AUTHOR:
{{range .Authors}}{{ . }}{{end}}
{{end}}{{if .Commands}}
GLOBAL OPTIONS:
{{range .VisibleFlags}}{{.}}
{{end}}
VERSION:
{{.Version}}
{{end}}
`
// numKeys defines a flag for setting how many keys should generate
numKeys = cli.IntFlag{
Name: "num-keys",
Usage: "How many keys should generate. Example: 1",
Value: 1,
Destination: &argsConfig.numKeys,
}
// keyType defines a flag for setting what keys should generate
keyType = cli.StringFlag{
Name: "key-type",
Usage: "What king of keys should generate. Available options: validator, wallet, both",
Value: "validator",
Destination: &argsConfig.keyType,
}
argsConfig = &cfg{}
walletKeyFileName = "walletKey.pem"
validatorKeyFileName = "validatorKey.pem"
log = logger.GetOrCreate("keygenerator")
)
func main() {
app := cli.NewApp()
cli.AppHelpTemplate = fileGenHelpTemplate
app.Name = "Key generation Tool"
app.Version = "v1.0.0"
app.Usage = "This binary will generate a validatorKey.pem and walletKey.pem, each containing private key(s)"
app.Authors = []cli.Author{
{
Name: "The Elrond Team",
Email: "contact@elrond.com",
},
}
app.Flags = []cli.Flag{
numKeys,
keyType,
}
app.Action = func(_ *cli.Context) error {
return generateAllFiles()
}
err := app.Run(os.Args)
if err != nil {
log.Error("error generating files", "error", err)
os.Exit(1)
}
}
func generateFolder(index int, numKeys int) (string, error) {
absPath, err := os.Getwd()
if err != nil {
return "", err
}
if numKeys > 1 {
absPath = filepath.Join(absPath, fmt.Sprintf(keysFolderPattern, index))
}
log.Info("generating files in", "folder", absPath)
err = os.MkdirAll(absPath, os.ModePerm)
if err != nil {
return "", err
}
return absPath, nil
}
func generateKeys(keyGen crypto.KeyGenerator) ([]byte, []byte, error) {
sk, pk := keyGen.GeneratePair()
skBytes, err := sk.ToByteArray()
if err != nil {
return nil, nil, err
}
pkBytes, err := pk.ToByteArray()
if err != nil {
return nil, nil, err
}
return skBytes, pkBytes, nil
}
func backupFileIfExists(filename string) {
if _, err := os.Stat(filename); err != nil {
if os.IsNotExist(err) {
return
}
}
//if we reached here the file probably exists, make a timestamped backup
_ = os.Rename(filename, filename+"."+fmt.Sprintf("%d", time.Now().Unix()))
}
func generateAllFiles() error {
for i := 0; i < argsConfig.numKeys; i++ {
err := generateOneSetOfFiles(i, argsConfig.numKeys)
if err != nil {
return err
}
}
return nil
}
func generateOneSetOfFiles(index int, numKeys int) error {
switch argsConfig.keyType {
case "validator":
return generateBlockKey(index, numKeys)
case "wallet":
return generateTxKey(index, numKeys)
case "both":
err := generateBlockKey(index, numKeys)
if err != nil {
return err
}
return generateTxKey(index, numKeys)
default:
return fmt.Errorf("unknown key type %s", argsConfig.keyType)
}
}
func generateBlockKey(index int, numKeys int) error {
pubkeyConverter, err := factory.NewPubkeyConverter(
config.PubkeyConfig{
Length: blsPubkeyLen,
Type: factory.HexFormat,
},
)
if err != nil {
return err
}
genForBlockSigningSk := signing.NewKeyGenerator(mcl.NewSuiteBLS12())
return generateAndSave(index, numKeys, validatorKeyFileName, genForBlockSigningSk, pubkeyConverter)
}
func generateTxKey(index int, numKeys int) error {
pubkeyConverter, err := factory.NewPubkeyConverter(
config.PubkeyConfig{
Length: txSignPubkeyLen,
Type: factory.Bech32Format,
},
)
if err != nil {
return err
}
genForBlockSigningSk := signing.NewKeyGenerator(ed25519.NewEd25519())
return generateAndSave(index, numKeys, walletKeyFileName, genForBlockSigningSk, pubkeyConverter)
}
func generateAndSave(index int, numKeys int, baseFilename string, genForBlockSigningSk crypto.KeyGenerator, pubkeyConverter core.PubkeyConverter) error {
folder, err := generateFolder(index, numKeys)
if err != nil {
return err
}
filename := filepath.Join(folder, baseFilename)
backupFileIfExists(filename)
err = os.Remove(filename)
if err != nil && !os.IsNotExist(err) {
return err
}
file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, core.FileModeUserReadWrite)
if err != nil {
return err
}
defer func() {
_ = file.Close()
}()
sk, pk, err := generateKeys(genForBlockSigningSk)
if err != nil {
return err
}
pkString := pubkeyConverter.Encode(pk)
return core.SaveSkToPemFile(file, pkString, []byte(hex.EncodeToString(sk)))
}