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 acpIndexCap uint64 // points to end of block
109 accIndexMu sync.Mutex
112 // ExpireReservations removes reservations that have expired periodically.
113 // It blocks until the context is canceled.
114 func (m *Manager) ExpireReservations(ctx context.Context, period time.Duration) {
115 ticks := time.Tick(period)
119 log.Info("Deposed, ExpireReservations exiting")
122 err := m.utxoDB.ExpireReservations(ctx)
124 log.WithField("error", err).Error("Expire reservations")
130 // Account is structure of Bytom account
131 type Account struct {
135 Tags map[string]interface{}
138 func (m *Manager) getNextXpubsIndex(xpubs []chainkd.XPub) uint64 {
140 defer m.accIndexMu.Unlock()
142 var nextIndex uint64 = 1
143 if rawIndexBytes := m.db.Get(indexKeys(xpubs)); rawIndexBytes != nil {
144 nextIndex = convertBytesToUint64(rawIndexBytes) + 1
147 m.db.Set(indexKeys(xpubs), convertUnit64ToBytes(nextIndex))
152 // Create creates a new Account.
153 func (m *Manager) Create(ctx context.Context, xpubs []chainkd.XPub, quorum int, alias string, tags map[string]interface{}) (*Account, error) {
154 if existed := m.db.Get(aliasKey(alias)); existed != nil {
155 return nil, ErrDuplicateAlias
158 nextAccountIndex := m.getNextXpubsIndex(xpubs)
160 signer, err := signers.Create("account", xpubs, quorum, nextAccountIndex)
161 id := signers.IDGenerate()
163 return nil, errors.Wrap(err)
166 account := &Account{Signer: signer, ID: id, Alias: alias, Tags: tags}
167 rawAccount, err := json.Marshal(account)
169 return nil, ErrMarshalAccount
171 storeBatch := m.db.NewBatch()
174 storeBatch.Set(accountID, rawAccount)
175 storeBatch.Set(aliasKey(alias), []byte(id))
181 // UpdateTags modifies the tags of the specified account. The account may be
182 // identified either by ID or Alias, but not both.
183 func (m *Manager) UpdateTags(ctx context.Context, accountInfo string, tags map[string]interface{}) (err error) {
184 account := &Account{}
185 if account, err = m.FindByAlias(nil, accountInfo); err != nil {
186 if account, err = m.findByID(ctx, accountInfo); err != nil {
192 rawAccount, err := json.Marshal(account)
194 return ErrMarshalTags
197 m.db.Set(Key(account.ID), rawAccount)
199 m.cache.Add(account.ID, account)
204 // FindByAlias retrieves an account's Signer record by its alias
205 func (m *Manager) FindByAlias(ctx context.Context, alias string) (*Account, error) {
207 cachedID, ok := m.aliasCache.Get(alias)
210 return m.findByID(ctx, cachedID.(string))
213 rawID := m.db.Get(aliasKey(alias))
215 return nil, ErrFindAccount
218 accountID := string(rawID)
220 m.aliasCache.Add(alias, accountID)
222 return m.findByID(ctx, accountID)
225 // findByID returns an account's Signer record by its ID.
226 func (m *Manager) findByID(ctx context.Context, id string) (*Account, error) {
228 cachedAccount, ok := m.cache.Get(id)
231 return cachedAccount.(*Account), nil
234 rawAccount := m.db.Get(Key(id))
235 if rawAccount == nil {
236 return nil, ErrFindAccount
239 account := &Account{}
240 if err := json.Unmarshal(rawAccount, account); err != nil {
245 m.cache.Add(id, account)
250 // GetAliasByID return the account alias by given ID
251 func (m *Manager) GetAliasByID(id string) string {
252 account := &Account{}
254 rawAccount := m.db.Get(Key(id))
255 if rawAccount == nil {
256 log.Warn("fail to find account")
260 if err := json.Unmarshal(rawAccount, account); err != nil {
267 // CreateAddress generate an address for the select account
268 func (m *Manager) CreateAddress(ctx context.Context, accountID string, change bool) (cp *CtrlProgram, err error) {
269 account, err := m.findByID(ctx, accountID)
273 return m.createAddress(ctx, account, change)
276 // CreateAddress generate an address for the select account
277 func (m *Manager) createAddress(ctx context.Context, account *Account, change bool) (cp *CtrlProgram, err error) {
278 if len(account.XPubs) == 1 {
279 cp, err = m.createP2PKH(ctx, account, change)
281 cp, err = m.createP2SH(ctx, account, change)
287 if err = m.insertAccountControlProgram(ctx, cp); err != nil {
293 func (m *Manager) createP2PKH(ctx context.Context, account *Account, change bool) (*CtrlProgram, error) {
294 idx := m.nextAccountIndex(account)
295 path := signers.Path(account.Signer, signers.AccountKeySpace, idx)
296 derivedXPubs := chainkd.DeriveXPubs(account.XPubs, path)
297 derivedPK := derivedXPubs[0].PublicKey()
298 pubHash := crypto.Ripemd160(derivedPK)
300 // TODO: pass different params due to config
301 address, err := common.NewAddressWitnessPubKeyHash(pubHash, &consensus.MainNetParams)
306 control, err := vmutil.P2WPKHProgram([]byte(pubHash))
312 AccountID: account.ID,
313 Address: address.EncodeAddress(),
315 ControlProgram: control,
320 func (m *Manager) createP2SH(ctx context.Context, account *Account, change bool) (*CtrlProgram, error) {
321 idx := m.nextAccountIndex(account)
322 path := signers.Path(account.Signer, signers.AccountKeySpace, idx)
323 derivedXPubs := chainkd.DeriveXPubs(account.XPubs, path)
324 derivedPKs := chainkd.XPubKeys(derivedXPubs)
325 signScript, err := vmutil.P2SPMultiSigProgram(derivedPKs, account.Quorum)
329 scriptHash := crypto.Sha256(signScript)
331 // TODO: pass different params due to config
332 address, err := common.NewAddressWitnessScriptHash(scriptHash, &consensus.MainNetParams)
337 control, err := vmutil.P2WSHProgram(scriptHash)
343 AccountID: account.ID,
344 Address: address.EncodeAddress(),
346 ControlProgram: control,
351 //CtrlProgram is structure of account control program
352 type CtrlProgram struct {
356 ControlProgram []byte
360 func (m *Manager) insertAccountControlProgram(ctx context.Context, progs ...*CtrlProgram) error {
362 for _, prog := range progs {
363 accountCP, err := json.Marshal(prog)
368 sha3pool.Sum256(hash[:], prog.ControlProgram)
369 m.db.Set(CPKey(hash), accountCP)
374 // IsLocalControlProgram check is the input control program belong to local
375 func (m *Manager) IsLocalControlProgram(prog []byte) bool {
377 sha3pool.Sum256(hash[:], prog)
378 bytes := m.db.Get(CPKey(hash))
382 // GetCoinbaseControlProgram will return a coinbase script
383 func (m *Manager) GetCoinbaseControlProgram() ([]byte, error) {
384 if data := m.db.Get(miningAddressKey); data != nil {
386 return cp.ControlProgram, json.Unmarshal(data, cp)
389 accountIter := m.db.IteratorPrefix([]byte(accountPrefix))
390 defer accountIter.Release()
391 if !accountIter.Next() {
392 log.Warningf("GetCoinbaseControlProgram: can't find any account in db")
393 return vmutil.DefaultCoinbaseProgram()
396 account := &Account{}
397 if err := json.Unmarshal(accountIter.Value(), account); err != nil {
401 program, err := m.createAddress(nil, account, false)
406 rawCP, err := json.Marshal(program)
411 m.db.Set(miningAddressKey, rawCP)
412 return program.ControlProgram, nil
415 func (m *Manager) nextAccountIndex(account *Account) uint64 {
416 return m.getNextXpubsIndex(account.Signer.XPubs)
419 // DeleteAccount deletes the account's ID or alias matching accountInfo.
420 func (m *Manager) DeleteAccount(in struct {
421 AccountInfo string `json:"account_info"`
423 account := &Account{}
424 if account, err = m.FindByAlias(nil, in.AccountInfo); err != nil {
425 if account, err = m.findByID(nil, in.AccountInfo); err != nil {
430 storeBatch := m.db.NewBatch()
433 m.aliasCache.Remove(account.Alias)
436 storeBatch.Delete(aliasKey(account.Alias))
437 storeBatch.Delete(Key(account.ID))
443 // ListAccounts will return the accounts in the db
444 func (m *Manager) ListAccounts(id string) ([]*Account, error) {
445 accounts := []*Account{}
446 accountIter := m.db.IteratorPrefix([]byte(accountPrefix + id))
447 defer accountIter.Release()
449 for accountIter.Next() {
450 account := &Account{}
451 if err := json.Unmarshal(accountIter.Value(), &account); err != nil {
454 accounts = append(accounts, account)
460 // ListControlProgram return all the local control program
461 func (m *Manager) ListControlProgram() ([]*CtrlProgram, error) {
462 cps := []*CtrlProgram{}
463 cpIter := m.db.IteratorPrefix([]byte(accountCPPrefix))
464 defer cpIter.Release()
468 if err := json.Unmarshal(cpIter.Value(), cp); err != nil {
471 cps = append(cps, cp)