OSDN Git Service

Merge pull request #35 from Bytom/dev_dpos_vote_simplification
[bytom/vapor.git] / blockchain / pseudohsm / image.go
1 // Package pseudohsm provides a pseudo HSM for development environments.
2 package pseudohsm
3
4 import (
5         "encoding/json"
6         "io/ioutil"
7         "path/filepath"
8 )
9
10 // KeyImage is the struct for hold export key data
11 type KeyImage struct {
12         XKeys []*encryptedKeyJSON `json:"xkeys"`
13 }
14
15 // Backup export all the HSM keys into array
16 func (h *HSM) Backup() (*KeyImage, error) {
17         image := &KeyImage{}
18         xpubs := h.cache.keys()
19         for _, xpub := range xpubs {
20                 data, err := ioutil.ReadFile(xpub.File)
21                 if err != nil {
22                         return nil, err
23                 }
24
25                 xKey := &encryptedKeyJSON{}
26                 if err := json.Unmarshal(data, xKey); err != nil {
27                         return nil, err
28                 }
29
30                 image.XKeys = append(image.XKeys, xKey)
31         }
32         return image, nil
33 }
34
35 // Restore import the keyImages into HSM
36 func (h *HSM) Restore(image *KeyImage) error {
37         h.cacheMu.Lock()
38         defer h.cacheMu.Unlock()
39
40         for _, xKey := range image.XKeys {
41                 if ok := h.cache.hasAlias(xKey.Alias); ok {
42                         return ErrDuplicateKeyAlias
43                 }
44
45                 rawKey, err := json.Marshal(xKey)
46                 if err != nil {
47                         return err
48                 }
49
50                 _, fileName := filepath.Split(xKey.ID)
51                 file := h.keyStore.JoinPath(keyFileName(fileName))
52                 if err := writeKeyFile(file, rawKey); err != nil {
53                         return err
54                 }
55         }
56         h.cache.maybeReload()
57         return nil
58 }