-
Notifications
You must be signed in to change notification settings - Fork 2
/
key.go
92 lines (79 loc) · 1.84 KB
/
key.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
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"path/filepath"
"github.com/nbd-wtf/go-nostr"
"github.com/urfave/cli/v2"
)
var keyCmd = &cli.Command{
Name: "key",
Usage: "generate, set private key",
Action: keyAction,
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "gen",
Usage: "generate private key",
DisableDefaultText: true,
},
&cli.StringFlag{
Name: "set",
Usage: "set private key",
},
&cli.BoolFlag{
Name: "get",
Usage: "get current public key set",
DisableDefaultText: true,
},
},
}
func keyAction(ctx *cli.Context) error {
if ctx.NumFlags() < 1 {
fmt.Printf("specify flag for 'key' command\n\n")
cli.ShowSubcommandHelp(ctx)
return nil
}
if ctx.IsSet("gen") {
generatePrivateKey()
} else if ctx.IsSet("set") {
savePrivateKey(ctx.String("set"))
} else if ctx.IsSet("get") {
getPubKey()
}
return nil
}
func generatePrivateKey() {
pk := nostr.GeneratePrivateKey()
fmt.Printf("private key: %v\n", pk)
}
func savePrivateKey(key string) {
configPath := getConfigPath()
configFilePath := filepath.Join(configPath, "config.json")
configFile, err := os.OpenFile(configFilePath, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0644)
if err != nil {
log.Fatalf("error opening '%v' file: %v", configFilePath, err)
}
defer configFile.Close()
config := Config{PrivateKey: key}
jsonBytes, err := json.MarshalIndent(config, "", " ")
if err != nil {
log.Fatalf("error saving key: %v\n", err)
}
_, err = configFile.Write(jsonBytes)
if err != nil {
log.Fatalf("error saving key: %v\n", err)
}
}
func getPubKey() {
config := getConfig()
if config == nil || config.PrivateKey == "" {
printErr("key not set")
}
pubkey, err := nostr.GetPublicKey(config.PrivateKey)
if err != nil {
printErr("error getting public key")
}
fmt.Println(pubkey)
}