This repository has been archived by the owner on Jun 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 53
/
key.go
91 lines (76 loc) · 1.85 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
package main
import (
"encoding/hex"
"fmt"
"log"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/btcutil/bech32"
"github.com/docopt/docopt-go"
"github.com/nbd-wtf/go-nostr/nip06"
"github.com/nbd-wtf/go-nostr/nip19"
)
func decodeKey(keyraw string) ([]byte, error) {
if len(keyraw) == 64 {
// hex-encoded
keyval, err := hex.DecodeString(keyraw)
if err != nil {
return nil, fmt.Errorf("decoding key from hex: %w", err)
}
return keyval, nil
}
// bech32-encoded
_, keyval, err := bech32.Decode(keyraw)
if err != nil {
return nil, err
}
if err != nil {
return nil, fmt.Errorf("decoding key from bech32: %w", err)
}
return keyval, nil
}
func setPrivateKey(opts docopt.Opts) {
keyraw := opts["<key>"].(string)
keyval, err := decodeKey(keyraw)
if err != nil {
log.Printf("Failed to parse private key: %s\n", err.Error())
return
}
config.PrivateKey = string(keyval)
}
func showPublicKey(opts docopt.Opts) {
if config.PrivateKey == "" {
log.Printf("No private key set.\n")
return
}
pubkey := getPubKey(config.PrivateKey)
if pubkey != "" {
fmt.Printf("%s\n", pubkey)
nip19pubkey, _ := nip19.EncodePublicKey(pubkey, "")
fmt.Printf("%s\n", nip19pubkey)
}
}
func getPubKey(privateKey string) string {
if keyb, err := hex.DecodeString(privateKey); err != nil {
log.Printf("Error decoding key from hex: %s\n", err.Error())
return ""
} else {
_, pubkey := btcec.PrivKeyFromBytes(keyb)
return hex.EncodeToString(schnorr.SerializePubKey(pubkey))
}
}
func keyGen(opts docopt.Opts) {
seedWords, err := nip06.GenerateSeedWords()
if err != nil {
log.Println(err)
return
}
seed := nip06.SeedFromWords(seedWords)
sk, err := nip06.PrivateKeyFromSeed(seed)
if err != nil {
log.Println(err)
return
}
fmt.Println("seed:", seedWords)
fmt.Println("private key:", sk)
}