1 // Package account stores and tracks accounts within a Chain Core.
11 "github.com/golang/groupcache/lru"
12 log "github.com/sirupsen/logrus"
13 dbm "github.com/tendermint/tmlibs/db"
15 "github.com/bytom/blockchain/signers"
16 "github.com/bytom/blockchain/txbuilder"
17 "github.com/bytom/common"
18 "github.com/bytom/consensus"
19 "github.com/bytom/crypto"
20 "github.com/bytom/crypto/ed25519/chainkd"
21 "github.com/bytom/crypto/sha3pool"
22 "github.com/bytom/errors"
23 "github.com/bytom/protocol"
24 "github.com/bytom/protocol/vm/vmutil"
28 maxAccountCache = 1000
32 accountIndexKey = []byte("AccountIndex")
33 accountPrefix = []byte("Account:")
34 aliasPrefix = []byte("AccountAlias:")
35 contractIndexPrefix = []byte("ContractIndex")
36 contractPrefix = []byte("Contract:")
37 miningAddressKey = []byte("MiningAddress")
40 // pre-define errors for supporting bytom errorFormatter
42 ErrDuplicateAlias = errors.New("duplicate account alias")
43 ErrFindAccount = errors.New("fail to find account")
44 ErrMarshalAccount = errors.New("failed marshal account")
47 func aliasKey(name string) []byte {
48 return append(aliasPrefix, []byte(name)...)
51 // Key account store prefix
52 func Key(name string) []byte {
53 return append(accountPrefix, []byte(name)...)
56 // ContractKey account control promgram store prefix
57 func ContractKey(hash common.Hash) []byte {
58 return append(contractPrefix, hash[:]...)
61 func contractIndexKey(accountID string) []byte {
62 return append(contractIndexPrefix, []byte(accountID)...)
65 // NewManager creates a new account manager
66 func NewManager(walletDB dbm.DB, chain *protocol.Chain) *Manager {
70 utxoDB: newReserver(chain, walletDB),
71 cache: lru.New(maxAccountCache),
72 aliasCache: lru.New(maxAccountCache),
73 delayedACPs: make(map[*txbuilder.TemplateBuilder][]*CtrlProgram),
77 // Manager stores accounts and their associated control programs.
87 delayedACPsMu sync.Mutex
88 delayedACPs map[*txbuilder.TemplateBuilder][]*CtrlProgram
93 // ExpireReservations removes reservations that have expired periodically.
94 // It blocks until the context is canceled.
95 func (m *Manager) ExpireReservations(ctx context.Context, period time.Duration) {
96 ticks := time.Tick(period)
100 log.Info("Deposed, ExpireReservations exiting")
103 err := m.utxoDB.ExpireReservations(ctx)
105 log.WithField("error", err).Error("Expire reservations")
111 // Account is structure of Bytom account
112 type Account struct {
118 func (m *Manager) getNextAccountIndex() uint64 {
120 defer m.accIndexMu.Unlock()
122 var nextIndex uint64 = 1
123 if rawIndexBytes := m.db.Get(accountIndexKey); rawIndexBytes != nil {
124 nextIndex = common.BytesToUnit64(rawIndexBytes) + 1
127 m.db.Set(accountIndexKey, common.Unit64ToBytes(nextIndex))
131 func (m *Manager) getNextContractIndex(accountID string) uint64 {
133 defer m.accIndexMu.Unlock()
135 nextIndex := uint64(1)
136 if rawIndexBytes := m.db.Get(contractIndexKey(accountID)); rawIndexBytes != nil {
137 nextIndex = common.BytesToUnit64(rawIndexBytes) + 1
140 m.db.Set(contractIndexKey(accountID), common.Unit64ToBytes(nextIndex))
144 // Create creates a new Account.
145 func (m *Manager) Create(ctx context.Context, xpubs []chainkd.XPub, quorum int, alias string) (*Account, error) {
146 normalizedAlias := strings.ToLower(strings.TrimSpace(alias))
147 if existed := m.db.Get(aliasKey(normalizedAlias)); existed != nil {
148 return nil, ErrDuplicateAlias
151 signer, err := signers.Create("account", xpubs, quorum, m.getNextAccountIndex())
152 id := signers.IDGenerate()
154 return nil, errors.Wrap(err)
157 account := &Account{Signer: signer, ID: id, Alias: normalizedAlias}
158 rawAccount, err := json.Marshal(account)
160 return nil, ErrMarshalAccount
162 storeBatch := m.db.NewBatch()
165 storeBatch.Set(accountID, rawAccount)
166 storeBatch.Set(aliasKey(alias), []byte(id))
172 // FindByAlias retrieves an account's Signer record by its alias
173 func (m *Manager) FindByAlias(ctx context.Context, alias string) (*Account, error) {
175 cachedID, ok := m.aliasCache.Get(alias)
178 return m.FindByID(ctx, cachedID.(string))
181 rawID := m.db.Get(aliasKey(alias))
183 return nil, ErrFindAccount
186 accountID := string(rawID)
188 m.aliasCache.Add(alias, accountID)
190 return m.FindByID(ctx, accountID)
193 // FindByID returns an account's Signer record by its ID.
194 func (m *Manager) FindByID(ctx context.Context, id string) (*Account, error) {
196 cachedAccount, ok := m.cache.Get(id)
199 return cachedAccount.(*Account), nil
202 rawAccount := m.db.Get(Key(id))
203 if rawAccount == nil {
204 return nil, ErrFindAccount
207 account := &Account{}
208 if err := json.Unmarshal(rawAccount, account); err != nil {
213 m.cache.Add(id, account)
218 // GetAliasByID return the account alias by given ID
219 func (m *Manager) GetAliasByID(id string) string {
220 account := &Account{}
222 rawAccount := m.db.Get(Key(id))
223 if rawAccount == nil {
224 log.Warn("fail to find account")
228 if err := json.Unmarshal(rawAccount, account); err != nil {
235 // CreateAddress generate an address for the select account
236 func (m *Manager) CreateAddress(ctx context.Context, accountID string, change bool) (cp *CtrlProgram, err error) {
237 account, err := m.FindByID(ctx, accountID)
241 return m.createAddress(ctx, account, change)
244 // CreateAddress generate an address for the select account
245 func (m *Manager) createAddress(ctx context.Context, account *Account, change bool) (cp *CtrlProgram, err error) {
246 if len(account.XPubs) == 1 {
247 cp, err = m.createP2PKH(ctx, account, change)
249 cp, err = m.createP2SH(ctx, account, change)
255 if err = m.insertAccountControlProgram(ctx, cp); err != nil {
261 func (m *Manager) createP2PKH(ctx context.Context, account *Account, change bool) (*CtrlProgram, error) {
262 idx := m.getNextContractIndex(account.ID)
263 path := signers.Path(account.Signer, signers.AccountKeySpace, idx)
264 derivedXPubs := chainkd.DeriveXPubs(account.XPubs, path)
265 derivedPK := derivedXPubs[0].PublicKey()
266 pubHash := crypto.Ripemd160(derivedPK)
268 // TODO: pass different params due to config
269 address, err := common.NewAddressWitnessPubKeyHash(pubHash, &consensus.ActiveNetParams)
274 control, err := vmutil.P2WPKHProgram([]byte(pubHash))
280 AccountID: account.ID,
281 Address: address.EncodeAddress(),
283 ControlProgram: control,
288 func (m *Manager) createP2SH(ctx context.Context, account *Account, change bool) (*CtrlProgram, error) {
289 idx := m.getNextContractIndex(account.ID)
290 path := signers.Path(account.Signer, signers.AccountKeySpace, idx)
291 derivedXPubs := chainkd.DeriveXPubs(account.XPubs, path)
292 derivedPKs := chainkd.XPubKeys(derivedXPubs)
293 signScript, err := vmutil.P2SPMultiSigProgram(derivedPKs, account.Quorum)
297 scriptHash := crypto.Sha256(signScript)
299 // TODO: pass different params due to config
300 address, err := common.NewAddressWitnessScriptHash(scriptHash, &consensus.ActiveNetParams)
305 control, err := vmutil.P2WSHProgram(scriptHash)
311 AccountID: account.ID,
312 Address: address.EncodeAddress(),
314 ControlProgram: control,
319 //CtrlProgram is structure of account control program
320 type CtrlProgram struct {
324 ControlProgram []byte
325 Change bool // Mark whether this control program is for UTXO change
328 func (m *Manager) insertAccountControlProgram(ctx context.Context, progs ...*CtrlProgram) error {
330 for _, prog := range progs {
331 accountCP, err := json.Marshal(prog)
336 sha3pool.Sum256(hash[:], prog.ControlProgram)
337 m.db.Set(ContractKey(hash), accountCP)
342 // IsLocalControlProgram check is the input control program belong to local
343 func (m *Manager) IsLocalControlProgram(prog []byte) bool {
345 sha3pool.Sum256(hash[:], prog)
346 bytes := m.db.Get(ContractKey(hash))
350 // GetCoinbaseControlProgram will return a coinbase script
351 func (m *Manager) GetCoinbaseControlProgram() ([]byte, error) {
352 if data := m.db.Get(miningAddressKey); data != nil {
354 return cp.ControlProgram, json.Unmarshal(data, cp)
357 accountIter := m.db.IteratorPrefix([]byte(accountPrefix))
358 defer accountIter.Release()
359 if !accountIter.Next() {
360 log.Warningf("GetCoinbaseControlProgram: can't find any account in db")
361 return vmutil.DefaultCoinbaseProgram()
364 account := &Account{}
365 if err := json.Unmarshal(accountIter.Value(), account); err != nil {
369 program, err := m.createAddress(nil, account, false)
374 rawCP, err := json.Marshal(program)
379 m.db.Set(miningAddressKey, rawCP)
380 return program.ControlProgram, nil
383 // DeleteAccount deletes the account's ID or alias matching accountInfo.
384 func (m *Manager) DeleteAccount(aliasOrID string) (err error) {
385 account := &Account{}
386 if account, err = m.FindByAlias(nil, aliasOrID); err != nil {
387 if account, err = m.FindByID(nil, aliasOrID); err != nil {
392 storeBatch := m.db.NewBatch()
395 m.aliasCache.Remove(account.Alias)
398 storeBatch.Delete(aliasKey(account.Alias))
399 storeBatch.Delete(Key(account.ID))
405 // ListAccounts will return the accounts in the db
406 func (m *Manager) ListAccounts() ([]*Account, error) {
407 accounts := []*Account{}
408 accountIter := m.db.IteratorPrefix(accountPrefix)
409 defer accountIter.Release()
411 for accountIter.Next() {
412 account := &Account{}
413 if err := json.Unmarshal(accountIter.Value(), &account); err != nil {
416 accounts = append(accounts, account)
422 // ListControlProgram return all the local control program
423 func (m *Manager) ListControlProgram() ([]*CtrlProgram, error) {
424 var cps []*CtrlProgram
425 cpIter := m.db.IteratorPrefix(contractPrefix)
426 defer cpIter.Release()
430 if err := json.Unmarshal(cpIter.Value(), cp); err != nil {
433 cps = append(cps, cp)