-
Notifications
You must be signed in to change notification settings - Fork 0
/
nip19.go
59 lines (46 loc) · 1.31 KB
/
nip19.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
package crypto
import (
"encoding/hex"
"fmt"
"github.com/btcsuite/btcd/btcutil/bech32"
)
func DecodeBech32(bech32string string) (prefix string, value any, err error) {
prefix, bits5, err := bech32.DecodeNoLimit(bech32string)
if err != nil {
return "", nil, err
}
data, err := bech32.ConvertBits(bits5, 5, 8, false)
if err != nil {
return prefix, nil, fmt.Errorf("failed translating data into 8 bits: %s", err.Error())
}
switch prefix {
case "npub", "nsec":
if len(data) < 32 {
return prefix, nil, fmt.Errorf("data is less than 32 bytes (%d)", len(data))
}
return prefix, hex.EncodeToString(data[0:32]), nil
}
return prefix, data, fmt.Errorf("unknown tag %s", prefix)
}
func EncodePrivateKey(privateKeyHex string) (string, error) {
b, err := hex.DecodeString(privateKeyHex)
if err != nil {
return "", fmt.Errorf("failed to decode private key hex: %w", err)
}
bits5, err := bech32.ConvertBits(b, 8, 5, true)
if err != nil {
return "", err
}
return bech32.Encode("nsec", bits5)
}
func EncodePublicKey(publicKeyHex string) (string, error) {
b, err := hex.DecodeString(publicKeyHex)
if err != nil {
return "", fmt.Errorf("failed to decode public key hex: %w", err)
}
bits5, err := bech32.ConvertBits(b, 8, 5, true)
if err != nil {
return "", err
}
return bech32.Encode("npub", bits5)
}