OSDN Git Service

writer close
[bytom/vapor.git] / account / image.go
1 // Package account stores and tracks accounts within a Bytom Core.
2 package account
3
4 import (
5         log "github.com/sirupsen/logrus"
6 )
7
8 // ImageSlice record info of single account
9 type ImageSlice struct {
10         Account       *Account `json:"account"`
11         ContractIndex uint64   `json:"contract_index"`
12 }
13
14 // Image is the struct for hold export account data
15 type Image struct {
16         Slice []*ImageSlice `json:"slices"`
17 }
18
19 // Backup export all the account info into image
20 func (m *Manager) Backup() (*Image, error) {
21         m.accountMu.Lock()
22         defer m.accountMu.Unlock()
23
24         image := &Image{
25                 Slice: []*ImageSlice{},
26         }
27
28         accounts, err := m.store.ListAccounts("")
29         if err != nil {
30                 return nil, err
31         }
32
33         for _, account := range accounts {
34                 image.Slice = append(image.Slice, &ImageSlice{
35                         Account:       account,
36                         ContractIndex: m.store.GetContractIndex(account.ID),
37                 })
38         }
39         return image, nil
40 }
41
42 // Restore import the accountImages into account manage
43 func (m *Manager) Restore(image *Image) error {
44         m.accountMu.Lock()
45         defer m.accountMu.Unlock()
46
47         newStore := m.store.InitBatch()
48
49         for _, slice := range image.Slice {
50                 if _, err := newStore.GetAccountByID(slice.Account.ID); err == nil {
51                         log.WithFields(log.Fields{
52                                 "module": logModule,
53                                 "alias":  slice.Account.Alias,
54                                 "id":     slice.Account.ID,
55                         }).Warning("skip restore account due to already existed")
56                         continue
57                 } else if err != ErrFindAccount {
58                         return err
59                 }
60
61                 if _, err := newStore.GetAccountByAlias(slice.Account.Alias); err == nil {
62                         return ErrDuplicateAlias
63                 } else if err != ErrFindAccount {
64                         return err
65                 }
66
67                 if err := newStore.SetAccount(slice.Account); err != nil {
68                         return err
69                 }
70         }
71
72         return newStore.CommitBatch()
73 }