-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathidentity.go
76 lines (59 loc) · 1.49 KB
/
identity.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
package ezlibp2p
import (
"crypto/rand"
"os"
"path/filepath"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p/core/crypto"
)
const DEFAULT_ID_FILE_NAME = "libp2p_id"
//
func PersistentIdentity() (libp2p.Option, error) {
currentDir, err := os.Getwd()
if err != nil {
return nil, err
}
filePath := filepath.Join(currentDir, DEFAULT_ID_FILE_NAME)
return PersistentIdentityFilePath(filePath)
}
func PersistentIdentityFilePath(filePath string) (libp2p.Option, error) {
_, err := os.Stat(filePath)
if err != nil && !os.IsNotExist(err) {
return nil, err
}
if os.IsNotExist(err) {
privKey, _, err := crypto.GenerateEd25519Key(rand.Reader)
if err != nil {
return nil, err
}
err = writePrivateKey(filePath, privKey)
if err != nil {
return nil, err
}
return libp2p.Identity(privKey), nil
}
privKey, err := readPrivateKey(filePath)
if err != nil {
return nil, err
}
return libp2p.Identity(privKey), nil
}
func readPrivateKey(fileName string) (crypto.PrivKey, error) {
keyStringBytes, err := os.ReadFile(fileName)
if err != nil {
return nil, err
}
keyBytes, err := crypto.ConfigDecodeKey(string(keyStringBytes))
if err != nil {
return nil, err
}
return crypto.UnmarshalPrivateKey(keyBytes)
}
func writePrivateKey(fileName string, key crypto.PrivKey) error {
keyBytes, err := crypto.MarshalPrivateKey(key)
if err != nil {
return err
}
keyString := crypto.ConfigEncodeKey(keyBytes)
return os.WriteFile(fileName, []byte(keyString), os.ModePerm)
}