This repository has been archived by the owner on Mar 21, 2024. It is now read-only.
/
image.go
83 lines (68 loc) · 1.68 KB
/
image.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
// Package pseudohsm provides a pseudo HSM for development environments.
package pseudohsm
import (
"encoding/hex"
"encoding/json"
"io/ioutil"
"path/filepath"
log "github.com/sirupsen/logrus"
"github.com/bytom/bytom/crypto/ed25519/chainkd"
)
const logModule = "pseudohsm"
// KeyImage is the struct for hold export key data
type KeyImage struct {
XKeys []*encryptedKeyJSON `json:"xkeys"`
}
// Backup export all the HSM keys into array
func (h *HSM) Backup() (*KeyImage, error) {
image := &KeyImage{}
xpubs := h.cache.keys()
for _, xpub := range xpubs {
data, err := ioutil.ReadFile(xpub.File)
if err != nil {
return nil, err
}
xKey := &encryptedKeyJSON{}
if err := json.Unmarshal(data, xKey); err != nil {
return nil, err
}
image.XKeys = append(image.XKeys, xKey)
}
return image, nil
}
// Restore import the keyImages into HSM
func (h *HSM) Restore(image *KeyImage) error {
h.cacheMu.Lock()
defer h.cacheMu.Unlock()
for _, xKey := range image.XKeys {
data, err := hex.DecodeString(xKey.XPub)
if err != nil {
return ErrXPubFormat
}
var xPub chainkd.XPub
copy(xPub[:], data)
if h.cache.hasKey(xPub) {
log.WithFields(log.Fields{
"module": logModule,
"alias": xKey.Alias,
"id": xKey.ID,
"xPub": xKey.XPub,
}).Warning("skip restore key due to already existed")
continue
}
if ok := h.cache.hasAlias(xKey.Alias); ok {
return ErrDuplicateKeyAlias
}
rawKey, err := json.Marshal(xKey)
if err != nil {
return err
}
_, fileName := filepath.Split(xKey.ID)
file := h.keyStore.JoinPath(keyFileName(fileName))
if err := writeKeyFile(file, rawKey); err != nil {
return err
}
h.cache.reload()
}
return nil
}