OSDN Git Service

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