OSDN Git Service

fix for golint
[bytom/bytom-spv.git] / account / image.go
1 // Package account stores and tracks accounts within a Chain Core.
2 package account
3
4 import (
5         "encoding/json"
6
7         "github.com/bytom/common"
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         AccountIndex uint64        `json:"account_index"`
20 }
21
22 // Backup export all the account info into image
23 func (m *Manager) Backup() (*Image, error) {
24         image := &Image{
25                 Slice:        []*ImageSlice{},
26                 AccountIndex: m.getNextAccountIndex(),
27         }
28
29         accountIter := m.db.IteratorPrefix(accountPrefix)
30         defer accountIter.Release()
31         for accountIter.Next() {
32                 a := &Account{}
33                 if err := json.Unmarshal(accountIter.Value(), a); err != nil {
34                         return nil, err
35                 }
36
37                 image.Slice = append(image.Slice, &ImageSlice{
38                         Account:       a,
39                         ContractIndex: m.getNextContractIndex(a.ID),
40                 })
41         }
42         return image, nil
43 }
44
45 // Restore import the accountImages into account manage
46 func (m *Manager) Restore(image *Image) error {
47         storeBatch := m.db.NewBatch()
48         for _, slice := range image.Slice {
49                 if existed := m.db.Get(aliasKey(slice.Account.Alias)); existed != nil {
50                         return ErrDuplicateAlias
51                 }
52
53                 rawAccount, err := json.Marshal(slice.Account)
54                 if err != nil {
55                         return ErrMarshalAccount
56                 }
57
58                 storeBatch.Set(Key(slice.Account.ID), rawAccount)
59                 storeBatch.Set(aliasKey(slice.Account.Alias), []byte(slice.Account.ID))
60                 storeBatch.Set(contractIndexKey(slice.Account.ID), common.Unit64ToBytes(slice.ContractIndex))
61         }
62
63         if localIndex := m.getNextAccountIndex(); localIndex < image.AccountIndex {
64                 storeBatch.Set(accountIndexKey, common.Unit64ToBytes(image.AccountIndex))
65         }
66         storeBatch.Write()
67
68         for _, slice := range image.Slice {
69                 for i := uint64(1); i < slice.ContractIndex; i++ {
70                         if _, err := m.createAddress(nil, slice.Account, false); err != nil {
71                                 return err
72                         }
73                 }
74         }
75         return nil
76 }