forked from scroll-tech/scroll
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeystore.go
45 lines (39 loc) · 1.21 KB
/
keystore.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
package utils
import (
"crypto/ecdsa"
"errors"
"fmt"
"os"
"path/filepath"
"github.com/scroll-tech/go-ethereum/accounts/keystore"
"github.com/scroll-tech/go-ethereum/log"
)
// LoadOrCreateKey load or create keystore by keystorePath, keystorePath cannot be a dir.
func LoadOrCreateKey(keystorePath string, keystorePassword string) (*ecdsa.PrivateKey, error) {
if fi, err := os.Stat(keystorePath); os.IsNotExist(err) {
// If there is no keystore, make a new one.
ks := keystore.NewKeyStore(filepath.Dir(keystorePath), keystore.StandardScryptN, keystore.StandardScryptP)
account, kerr := ks.NewAccount(keystorePassword)
if kerr != nil {
return nil, fmt.Errorf("generate crypto account failed %v", kerr)
}
err = os.Rename(account.URL.Path, keystorePath)
if err != nil {
return nil, err
}
log.Info("create a new account", "address", account.Address.Hex())
} else if err != nil {
return nil, err
} else if fi.IsDir() {
return nil, errors.New("keystorePath cannot be a dir")
}
keyjson, err := os.ReadFile(filepath.Clean(keystorePath))
if err != nil {
return nil, err
}
key, err := keystore.DecryptKey(keyjson, keystorePassword)
if err != nil {
return nil, err
}
return key.PrivateKey, nil
}