OSDN Git Service

init push for backup wallet
[bytom/bytom.git] / blockchain / pseudohsm / image.go
1 // Package pseudohsm provides a pseudo HSM for development environments.
2 package pseudohsm
3
4 import (
5         "io/ioutil"
6         "path/filepath"
7 )
8
9 type KeyImage struct {
10         XPub XPub   `json:"xpub"`
11         XKey []byte `json:"xkey"`
12 }
13
14 func (h *HSM) Backup() ([]*KeyImage, error) {
15         images := []*KeyImage{}
16         xpubs := h.cache.keys()
17         for _, xpub := range xpubs {
18                 xKey, err := ioutil.ReadFile(xpub.File)
19                 if err != nil {
20                         return nil, err
21                 }
22
23                 images = append(images, &KeyImage{XPub: xpub, XKey: xKey})
24         }
25         return images, nil
26 }
27
28 func (h *HSM) Restore(images []*KeyImage) error {
29         for _, image := range images {
30                 if ok := h.cache.hasAlias(image.XPub.Alias); ok {
31                         return ErrDuplicateKeyAlias
32                 }
33
34                 fileName := filepath.Base(image.XPub.File)
35                 image.XPub.File = h.keyStore.JoinPath(fileName)
36                 if err := writeKeyFile(image.XPub.File, image.XKey); err != nil {
37                         return nil
38                 }
39                 h.cache.add(image.XPub)
40         }
41         return nil
42 }