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 // pre-define errors for supporting bytom errorFormatter
39 ErrDuplicateAlias = errors.New("duplicate account alias")
40 ErrFindAccount = errors.New("fail to find account")
41 ErrMarshalAccount = errors.New("failed marshal account")
42 ErrMarshalTags = errors.New("failed marshal account to update tags")
45 func aliasKey(name string) []byte {
46 return []byte(aliasPrefix + name)
49 func indexKeys(xpubs []chainkd.XPub) []byte {
50 xpubStrings := make([]string, len(xpubs))
51 for i, xpub := range xpubs {
52 xpubStrings[i] = xpub.String()
54 sort.Strings(xpubStrings)
55 suffix := strings.Join(xpubStrings, "")
57 return []byte(indexPrefix + suffix)
60 //Key account store prefix
61 func Key(name string) []byte {
62 return []byte(accountPrefix + name)
65 //CPKey account control promgram store prefix
66 func CPKey(hash common.Hash) []byte {
67 return append([]byte(accountCPPrefix), hash[:]...)
70 func convertUnit64ToBytes(nextIndex uint64) []byte {
71 buf := make([]byte, 8)
72 binary.PutUvarint(buf, nextIndex)
76 func convertBytesToUint64(rawIndex []byte) uint64 {
77 result, _ := binary.Uvarint(rawIndex)
81 // NewManager creates a new account manager
82 func NewManager(walletDB dbm.DB, chain *protocol.Chain) *Manager {
86 utxoDB: newReserver(chain, walletDB),
87 cache: lru.New(maxAccountCache),
88 aliasCache: lru.New(maxAccountCache),
89 delayedACPs: make(map[*txbuilder.TemplateBuilder][]*CtrlProgram),
93 // Manager stores accounts and their associated control programs.
101 aliasCache *lru.Cache
103 delayedACPsMu sync.Mutex
104 delayedACPs map[*txbuilder.TemplateBuilder][]*CtrlProgram
106 acpIndexCap uint64 // points to end of block
107 accIndexMu sync.Mutex
110 // ExpireReservations removes reservations that have expired periodically.
111 // It blocks until the context is canceled.
112 func (m *Manager) ExpireReservations(ctx context.Context, period time.Duration) {
113 ticks := time.Tick(period)
117 log.Info("Deposed, ExpireReservations exiting")
120 err := m.utxoDB.ExpireReservations(ctx)
122 log.WithField("error", err).Error("Expire reservations")
128 // Account is structure of Bytom account
129 type Account struct {
133 Tags map[string]interface{}
136 func (m *Manager) getNextXpubsIndex(xpubs []chainkd.XPub) uint64 {
138 defer m.accIndexMu.Unlock()
140 var nextIndex uint64 = 1
141 if rawIndexBytes := m.db.Get(indexKeys(xpubs)); rawIndexBytes != nil {
142 nextIndex = convertBytesToUint64(rawIndexBytes) + 1
145 m.db.Set(indexKeys(xpubs), convertUnit64ToBytes(nextIndex))
150 // Create creates a new Account.
151 func (m *Manager) Create(ctx context.Context, xpubs []chainkd.XPub, quorum int, alias string, tags map[string]interface{}) (*Account, error) {
152 if existed := m.db.Get(aliasKey(alias)); existed != nil {
153 return nil, ErrDuplicateAlias
156 nextAccountIndex := m.getNextXpubsIndex(xpubs)
158 signer, err := signers.Create("account", xpubs, quorum, nextAccountIndex)
159 id := signers.IDGenerate()
161 return nil, errors.Wrap(err)
164 account := &Account{Signer: signer, ID: id, Alias: alias, 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, change bool) (cp *CtrlProgram, err error) {
267 account, err := m.findByID(ctx, accountID)
271 return m.createAddress(ctx, account, change)
274 // CreateAddress generate an address for the select account
275 func (m *Manager) createAddress(ctx context.Context, account *Account, change bool) (cp *CtrlProgram, err error) {
276 if len(account.XPubs) == 1 {
277 cp, err = m.createP2PKH(ctx, account, change)
279 cp, err = m.createP2SH(ctx, account, change)
285 if err = m.insertAccountControlProgram(ctx, cp); err != nil {
291 func (m *Manager) createP2PKH(ctx context.Context, account *Account, change bool) (*CtrlProgram, error) {
292 idx := m.nextAccountIndex(account)
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,
318 func (m *Manager) createP2SH(ctx context.Context, account *Account, change bool) (*CtrlProgram, error) {
319 idx := m.nextAccountIndex(account)
320 path := signers.Path(account.Signer, signers.AccountKeySpace, idx)
321 derivedXPubs := chainkd.DeriveXPubs(account.XPubs, path)
322 derivedPKs := chainkd.XPubKeys(derivedXPubs)
323 signScript, err := vmutil.P2SPMultiSigProgram(derivedPKs, account.Quorum)
327 scriptHash := crypto.Sha256(signScript)
329 // TODO: pass different params due to config
330 address, err := common.NewAddressWitnessScriptHash(scriptHash, &consensus.MainNetParams)
335 control, err := vmutil.P2WSHProgram(scriptHash)
341 AccountID: account.ID,
342 Address: address.EncodeAddress(),
344 ControlProgram: control,
349 //CtrlProgram is structure of account control program
350 type CtrlProgram struct {
354 ControlProgram []byte
358 func (m *Manager) insertAccountControlProgram(ctx context.Context, progs ...*CtrlProgram) error {
360 for _, prog := range progs {
361 accountCP, err := json.Marshal(prog)
366 sha3pool.Sum256(hash[:], prog.ControlProgram)
367 m.db.Set(CPKey(hash), accountCP)
372 // IsLocalControlProgram check is the input control program belong to local
373 func (m *Manager) IsLocalControlProgram(prog []byte) bool {
375 sha3pool.Sum256(hash[:], prog)
376 bytes := m.db.Get(CPKey(hash))
380 // GetCoinbaseControlProgram will return a coinbase script
381 func (m *Manager) GetCoinbaseControlProgram() ([]byte, error) {
382 accountIter := m.db.IteratorPrefix([]byte(accountPrefix))
383 defer accountIter.Release()
384 if !accountIter.Next() {
385 log.Warningf("GetCoinbaseControlProgram: can't find any account in db")
386 return vmutil.DefaultCoinbaseProgram()
388 rawAccount := accountIter.Value()
390 account := &Account{}
391 if err := json.Unmarshal(rawAccount, account); err != nil {
395 program, err := m.createAddress(nil, account, false)
399 return program.ControlProgram, nil
402 func (m *Manager) nextAccountIndex(account *Account) uint64 {
403 return m.getNextXpubsIndex(account.Signer.XPubs)
406 // DeleteAccount deletes the account's ID or alias matching accountInfo.
407 func (m *Manager) DeleteAccount(in struct {
408 AccountInfo string `json:"account_info"`
410 account := &Account{}
411 if account, err = m.FindByAlias(nil, in.AccountInfo); err != nil {
412 if account, err = m.findByID(nil, in.AccountInfo); err != nil {
417 storeBatch := m.db.NewBatch()
420 m.aliasCache.Remove(account.Alias)
423 storeBatch.Delete(aliasKey(account.Alias))
424 storeBatch.Delete(Key(account.ID))
430 // ListAccounts will return the accounts in the db
431 func (m *Manager) ListAccounts(id string) ([]*Account, error) {
432 accounts := []*Account{}
433 accountIter := m.db.IteratorPrefix([]byte(accountPrefix + id))
434 defer accountIter.Release()
436 for accountIter.Next() {
437 account := &Account{}
438 if err := json.Unmarshal(accountIter.Value(), &account); err != nil {
441 accounts = append(accounts, account)
447 // ListControlProgram return all the local control program
448 func (m *Manager) ListControlProgram() ([]*CtrlProgram, error) {
449 cps := []*CtrlProgram{}
450 cpIter := m.db.IteratorPrefix([]byte(accountCPPrefix))
451 defer cpIter.Release()
455 if err := json.Unmarshal(cpIter.Value(), cp); err != nil {
458 cps = append(cps, cp)