-
Notifications
You must be signed in to change notification settings - Fork 2
/
account.go
118 lines (94 loc) · 2.43 KB
/
account.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package types
import (
"github.com/ProtoconNet/mitum-currency/v3/common"
"github.com/ProtoconNet/mitum2/base"
"github.com/ProtoconNet/mitum2/util"
"github.com/ProtoconNet/mitum2/util/hint"
"github.com/ProtoconNet/mitum2/util/valuehash"
"github.com/pkg/errors"
)
var (
AccountHint = hint.MustNewHint("mitum-currency-account-v0.0.1")
)
type Account struct {
hint.BaseHinter
h util.Hash
address base.Address
keys AccountKeys
}
func NewAccount(address base.Address, keys AccountKeys) (Account, error) {
if address == nil {
return Account{}, common.ErrValueInvalid.Wrap(errors.Errorf("address is nil"))
} else if err := address.IsValid(nil); err != nil {
return Account{}, err
}
// keys can be nil (zero account)
if keys != nil {
if err := keys.IsValid(nil); err != nil {
return Account{}, err
}
}
ac := Account{BaseHinter: hint.NewBaseHinter(AccountHint), address: address, keys: keys}
ac.h = ac.GenerateHash()
return ac, nil
}
func NewAccountFromKeys(keys AccountKeys) (Account, error) {
if a, err := NewAddressFromKeys(keys); err != nil {
return Account{}, err
} else if ac, err := NewAccount(a, keys); err != nil {
return Account{}, err
} else {
return ac, nil
}
}
func NewEthAccountFromKeys(keys AccountKeys) (Account, error) {
if a, err := NewEthAddressFromKeys(keys); err != nil {
return Account{}, err
} else if ac, err := NewAccount(a, keys); err != nil {
return Account{}, err
} else {
return ac, nil
}
}
func (ac Account) Bytes() []byte {
bs := make([][]byte, 2)
bs[0] = ac.address.Bytes()
if ac.keys != nil {
bs[1] = ac.keys.Bytes()
}
return util.ConcatBytesSlice(bs...)
}
func (ac Account) Hash() util.Hash {
return ac.h
}
func (ac Account) IsValid([]byte) error {
if err := ac.BaseHinter.IsValid(nil); err != nil {
return err
}
if err := util.CheckIsValiders(nil, false, ac.address); err != nil {
return err
}
if err := util.CheckIsValiders(nil, true, ac.keys); err != nil {
return err
}
return nil
}
func (ac Account) GenerateHash() util.Hash {
return valuehash.NewSHA256(ac.Bytes())
}
func (ac Account) Address() base.Address {
return ac.address
}
func (ac Account) Keys() AccountKeys {
return ac.keys
}
func (ac Account) SetKeys(keys AccountKeys) (Account, error) {
if err := keys.IsValid(nil); err != nil {
return Account{}, err
}
ac.keys = keys
return ac, nil
}
func ZeroAccount(cid CurrencyID) (Account, error) {
return NewAccount(ZeroAddress(cid), nil)
}