1 // Package account stores and tracks accounts within a Chain Core.
13 "github.com/golang/groupcache/lru"
14 log "github.com/sirupsen/logrus"
15 dbm "github.com/tendermint/tmlibs/db"
17 "github.com/bytom/blockchain/signers"
18 "github.com/bytom/blockchain/txbuilder"
19 "github.com/bytom/common"
20 "github.com/bytom/consensus"
21 "github.com/bytom/crypto"
22 "github.com/bytom/crypto/ed25519/chainkd"
23 "github.com/bytom/crypto/sha3pool"
24 "github.com/bytom/errors"
25 "github.com/bytom/protocol"
26 "github.com/bytom/protocol/vm/vmutil"
30 maxAccountCache = 1000
32 accountPrefix = "ACC:"
33 accountCPPrefix = "ACP:"
34 indexPrefix = "ACIDX:"
37 var miningAddressKey = []byte("miningAddress")
39 // pre-define errors for supporting bytom errorFormatter
41 ErrDuplicateAlias = errors.New("duplicate account alias")
42 ErrFindAccount = errors.New("fail to find account")
43 ErrMarshalAccount = errors.New("failed marshal account")
44 ErrMarshalTags = errors.New("failed marshal account to update tags")
47 func aliasKey(name string) []byte {
48 return []byte(aliasPrefix + name)
51 func indexKeys(xpubs []chainkd.XPub) []byte {
52 xpubStrings := make([]string, len(xpubs))
53 for i, xpub := range xpubs {
54 xpubStrings[i] = xpub.String()
56 sort.Strings(xpubStrings)
57 suffix := strings.Join(xpubStrings, "")
59 return []byte(indexPrefix + suffix)
62 //Key account store prefix
63 func Key(name string) []byte {
64 return []byte(accountPrefix + name)
67 //CPKey account control promgram store prefix
68 func CPKey(hash common.Hash) []byte {
69 return append([]byte(accountCPPrefix), hash[:]...)
72 func convertUnit64ToBytes(nextIndex uint64) []byte {
73 buf := make([]byte, 8)
74 binary.PutUvarint(buf, nextIndex)
78 func convertBytesToUint64(rawIndex []byte) uint64 {
79 result, _ := binary.Uvarint(rawIndex)
83 // NewManager creates a new account manager
84 func NewManager(walletDB dbm.DB, chain *protocol.Chain) *Manager {
88 utxoDB: newReserver(chain, walletDB),
89 cache: lru.New(maxAccountCache),
90 aliasCache: lru.New(maxAccountCache),
91 delayedACPs: make(map[*txbuilder.TemplateBuilder][]*CtrlProgram),
95 // Manager stores accounts and their associated control programs.
103 aliasCache *lru.Cache
105 delayedACPsMu sync.Mutex
106 delayedACPs map[*txbuilder.TemplateBuilder][]*CtrlProgram
108 accIndexMu sync.Mutex
111 // ExpireReservations removes reservations that have expired periodically.
112 // It blocks until the context is canceled.
113 func (m *Manager) ExpireReservations(ctx context.Context, period time.Duration) {
114 ticks := time.Tick(period)
118 log.Info("Deposed, ExpireReservations exiting")
121 err := m.utxoDB.ExpireReservations(ctx)
123 log.WithField("error", err).Error("Expire reservations")
129 // Account is structure of Bytom account
130 type Account struct {
134 Tags map[string]interface{}
137 func (m *Manager) getNextXpubsIndex(xpubs []chainkd.XPub) uint64 {
139 defer m.accIndexMu.Unlock()
141 var nextIndex uint64 = 1
142 if rawIndexBytes := m.db.Get(indexKeys(xpubs)); rawIndexBytes != nil {
143 nextIndex = convertBytesToUint64(rawIndexBytes) + 1
146 m.db.Set(indexKeys(xpubs), convertUnit64ToBytes(nextIndex))
151 // Create creates a new Account.
152 func (m *Manager) Create(ctx context.Context, xpubs []chainkd.XPub, quorum int, alias string, tags map[string]interface{}) (*Account, error) {
153 normalizedAlias := strings.ToLower(strings.TrimSpace(alias))
154 if existed := m.db.Get(aliasKey(normalizedAlias)); existed != nil {
155 return nil, ErrDuplicateAlias
158 signer, err := signers.Create("account", xpubs, quorum, m.getNextXpubsIndex(xpubs))
159 id := signers.IDGenerate()
161 return nil, errors.Wrap(err)
164 account := &Account{Signer: signer, ID: id, Alias: normalizedAlias, Tags: tags}
165 rawAccount, err := json.Marshal(account)
167 return nil, ErrMarshalAccount
169 storeBatch := m.db.NewBatch()
172 storeBatch.Set(accountID, rawAccount)
173 storeBatch.Set(aliasKey(alias), []byte(id))
179 // UpdateTags modifies the tags of the specified account. The account may be
180 // identified either by ID or Alias, but not both.
181 func (m *Manager) UpdateTags(ctx context.Context, accountInfo string, tags map[string]interface{}) (err error) {
182 account := &Account{}
183 if account, err = m.FindByAlias(nil, accountInfo); err != nil {
184 if account, err = m.findByID(ctx, accountInfo); err != nil {
190 rawAccount, err := json.Marshal(account)
192 return ErrMarshalTags
195 m.db.Set(Key(account.ID), rawAccount)
197 m.cache.Add(account.ID, account)
202 // FindByAlias retrieves an account's Signer record by its alias
203 func (m *Manager) FindByAlias(ctx context.Context, alias string) (*Account, error) {
205 cachedID, ok := m.aliasCache.Get(alias)
208 return m.findByID(ctx, cachedID.(string))
211 rawID := m.db.Get(aliasKey(alias))
213 return nil, ErrFindAccount
216 accountID := string(rawID)
218 m.aliasCache.Add(alias, accountID)
220 return m.findByID(ctx, accountID)
223 // findByID returns an account's Signer record by its ID.
224 func (m *Manager) findByID(ctx context.Context, id string) (*Account, error) {
226 cachedAccount, ok := m.cache.Get(id)
229 return cachedAccount.(*Account), nil
232 rawAccount := m.db.Get(Key(id))
233 if rawAccount == nil {
234 return nil, ErrFindAccount
237 account := &Account{}
238 if err := json.Unmarshal(rawAccount, account); err != nil {
243 m.cache.Add(id, account)
248 // GetAliasByID return the account alias by given ID
249 func (m *Manager) GetAliasByID(id string) string {
250 account := &Account{}
252 rawAccount := m.db.Get(Key(id))
253 if rawAccount == nil {
254 log.Warn("fail to find account")
258 if err := json.Unmarshal(rawAccount, account); err != nil {
265 // CreateAddress generate an address for the select account
266 func (m *Manager) CreateAddress(ctx context.Context, accountID string) (cp *CtrlProgram, err error) {
267 account, err := m.findByID(ctx, accountID)
271 return m.createAddress(ctx, account)
274 // CreateAddress generate an address for the select account
275 func (m *Manager) createAddress(ctx context.Context, account *Account) (cp *CtrlProgram, err error) {
276 if len(account.XPubs) == 1 {
277 cp, err = m.createP2PKH(ctx, account)
279 cp, err = m.createP2SH(ctx, account)
285 if err = m.insertAccountControlProgram(ctx, cp); err != nil {
291 func (m *Manager) createP2PKH(ctx context.Context, account *Account) (*CtrlProgram, error) {
292 idx := m.getNextXpubsIndex(account.Signer.XPubs)
293 path := signers.Path(account.Signer, signers.AccountKeySpace, idx)
294 derivedXPubs := chainkd.DeriveXPubs(account.XPubs, path)
295 derivedPK := derivedXPubs[0].PublicKey()
296 pubHash := crypto.Ripemd160(derivedPK)
298 // TODO: pass different params due to config
299 address, err := common.NewAddressWitnessPubKeyHash(pubHash, &consensus.MainNetParams)
304 control, err := vmutil.P2WPKHProgram([]byte(pubHash))
310 AccountID: account.ID,
311 Address: address.EncodeAddress(),
313 ControlProgram: control,
317 func (m *Manager) createP2SH(ctx context.Context, account *Account) (*CtrlProgram, error) {
318 idx := m.getNextXpubsIndex(account.Signer.XPubs)
319 path := signers.Path(account.Signer, signers.AccountKeySpace, idx)
320 derivedXPubs := chainkd.DeriveXPubs(account.XPubs, path)
321 derivedPKs := chainkd.XPubKeys(derivedXPubs)
322 signScript, err := vmutil.P2SPMultiSigProgram(derivedPKs, account.Quorum)
326 scriptHash := crypto.Sha256(signScript)
328 // TODO: pass different params due to config
329 address, err := common.NewAddressWitnessScriptHash(scriptHash, &consensus.MainNetParams)
334 control, err := vmutil.P2WSHProgram(scriptHash)
340 AccountID: account.ID,
341 Address: address.EncodeAddress(),
343 ControlProgram: control,
347 //CtrlProgram is structure of account control program
348 type CtrlProgram struct {
352 ControlProgram []byte
355 func (m *Manager) insertAccountControlProgram(ctx context.Context, progs ...*CtrlProgram) error {
357 for _, prog := range progs {
358 accountCP, err := json.Marshal(prog)
363 sha3pool.Sum256(hash[:], prog.ControlProgram)
364 m.db.Set(CPKey(hash), accountCP)
369 // IsLocalControlProgram check is the input control program belong to local
370 func (m *Manager) IsLocalControlProgram(prog []byte) bool {
372 sha3pool.Sum256(hash[:], prog)
373 bytes := m.db.Get(CPKey(hash))
377 // GetCoinbaseControlProgram will return a coinbase script
378 func (m *Manager) GetCoinbaseControlProgram() ([]byte, error) {
379 if data := m.db.Get(miningAddressKey); data != nil {
381 return cp.ControlProgram, json.Unmarshal(data, cp)
384 accountIter := m.db.IteratorPrefix([]byte(accountPrefix))
385 defer accountIter.Release()
386 if !accountIter.Next() {
387 log.Warningf("GetCoinbaseControlProgram: can't find any account in db")
388 return vmutil.DefaultCoinbaseProgram()
391 account := &Account{}
392 if err := json.Unmarshal(accountIter.Value(), account); err != nil {
396 program, err := m.createAddress(nil, account)
401 rawCP, err := json.Marshal(program)
406 m.db.Set(miningAddressKey, rawCP)
407 return program.ControlProgram, nil
410 // DeleteAccount deletes the account's ID or alias matching accountInfo.
411 func (m *Manager) DeleteAccount(in struct {
412 AccountInfo string `json:"account_info"`
414 account := &Account{}
415 if account, err = m.FindByAlias(nil, in.AccountInfo); err != nil {
416 if account, err = m.findByID(nil, in.AccountInfo); err != nil {
421 storeBatch := m.db.NewBatch()
424 m.aliasCache.Remove(account.Alias)
427 storeBatch.Delete(aliasKey(account.Alias))
428 storeBatch.Delete(Key(account.ID))
434 // ListAccounts will return the accounts in the db
435 func (m *Manager) ListAccounts(id string) ([]*Account, error) {
436 accounts := []*Account{}
437 accountIter := m.db.IteratorPrefix([]byte(accountPrefix + id))
438 defer accountIter.Release()
440 for accountIter.Next() {
441 account := &Account{}
442 if err := json.Unmarshal(accountIter.Value(), &account); err != nil {
445 accounts = append(accounts, account)
451 // ListControlProgram return all the local control program
452 func (m *Manager) ListControlProgram() ([]*CtrlProgram, error) {
453 var cps []*CtrlProgram
454 cpIter := m.db.IteratorPrefix([]byte(accountCPPrefix))
455 defer cpIter.Release()
459 if err := json.Unmarshal(cpIter.Value(), cp); err != nil {
462 cps = append(cps, cp)