1 // Package account stores and tracks accounts within a Bytom 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
94 // ExpireReservations removes reservations that have expired periodically.
95 // It blocks until the context is canceled.
96 func (m *Manager) ExpireReservations(ctx context.Context, period time.Duration) {
97 ticks := time.Tick(period)
101 log.Info("Deposed, ExpireReservations exiting")
104 err := m.utxoDB.ExpireReservations(ctx)
106 log.WithField("error", err).Error("Expire reservations")
112 // Account is structure of Bytom account
113 type Account struct {
115 ID string `json:"id"`
116 Alias string `json:"alias"`
119 func (m *Manager) getNextAccountIndex() uint64 {
121 defer m.accIndexMu.Unlock()
123 var nextIndex uint64 = 1
124 if rawIndexBytes := m.db.Get(accountIndexKey); rawIndexBytes != nil {
125 nextIndex = common.BytesToUnit64(rawIndexBytes) + 1
128 m.db.Set(accountIndexKey, common.Unit64ToBytes(nextIndex))
132 func (m *Manager) getNextContractIndex(accountID string) uint64 {
134 defer m.accIndexMu.Unlock()
136 nextIndex := uint64(1)
137 if rawIndexBytes := m.db.Get(contractIndexKey(accountID)); rawIndexBytes != nil {
138 nextIndex = common.BytesToUnit64(rawIndexBytes) + 1
141 m.db.Set(contractIndexKey(accountID), common.Unit64ToBytes(nextIndex))
145 // Create creates a new Account.
146 func (m *Manager) Create(ctx context.Context, xpubs []chainkd.XPub, quorum int, alias string) (*Account, error) {
148 defer m.accountMu.Unlock()
150 normalizedAlias := strings.ToLower(strings.TrimSpace(alias))
151 if existed := m.db.Get(aliasKey(normalizedAlias)); existed != nil {
152 return nil, ErrDuplicateAlias
155 signer, err := signers.Create("account", xpubs, quorum, m.getNextAccountIndex())
156 id := signers.IDGenerate()
158 return nil, errors.Wrap(err)
161 account := &Account{Signer: signer, ID: id, Alias: normalizedAlias}
162 rawAccount, err := json.Marshal(account)
164 return nil, ErrMarshalAccount
166 storeBatch := m.db.NewBatch()
169 storeBatch.Set(accountID, rawAccount)
170 storeBatch.Set(aliasKey(alias), []byte(id))
176 // FindByAlias retrieves an account's Signer record by its alias
177 func (m *Manager) FindByAlias(ctx context.Context, alias string) (*Account, error) {
179 cachedID, ok := m.aliasCache.Get(alias)
182 return m.FindByID(ctx, cachedID.(string))
185 rawID := m.db.Get(aliasKey(alias))
187 return nil, ErrFindAccount
190 accountID := string(rawID)
192 m.aliasCache.Add(alias, accountID)
194 return m.FindByID(ctx, accountID)
197 // FindByID returns an account's Signer record by its ID.
198 func (m *Manager) FindByID(ctx context.Context, id string) (*Account, error) {
200 cachedAccount, ok := m.cache.Get(id)
203 return cachedAccount.(*Account), nil
206 rawAccount := m.db.Get(Key(id))
207 if rawAccount == nil {
208 return nil, ErrFindAccount
211 account := &Account{}
212 if err := json.Unmarshal(rawAccount, account); err != nil {
217 m.cache.Add(id, account)
222 // GetAliasByID return the account alias by given ID
223 func (m *Manager) GetAliasByID(id string) string {
224 account := &Account{}
226 rawAccount := m.db.Get(Key(id))
227 if rawAccount == nil {
228 log.Warn("fail to find account")
232 if err := json.Unmarshal(rawAccount, account); err != nil {
239 // CreateAddress generate an address for the select account
240 func (m *Manager) CreateAddress(ctx context.Context, accountID string, change bool) (cp *CtrlProgram, err error) {
241 account, err := m.FindByID(ctx, accountID)
245 return m.createAddress(ctx, account, change)
248 // CreateAddress generate an address for the select account
249 func (m *Manager) createAddress(ctx context.Context, account *Account, change bool) (cp *CtrlProgram, err error) {
250 if len(account.XPubs) == 1 {
251 cp, err = m.createP2PKH(ctx, account, change)
253 cp, err = m.createP2SH(ctx, account, change)
259 if err = m.insertAccountControlProgram(ctx, cp); err != nil {
265 func (m *Manager) createP2PKH(ctx context.Context, account *Account, change bool) (*CtrlProgram, error) {
266 idx := m.getNextContractIndex(account.ID)
267 path := signers.Path(account.Signer, signers.AccountKeySpace, idx)
268 derivedXPubs := chainkd.DeriveXPubs(account.XPubs, path)
269 derivedPK := derivedXPubs[0].PublicKey()
270 pubHash := crypto.Ripemd160(derivedPK)
272 // TODO: pass different params due to config
273 address, err := common.NewAddressWitnessPubKeyHash(pubHash, &consensus.ActiveNetParams)
278 control, err := vmutil.P2WPKHProgram([]byte(pubHash))
284 AccountID: account.ID,
285 Address: address.EncodeAddress(),
287 ControlProgram: control,
292 func (m *Manager) createP2SH(ctx context.Context, account *Account, change bool) (*CtrlProgram, error) {
293 idx := m.getNextContractIndex(account.ID)
294 path := signers.Path(account.Signer, signers.AccountKeySpace, idx)
295 derivedXPubs := chainkd.DeriveXPubs(account.XPubs, path)
296 derivedPKs := chainkd.XPubKeys(derivedXPubs)
297 signScript, err := vmutil.P2SPMultiSigProgram(derivedPKs, account.Quorum)
301 scriptHash := crypto.Sha256(signScript)
303 // TODO: pass different params due to config
304 address, err := common.NewAddressWitnessScriptHash(scriptHash, &consensus.ActiveNetParams)
309 control, err := vmutil.P2WSHProgram(scriptHash)
315 AccountID: account.ID,
316 Address: address.EncodeAddress(),
318 ControlProgram: control,
323 //CtrlProgram is structure of account control program
324 type CtrlProgram struct {
328 ControlProgram []byte
329 Change bool // Mark whether this control program is for UTXO change
332 func (m *Manager) insertAccountControlProgram(ctx context.Context, progs ...*CtrlProgram) error {
334 for _, prog := range progs {
335 accountCP, err := json.Marshal(prog)
340 sha3pool.Sum256(hash[:], prog.ControlProgram)
341 m.db.Set(ContractKey(hash), accountCP)
346 // IsLocalControlProgram check is the input control program belong to local
347 func (m *Manager) IsLocalControlProgram(prog []byte) bool {
349 sha3pool.Sum256(hash[:], prog)
350 bytes := m.db.Get(ContractKey(hash))
354 // GetCoinbaseControlProgram will return a coinbase script
355 func (m *Manager) GetCoinbaseControlProgram() ([]byte, error) {
356 if data := m.db.Get(miningAddressKey); data != nil {
358 return cp.ControlProgram, json.Unmarshal(data, cp)
361 accountIter := m.db.IteratorPrefix([]byte(accountPrefix))
362 defer accountIter.Release()
363 if !accountIter.Next() {
364 log.Warningf("GetCoinbaseControlProgram: can't find any account in db")
365 return vmutil.DefaultCoinbaseProgram()
368 account := &Account{}
369 if err := json.Unmarshal(accountIter.Value(), account); err != nil {
373 program, err := m.createAddress(nil, account, false)
378 rawCP, err := json.Marshal(program)
383 m.db.Set(miningAddressKey, rawCP)
384 return program.ControlProgram, nil
387 // DeleteAccount deletes the account's ID or alias matching accountInfo.
388 func (m *Manager) DeleteAccount(aliasOrID string) (err error) {
389 account := &Account{}
390 if account, err = m.FindByAlias(nil, aliasOrID); err != nil {
391 if account, err = m.FindByID(nil, aliasOrID); err != nil {
396 storeBatch := m.db.NewBatch()
399 m.aliasCache.Remove(account.Alias)
402 storeBatch.Delete(aliasKey(account.Alias))
403 storeBatch.Delete(Key(account.ID))
409 // ListAccounts will return the accounts in the db
410 func (m *Manager) ListAccounts(id string) ([]*Account, error) {
411 accounts := []*Account{}
412 accountIter := m.db.IteratorPrefix(Key(id))
413 defer accountIter.Release()
415 for accountIter.Next() {
416 account := &Account{}
417 if err := json.Unmarshal(accountIter.Value(), &account); err != nil {
420 accounts = append(accounts, account)
426 // ListControlProgram return all the local control program
427 func (m *Manager) ListControlProgram() ([]*CtrlProgram, error) {
428 var cps []*CtrlProgram
429 cpIter := m.db.IteratorPrefix(contractPrefix)
430 defer cpIter.Release()
434 if err := json.Unmarshal(cpIter.Value(), cp); err != nil {
437 cps = append(cps, cp)