-
Notifications
You must be signed in to change notification settings - Fork 55
/
privkey.go
80 lines (64 loc) · 2.22 KB
/
privkey.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
package app
import (
"os"
"github.com/omni-network/omni/lib/errors"
"github.com/cometbft/cometbft/crypto"
cmtjson "github.com/cometbft/cometbft/libs/json"
"github.com/cometbft/cometbft/privval"
)
// loadPrivVal returns a privval.FilePV by loading either a CometBFT priv validator key or an Ethereum keystore file.
func loadPrivVal(cfg Config) (*privval.FilePV, error) {
cmtFile := cfg.Comet.PrivValidatorKeyFile()
cmtExists := exists(cmtFile)
if !cmtExists {
return nil, errors.New("cometBFT priv validator key file is required", "comet_file", cmtFile)
}
key, err := LoadCometFilePV(cmtFile)
if err != nil {
return nil, err
}
state, err := loadCometPVState(cfg.Comet.PrivValidatorStateFile())
if err != nil {
return nil, err
}
// Create a new privval.FilePV with the loaded key and state.
// This is a workaround for the fact that there is no other way
// to set FilePVLastSignState filePath field.
resp := privval.NewFilePV(key, "", cfg.Comet.PrivValidatorStateFile())
resp.LastSignState.Step = state.Step
resp.LastSignState.Round = state.Round
resp.LastSignState.Height = state.Height
resp.LastSignState.Signature = state.Signature
resp.LastSignState.SignBytes = state.SignBytes
return resp, nil
}
// LoadCometFilePV loads a CometBFT privval file and returns the private key.
func LoadCometFilePV(file string) (crypto.PrivKey, error) {
bz, err := os.ReadFile(file)
if err != nil {
return nil, errors.Wrap(err, "read comet privval", "path", file)
}
var pvKey privval.FilePVKey
err = cmtjson.Unmarshal(bz, &pvKey)
if err != nil {
return nil, errors.Wrap(err, "unmarshal comet privval", "path", file)
}
return pvKey.PrivKey, nil
}
// loadCometPVState loads a CometBFT privval state file.
func loadCometPVState(file string) (privval.FilePVLastSignState, error) {
bz, err := os.ReadFile(file)
if err != nil {
return privval.FilePVLastSignState{}, errors.Wrap(err, "read comet privval state", "path", file)
}
var state privval.FilePVLastSignState
err = cmtjson.Unmarshal(bz, &state)
if err != nil {
return privval.FilePVLastSignState{}, errors.Wrap(err, "unmarshal comet privval state", "path", file)
}
return state, nil
}
func exists(file string) bool {
_, err := os.Stat(file)
return !os.IsNotExist(err)
}